Keys, TTL, Collections and the View Decisions

Article · 9:00

Query-first modelling as carried over, TTL and collections, and an honest evaluation of global secondary indexes and materialized views in this engine.

Everything from the Cassandra modelling module applies: enumerate the queries, build one table per query, denormalise, bound the partition with a bucket, choose the clustering order from the dominant query, keep collections small and bounded, and remember that a TTL writes a tombstone. None of that changes, and this module does not re-teach it.

What is worth examining here is the thing Cassandra tells you to avoid and ScyllaDB improves: secondary indexes and materialized views.

Secondary indexes in ScyllaDB are global, not local. In Cassandra a standard index is local to each node, so a query using it must contact every node - a scatter-gather. ScyllaDB implements a secondary index as a hidden materialized view whose partition key is the indexed column, which means a lookup goes to the node owning that value rather than to all of them. That is a genuine architectural improvement and it changes the advice: a global secondary index is a reasonable tool here for a moderate-cardinality lookup, where in Cassandra it rarely is.

It is still not free, and the honest limits are:

  • Two hops. The index lookup finds the base table's primary key, then the base row is fetched - so a read costs two round trips, not one.
  • Write amplification. Every write to an indexed column writes the index view too.
  • Eventual consistency between base and view. The index is updated asynchronously, so a read immediately after a write may not find it through the index.
  • High-cardinality columns make an index whose partitions are tiny and numerous; low-cardinality columns make an index with enormous partitions, which is the same unbounded-partition problem in a different place. A local secondary index - indexed within the base partition key - avoids both and is the right choice when the query also constrains the partition key.

Materialized views are the explicit form of the same mechanism, and ScyllaDB's implementation is more complete than Cassandra's. A view is a table maintained by the database with a different primary key, which is exactly the denormalised table you would otherwise write by hand. The trade against hand-written tables: the database maintains it (so no divergence from a half-failed application write) at the cost of write-path work you do not control and a base-to-view consistency that is eventual.

The practical guidance for this course: hand-written tables remain the default because they are explicit and their cost is visible; a materialized view is a reasonable choice when the alternative is a second write path you would have to keep correct yourself, and you should measure the write amplification either way.

Laboratory exercise 2 - two models, measured.

Write the query list for the capstone's game event store - at least eight queries, numbered.

Design two schemas serving it: one strictly query-first with hand-written tables per query (the Cassandra approach), and one using global secondary indexes and materialized views for the secondary access patterns.

Implement both. Implement every query in both. Measure each query in both models: p50, p95, p99, and the number of round trips - the index's two-hop cost should be plainly visible.

Measure the write amplification: write one event in each model and record the actual writes per shard from the metrics, plus the disk used.

Measure the base-to-view lag: write a row, then query it through the index in a tight loop, and record how long until it appears. Do this under load and at idle, and record both.

Then measure index cardinality: build an index on a high-cardinality column and one on a low-cardinality column, and compare the resulting partition size distributions. Show the low-cardinality one producing an unbounded partition.

Finally, build a local secondary index and compare it with the global one for a query that constrains the partition key.

Deliverable: the numbered query list, both schemas, every query in both with latency and round-trip counts, the write amplification per shard, the base-to-view lag at idle and under load, the cardinality comparison with partition sizes, the local-against-global comparison, and a page arguing for one model.

-- ==================================================================
-- Everything from the Cassandra modelling module applies. Unchanged.
-- ==================================================================
--   enumerate the queries -> one table per query -> denormalise
--   -> bound the partition with a bucket -> clustering order from
--   the dominant query -> small bounded collections -> a TTL writes
--   a tombstone -> TWCS for TTL time-series
--
-- This module does not re-teach that. It examines the one thing
-- Cassandra tells you to avoid and ScyllaDB genuinely improves.

-- ==================================================================
-- SECONDARY INDEXES HERE ARE *GLOBAL*. A real improvement.
-- ==================================================================
-- In Cassandra a standard index is LOCAL TO EACH NODE, so a query
-- using it contacts EVERY node. ScyllaDB implements a secondary
-- index as a HIDDEN MATERIALIZED VIEW whose partition key is the
-- INDEXED COLUMN - so a lookup goes to the node owning that VALUE.

CREATE TABLE players (
    player_id uuid PRIMARY KEY,
    username  text,
    email     text,
    region    text,
    tier      text,
    last_seen timestamp
);

CREATE INDEX players_by_email ON players (email);
SELECT * FROM players WHERE email = 'ada@example.test';
--   ONE node, not all of them. In Cassandra this would be a
--   cluster-wide scatter-gather. So the ADVICE CHANGES: a global
--   secondary index is a reasonable tool here for a moderate-
--   cardinality lookup, where in Cassandra it rarely is.

