The method, and the order is not negotiable:
- List the queries. In a file, numbered, in plain language.
- For each query, design a table whose partition key is exactly what that query constrains, and whose clustering columns give the order it needs.
- Accept that the same data appears in several tables.
- Decide how the copies stay consistent, and write that down.
Step 3 is the one people resist. In Cassandra, a schema with five tables holding the same data five ways is correct, not a failure of normalisation. Disk is cheap, writes are cheap, and a query that reads one partition is the only query shape that scales. You are trading storage and write amplification for read predictability, deliberately.
Step 4 is the one people skip, and it is where the bugs are. If events_by_user and events_by_kind hold the same event, something must write both. The honest options: write both in the application (simple, and a partial failure leaves them divergent); write both in a logged batch (atomic in the sense that it will eventually complete, with a cost - see Module 3); or use a materialized view (maintained by Cassandra, and with known limitations that mean many operators avoid them in production). Choose, state it, and have a repair procedure for divergence.
Clustering order is a schema decision with a disk consequence. CLUSTERING ORDER BY (event_at DESC) stores the rows in that order, so "most recent 50" is a sequential read from the start of the partition. Defining it ascending and querying ORDER BY event_at DESC works and reads backwards, which is measurably slower. Decide from the dominant query.
Collections - set, list, map - are convenient and have real costs. They are read in their entirety, they have a recommended limit of a few hundred elements, and - the important part - updating a collection element writes a tombstone. A list is worse than a set or map because an append reads the existing list in some operations and index-based updates are read-before-write. The guidance: small, bounded, infrequently-updated collections are fine; anything that grows or churns belongs in its own table with a clustering column.
Frozen collections and UDTs are stored as a single blob, so they are cheaper to read and must be rewritten entirely to change. frozen<my_type> is often the right choice for a value object.
TTL is set per write (or as a table default) and is genuinely useful - but it writes a tombstone when it expires, so a table where everything TTLs is a table that generates tombstones continuously. That is manageable with the right compaction strategy and is the reason Module 4 exists.
Secondary indexes exist and are usually the wrong answer. A standard secondary index is local to each node, so a query using it must contact every node - a scatter-gather with extra steps. It is acceptable only for a column with moderate cardinality within a partition you also constrain. SASI indexes are richer and have had reliability problems. Storage-Attached Indexes (SAI) in Cassandra 5 are a genuine improvement and worth knowing about, and even then: the Cassandra answer to "I need to query by X" is a table keyed on X, not an index.
Laboratory exercise 2 - two models, measured.
Write the query list for the capstone's global event feed - at least eight queries, numbered.
Design two schemas serving it: one strictly query-first with a table per query, and one with fewer tables relying on secondary indexes and ALLOW FILTERING for the awkward queries.
Implement both. Implement every query in both. Measure each query in both models: p50, p95, p99, and - from a trace - the number of nodes contacted and SSTables read. The scatter-gather cost should be plainly visible.
Measure the write amplification: record one event in each model and count the actual writes and the bytes on disk.
Implement the copy-maintenance mechanism for the query-first model, then deliberately diverge the copies by failing one write, detect the divergence, and write the repair procedure.
Then measure collections: the same data as a map column and as a separate table with clustering columns, comparing read latency, write latency and tombstone generation when elements are updated.
Deliverable: the numbered query list, both schemas, every query in both with the measurements and traces, the write amplification figures, the divergence demonstration with its repair procedure, the collection comparison, and a page arguing for one model.
-- ==================================================================
-- STEP 1: THE QUERY LIST. In a file. Numbered. BEFORE any schema.
-- ==================================================================
-- # query partition key
-- 1 a user's events, newest first, by day (user_id, day)
-- 2 one event by id (event_id)
-- 3 events of a kind globally, by day (kind, day)
-- 4 events of a kind for one user (user_id, kind, day)
-- 5 a day's event count per kind (day) counter table
-- 6 the latest event per user (a feed header) (user_id)
-- 7 events in a time range for a user (user_id, day) + range
-- 8 recently active users (day, hour) bucket
--
-- In Cassandra the QUERIES ARE THE SPECIFICATION and the data model
-- is DERIVED from them. A query that was not anticipated usually
-- means a NEW TABLE AND A BACKFILL, not a new WHERE clause.
-- ==================================================================
-- STEP 2: ONE TABLE PER QUERY. The same data, several ways.
-- ==================================================================
-- Query 1
CREATE TABLE events_by_user_day (
user_id uuid, day date, event_at timestamp, event_id timeuuid,
kind text, payload text,
PRIMARY KEY ((user_id, day), event_at, event_id)
) WITH CLUSTERING ORDER BY (event_at DESC, event_id DESC);
-- Query 2
CREATE TABLE events_by_id (
event_id timeuuid PRIMARY KEY,
user_id uuid, day date, event_at timestamp, kind text, payload text
);
-- Query 3
CREATE TABLE events_by_kind_day (
kind text, day date, event_at timestamp, event_id timeuuid,
user_id uuid, payload text,
PRIMARY KEY ((kind, day), event_at, event_id)
) WITH CLUSTERING ORDER BY (event_at DESC, event_id DESC);
-- Query 4
CREATE TABLE events_by_user_kind_day (
user_id uuid, kind text, day date, event_at timestamp,
event_id timeuuid, payload text,
PRIMARY KEY ((user_id, kind, day), event_at, event_id)
) WITH CLUSTERING ORDER BY (event_at DESC, event_id DESC);
-- Query 5 - a counter table. Counters are their OWN column type and
-- cannot share a table with non-counter columns.
CREATE TABLE event_counts_by_day (
day date, kind text, total counter,
PRIMARY KEY (day, kind)
);
UPDATE event_counts_by_day SET total = total + 1
WHERE day = '2026-11-30' AND kind = 'login';
-- Counters are NOT idempotent - a retried increment DOUBLE-COUNTS,
-- and the driver retries. Treat them as approximate, or derive the
-- exact number elsewhere. Module 3.
-- Query 6 - one row per user, overwritten. A valid pattern:
CREATE TABLE latest_event_by_user (
user_id uuid PRIMARY KEY,
event_at timestamp, event_id timeuuid, kind text, payload text
);
-- FIVE TABLES HOLDING THE SAME EVENT. THIS IS CORRECT. You are
-- trading storage and write amplification for READ PREDICTABILITY,
-- deliberately. Disk is cheap; a scatter-gather is not.
-- ==================================================================
-- STEP 4: HOW THE COPIES STAY CONSISTENT. The step people skip, and
-- where the bugs are.
-- ==================================================================
-- OPTION A - a LOGGED BATCH over the same partition key values.
-- Atomic in the sense that it WILL EVENTUALLY COMPLETE (the batch
-- log is replicated), NOT isolated. It has a real cost: Module 3.
BEGIN BATCH
INSERT INTO events_by_user_day (user_id, day, event_at, event_id, kind, payload)
VALUES (7f3c..., '2026-11-30', '2026-11-30 14:04:00+0000', now(), 'login', '{}');
INSERT INTO events_by_id (event_id, user_id, day, event_at, kind, payload)
VALUES (now(), 7f3c..., '2026-11-30', '2026-11-30 14:04:00+0000', 'login', '{}');
INSERT INTO events_by_kind_day (kind, day, event_at, event_id, user_id, payload)
VALUES ('login', '2026-11-30', '2026-11-30 14:04:00+0000', now(), 7f3c..., '{}');
APPLY BATCH;
-- OPTION B - write all five in the application, in parallel,
-- unlogged. Fastest; A PARTIAL FAILURE LEAVES THEM DIVERGENT, and
-- you need a detection query and a repair procedure.
-- OPTION C - a MATERIALIZED VIEW, maintained by Cassandra:
CREATE MATERIALIZED VIEW events_by_kind_mv AS
SELECT * FROM events_by_user_day
WHERE kind IS NOT NULL AND user_id IS NOT NULL AND day IS NOT NULL
AND event_at IS NOT NULL AND event_id IS NOT NULL
PRIMARY KEY ((kind, day), user_id, event_at, event_id);
-- Convenient, AND materialized views have KNOWN LIMITATIONS that
-- lead many operators to avoid them in production: view/base
-- inconsistency after certain failures, no repair for views, and a
-- write-path cost. Know they exist; prefer explicit tables unless
-- you have tested them for your case.
--
-- WHICHEVER YOU CHOOSE: write it down, and have a DETECTION QUERY
-- and a REPAIR PROCEDURE for divergence. Demonstrate both in the lab.
-- ==================================================================
-- CLUSTERING ORDER is a DISK LAYOUT decision.
-- ==================================================================
-- Stored DESC, so "newest 50" is a SEQUENTIAL read from the start:
-- WITH CLUSTERING ORDER BY (event_at DESC)
-- SELECT ... LIMIT 50; <- fast
-- Stored ASC and queried DESC works and reads BACKWARDS, which is
-- measurably slower. Decide from the DOMINANT query.
-- ==================================================================
-- COLLECTIONS: convenient, with real costs.
-- ==================================================================
CREATE TABLE user_profile (
user_id uuid PRIMARY KEY,
name text,
tags set<text>, -- small, bounded: fine
settings map<text, text>, -- small, bounded: fine
recent_ips list<inet> -- A LIST IS THE WORST CHOICE.
);
UPDATE user_profile SET tags = tags + {'vip'} WHERE user_id = 7f3c...;
UPDATE user_profile SET tags = tags - {'trial'} WHERE user_id = 7f3c...;
-- ^^^^^^^^^ a REMOVAL writes a
-- TOMBSTONE
UPDATE user_profile SET settings['theme'] = 'dark' WHERE user_id = 7f3c...;
-- THE COSTS, all three real:
-- * a collection is read IN ITS ENTIRETY
-- * recommended limit a FEW HUNDRED elements
-- * UPDATING AN ELEMENT WRITES A TOMBSTONE, and replacing a whole
-- collection writes a RANGE tombstone covering it
-- * a LIST is worse: index-based updates are READ-BEFORE-WRITE
--
-- Small, bounded, rarely-updated: fine. Anything that GROWS or
-- CHURNS belongs in its OWN TABLE with a clustering column:
CREATE TABLE user_tags (
user_id uuid, tag text,
PRIMARY KEY (user_id, tag)
);
-- Now adding a tag is one write and removing one is one tombstone in
-- a table you can compact appropriately - rather than a tombstone in
-- the middle of a profile row you read on every request.
-- FROZEN collections and UDTs: stored as ONE BLOB. Cheaper to read,
-- and must be REWRITTEN ENTIRELY to change. Often right for a value
-- object:
CREATE TYPE address (line1 text, city text, postcode text);
ALTER TABLE user_profile ADD home frozen<address>;
-- ==================================================================
-- TTL: useful, and it GENERATES TOMBSTONES.
-- ==================================================================
INSERT INTO events_by_user_day (user_id, day, event_at, event_id, kind, payload)
VALUES (7f3c..., '2026-11-30', '2026-11-30 14:04:00+0000', now(), 'login', '{}')
USING TTL 2592000; -- 30 days
ALTER TABLE events_by_user_day WITH default_time_to_live = 2592000;
SELECT TTL(payload), WRITETIME(payload) FROM events_by_user_day
WHERE user_id = 7f3c... AND day = '2026-11-30' LIMIT 1;
--
-- A table where EVERYTHING TTLs generates tombstones CONTINUOUSLY.
-- That is manageable with TimeWindowCompactionStrategy (Module 4) -
-- and it is the reason Module 4 exists.
-- ==================================================================
-- SECONDARY INDEXES: usually the wrong answer.
-- ==================================================================
CREATE INDEX ON events_by_user_day (kind);
SELECT * FROM events_by_user_day WHERE kind = 'login';
-- A standard index is LOCAL TO EACH NODE, so this query must
-- contact EVERY NODE: a scatter-gather with extra steps.
--
-- Acceptable only when you ALSO constrain the partition key, so the
-- index is used within one partition:
SELECT * FROM events_by_user_day
WHERE user_id = 7f3c... AND day = '2026-11-30' AND kind = 'login';
--
-- SASI richer, and has had reliability problems
-- SAI (C* 5) a GENUINE improvement; worth knowing about
--
-- AND EVEN THEN: the Cassandra answer to "I need to query by X" is
-- A TABLE KEYED ON X. That is what query-first means.
Discussion
No questions on this topic yet. Sign in to ask the first one.