-- *** AND IT IS STILL NOT FREE. The four honest limits: ***
--
-- 1. TWO HOPS. The index lookup finds the base PRIMARY KEY, then the
--    base row is fetched. A read costs TWO round trips, not one.
--    Measure it against a hand-written table: the difference is the
--    second hop, every time.
--
-- 2. WRITE AMPLIFICATION. Every write to an indexed column writes
--    the index view too.
--
-- 3. BASE-TO-VIEW CONSISTENCY IS EVENTUAL. The index is updated
--    ASYNCHRONOUSLY, so a read immediately after a write MAY NOT
--    FIND IT through the index.
--      INSERT INTO players (player_id, email) VALUES (uuid(), 'x@y.z');
--      SELECT * FROM players WHERE email = 'x@y.z';   -- may be EMPTY
--    Measure the lag at idle AND under load. Under load it is
--    larger, which is exactly when your code will meet it.
--
-- 4. CARDINALITY CUTS BOTH WAYS:
--      HIGH cardinality (email)  -> many tiny index partitions. Fine.
--      LOW cardinality (region)  -> ENORMOUS index partitions. The
--         same unbounded-partition problem, relocated.
CREATE INDEX players_by_region ON players (region);   -- 5 regions
--   5,000,000 players / 5 regions = 1,000,000 ROWS PER INDEX
--   PARTITION. That is the Cassandra partition-size rule being
--   broken by an index you created in one line. Demonstrate it:
--     nodetool tablehistograms game.players_by_region_index

-- LOCAL secondary index: indexed WITHIN the base partition key.
-- Avoids both problems, and is right when the query ALSO constrains
-- the partition key:
CREATE INDEX ON events_by_player_hour ((player_id, day, hour), kind);
SELECT * FROM events_by_player_hour
WHERE player_id = 7f3c... AND day = '2026-11-30' AND hour = 14
  AND kind = 'levelup';
--   ONE partition, ONE shard, no second hop to another node. This is
--   usually the right index in this engine.

DESC INDEX players_by_email;
SELECT * FROM system_schema.indexes WHERE keyspace_name = 'game';

-- ==================================================================
-- MATERIALIZED VIEWS: the explicit form of the same mechanism.
-- ==================================================================
CREATE MATERIALIZED VIEW events_by_kind_hour AS
  SELECT player_id, day, hour, event_at, event_id, kind, payload
  FROM events_by_player_hour
  WHERE kind IS NOT NULL AND player_id IS NOT NULL
    AND day IS NOT NULL AND hour IS NOT NULL
    AND event_at IS NOT NULL AND event_id IS NOT NULL
  PRIMARY KEY ((kind, day, hour), player_id, event_at, event_id)
  WITH CLUSTERING ORDER BY (player_id ASC, event_at DESC, event_id DESC);
--   Every component of the BASE primary key must appear in the
--   view's key, and every key column must be NOT NULL.

SELECT * FROM events_by_kind_hour
WHERE kind = 'levelup' AND day = '2026-11-30' AND hour = 14 LIMIT 50;

-- THE TRADE, against a hand-written table:
--   FOR THE VIEW:   the DATABASE maintains it, so there is NO
--                   DIVERGENCE from a half-failed application write -
--                   which is the bug the Cassandra course warns about
--   AGAINST:        write-path work you do not control, a
--                   base-to-view consistency that is EVENTUAL, and
--                   a view you cannot repair independently
--
-- THIS COURSE'S GUIDANCE: hand-written tables remain the DEFAULT,
-- because they are explicit and their cost is visible. A
-- materialized view is a reasonable choice when the alternative is a
-- SECOND WRITE PATH YOU WOULD HAVE TO KEEP CORRECT YOURSELF - and
-- you should MEASURE THE WRITE AMPLIFICATION EITHER WAY.

-- Measuring the amplification, per shard - this is the deliverable:
--   curl -s http://localhost:9180/metrics | grep -E \
--     'scylla_database_total_writes|scylla_database_total_writes_failed'
--   write one event, read the counters before and after, PER SHARD.
--   A hand-written 3-table design and a 1-table-plus-2-views design
--   do the same work; the question is who you want writing it and
--   whether you can see the cost.

-- ==================================================================
-- TTL and collections: as Cassandra, with the same costs.
-- ==================================================================
INSERT INTO events_by_player_hour
  (player_id, day, hour, event_at, event_id, kind, payload)
VALUES (7f3c..., '2026-11-30', 14, '2026-11-30 14:04:00+0000',
        now(), 'levelup', '{"level":42}')
USING TTL 604800;
SELECT TTL(payload), WRITETIME(payload) FROM events_by_player_hour
WHERE player_id = 7f3c... AND day = '2026-11-30' AND hour = 14 LIMIT 1;

--   A TTL expiry writes a tombstone -> TWCS, so the whole window is
--   dropped without compaction.
--   A collection element update writes a tombstone -> keep them
--   small and bounded, or use a table with a clustering column.
--   Binding NULL in a prepared statement writes a tombstone -> use
--   `unset`.
-- All three are Cassandra lessons, and all three are still true.

Discussion

No questions on this topic yet. Sign in to ask the first one.