▚ The Software Engineer's Field Manual
Chapter E18 · Primer + senior drill

Apache Cassandra — Data Modelling Mental Map + 100-Question Drill

"In a relational database you model the data and ask any question later. In Cassandra you write down the questions first and build one table for each. Every other difference in this chapter is a consequence of that one flip."

100 questions · answers collapsed Every example: relational vs Cassandra side by side Heavy on: query-first modelling · partition keys · denormalisation · consistency

01 · Why this primer existsYou Know Relational Modelling — Cassandra Asks You to Un-Learn Half of It

Cassandra is a database that stores each row in one place, found by hashing a key, and never joins tables at read time. So you cannot design it the way you design PostgreSQL. This chapter is a map from every relational habit you have to the Cassandra replacement, with both versions shown side by side.

Here is a story that happens to teams who move a successful relational system to Cassandra. A food-delivery app called QuickBite runs on PostgreSQL. It has 30 million orders, a clean normalised schema, and a handful of well-chosen indexes.

The app grows. One PostgreSQL server cannot take the write load of a lunch rush, so the team picks Cassandra, which spreads rows over many machines and keeps accepting writes when a machine dies.

The team is good, so they do the careful thing. They take the PostgreSQL schema, table by table, and write the same tables in CQL (Cassandra Query Language, which looks almost exactly like SQL). Same columns, same keys. Migration done in two weeks.

On launch day the "My orders" screen shows a spinner. The query behind it is the one every customer runs: "the 20 newest orders for this customer".

Relational · PostgreSQL

The orders table has order_id as its primary key. An index on customer_id makes this query fast, and the planner picks it.

orders.sqlruns offline
SELECT order_id, placed_at, total_cents
FROM orders
WHERE customer_id = $1
ORDER BY placed_at DESC
LIMIT 20;
-- index orders(customer_id) makes this ~1 ms

Cassandra · CQL

The team copied the table with order_id as its key. Cassandra refuses the query, so they add a flag.

orders.cql (naive port)runs offline
SELECT order_id, placed_at, total_cents
FROM orders
WHERE customer_id = ?
ALLOW FILTERING;
-- ❌ TRAP: asks every node to scan its rows

The shift: Relational stores rows once and lets an index find them by anything. Cassandra finds a row only by its partition key, so "by customer" must be a different table.

Make the invisible visible: what Cassandra says when you ask a question the table was not built for, and what the cluster does when you force it.

cqlsh session, naive portruns offline
# illustrative output
cqlsh:quickbite> SELECT * FROM orders WHERE customer_id = 7f3e...;
InvalidRequest: Error from server: code=2200
  message="Cannot execute this query as it might involve data
  filtering and thus may have unpredictable performance. If you
  want to execute this query despite the performance
  unpredictability, use ALLOW FILTERING"

cqlsh:quickbite> SELECT * FROM orders WHERE customer_id = 7f3e... ALLOW FILTERING;
ReadTimeout: Error from server: code=1200
  message="Operation timed out - received only 1 responses."
  info={'consistency': 'LOCAL_ONE', 'required_responses': 1,
        'received_responses': 0}

That error message is Cassandra being polite. It is saying: "I have no way to jump to this customer's orders. I would have to read every order on every machine and throw away all the ones that are not this customer's."

With 30 million orders spread over 9 nodes, that is about 3.3 million rows per node to read for one customer who has 40 orders. At lunch time, thousands of customers do this at once, and the cluster falls over.

The fix: the team does not tune anything. They add a second table, orders_by_customer, whose partition key is customer_id, and write every order into both tables. Reading "my orders" now touches one partition on one set of replicas.

Relational · PostgreSQL

One table, many indexes. A new question usually means a new index, not a new table.

new questionruns offline
CREATE INDEX ON orders (customer_id);
CREATE INDEX ON orders (restaurant_id);
-- one table, one copy of every order

Cassandra · CQL

One table per question. A new question means a new table that you also write to.

new questionruns offline
CREATE TABLE orders_by_customer (
  customer_id uuid,
  placed_at   timestamp,
  order_id    uuid,
  total_cents int,
  PRIMARY KEY ((customer_id),
    placed_at, order_id)
) WITH CLUSTERING ORDER BY
  (placed_at DESC, order_id ASC);

The shift: Copying data is the design, not a mistake. The copy is how a read becomes "one partition, already sorted".

The mental map in one picture

Both kinds of database end up with tables. The difference is what the designer starts from, and that changes every decision after it.

A relational designer starts from the things in the business (customers, orders) and makes sure each fact is stored once. A Cassandra designer starts from the questions the app asks (show my orders, show today's orders for this restaurant) and builds a table that answers each one directly.

Keep Fig. 18.1 in your head. Every section after this one is one box of this picture, zoomed in.

Relational: model the data first Cassandra: list the questions first 1 Entities and relationships (customer, order, restaurant ...) 2 Normalise each fact stored exactly once 3 Tables + foreign keys one table per kind of thing 4 Any question, asked later new screen = new query, no schema change 5 Planner joins and indexes finds the rows at read time 1 Application workflow (screens, jobs, events) 2 Queries Q1 ... Qn written down before any table 3 One table per query each table answers one question 4 Partition key + clustering columns where rows live, how they are sorted 5 Denormalise write each fact into N tables Writes are cheap, reads are smart. The cost is paid when you ask. Reads are trivial, writes are repeated. The cost is paid when you save.
Fig. 18.1 — the mental map. Left: relational design moves from data to questions. Right: Cassandra design moves from questions to data. Both pipelines have five steps; the order is reversed in spirit.

The right-hand pipeline looks backwards to a relational engineer, and that is the whole point. In step 2 you write the queries before you draw any table.

A useful sentence to repeat: in Cassandra, the query is the input and the table is the output. In PostgreSQL, the table is the input and the query is the output.

What you see: the ten biggest habit changes in one table. Each row links to a translation block later in the chapter (the blocks are written the same way: habit, replacement, side-by-side code, trap).

The ten biggest habit changes
#Relational habitCassandra replacementWhere to read more
1Primary key means "this row is unique".Primary key means "this is where the row lives and how it is sorted".map-primary-key
2INSERT fails if the key exists; UPDATE needs the row to exist.INSERT and UPDATE are both an upsert. Last write wins.map-upsert
3An index lets me find a row by any column.A row is found by its partition key only. Other lookups need another table.map-row-lookup
4WHERE and ORDER BY on any column.Equality on the whole partition key, then a left-to-right prefix of the clustering columns. Sort order is fixed at table creation.map-where-clause · map-order-by
5Design the entities, then the queries.Design the queries, then the tables.map-design-order
6Normalise: store each fact once.Denormalise: store each fact once per query that needs it.map-normalise
7JOIN at read time.Pre-join at write time: the joined row is already in the table.map-join
8Foreign keys and UNIQUE constraints keep data honest.No foreign keys, no UNIQUE. The application keeps data honest, with a lookup table or a lightweight transaction.map-foreign-key · map-unique
9COUNT, SUM and GROUP BY when I ask.Keep the answer ready: a counter, or a table built for the report.map-aggregate
10One transaction, many tables, all or nothing.Tunable consistency per query, logged batches for copies, and deletes that leave tombstones.map-transaction · map-delete

How to read this chapter: the map, node by node

Fig. 18.1 and the table above are the whole chapter in miniature. Here is the same map walked one box at a time, in plain words, so you know what each later section is doing for you.

Node 1, the entity or the workflow. In both worlds you start by understanding the business. The relational designer writes down the nouns: customer, order, restaurant. The Cassandra designer writes down the verbs: show my orders, mark an order delivered, move the rider on the map. This is the section called "The modelling method". Node 2, normalise or list the queries. The relational designer removes repeated facts so each is stored once. The Cassandra designer does something that feels odd at first: writes the queries as sentences, with what is given and what comes back. The reason is in the storage section: Cassandra can only find a row by its key, so the key must be chosen from the query. Node 3, tables. Both end up with tables. In PostgreSQL a table is a kind of thing. In Cassandra a table is an answer to one question. If two questions need different keys or different sort orders, they get two tables. Node 4, the keys. In PostgreSQL the primary key mostly says "this row is unique". In Cassandra it says where the row lives and how rows next to it are ordered. That is why one whole section is about keys. Node 5, the read-time work. In PostgreSQL the planner does the work when you read: it joins, sorts and picks indexes. In Cassandra that work was done earlier, when you wrote the row into the right tables. The next three sections (relationships, consistency, case studies) show how every relational tool maps onto that idea.

If you remember only one thing: relational pays at read time, Cassandra pays at write time. Everything else is detail on that sentence.

What you see: a new requirement arrives after launch. Support wants "all orders that were refunded this week". Watch what each team does.

Relational · PostgreSQL

Write the query. Maybe add an index. Done by lunch.

refunds.sqlruns offline
SELECT order_id, total_cents
FROM orders
WHERE status = 'refunded'
  AND placed_at > now() - interval '7d';
CREATE INDEX ON orders (status, placed_at);

Cassandra · CQL

Add a table for this question, then fill it.

refunds.cqlruns offline
CREATE TABLE refunds_by_week (
  week  date, refunded_at timestamp,
  order_id uuid, total_cents int,
  PRIMARY KEY ((week), refunded_at, order_id)
);
-- app writes it from now on;
-- old rows need a backfill job

The shift: A new relational question costs a query. A new Cassandra question costs a table, a write path and perhaps a backfill, so the list of questions must be taken seriously up front.

Bridge: what "one table per query" costs and buys, with numbers

The idea of writing the same order into several tables feels wasteful, so check it with QuickBite's numbers. On a busy day there are 120,000 orders. Each order is written into four tables, so 480,000 row writes instead of 120,000.

That sounds like four times the work, but the writes are cheap: each is an append to the commit log and a memtable insert, and a single node can absorb tens of thousands of these a second. Spread over nine nodes and three replicas each, the extra load is small.

Now count the reads. "My orders", "order detail", "restaurant board" and "status timeline" are asked millions of times a day. Each is one partition read. Without the copies, each would be a join or a scan across nodes.

The trade is therefore: more cheap writes in exchange for far fewer and far cheaper reads. It pays off whenever reads outnumber writes by a good margin, and that is true for most products. It also costs disk: four copies of a 120-byte summary for 30 million orders is about 14 GB before replication, which is nothing for a cluster of this size.

The one thing it costs that numbers do not show is discipline. Four tables can now disagree if a write goes wrong, and the next sections explain how to keep them in step.

Meet QuickBite, the running example

Every example in this chapter uses one product so you can see the same data modelled both ways. QuickBite is a food-delivery app. Keep these illustrative numbers in mind:

The relational designer sees eight tables joined by foreign keys (a foreign key is a column that must match the key of a row in another table). The Cassandra designer sees eight questions, each of which will get its own table.

Fig. 18.2 shows both views of the same product. We will build the real thing, step by step, in the section called "The modelling method".

Relational: 8 tables, one copy of each fact Cassandra: 8 questions, 1 table each customers restaurants orders order_items order_status_events menu_items riders rider_locations lines = foreign keys; read by joining Q1 My orders, newest first orders_by_customer Q2 One order and its lines orders_by_id Q3 A restaurant's menu menu_by_restaurant Q4 Restaurant orders today orders_by_restaurant_day Q5 Order status timeline order_events_by_order Q6 Rider's live position rider_latest Q7 Login by phone number customers_by_phone Q8 Customer profile customers_by_id each arrow = one query answered by one table
Fig. 18.2 — QuickBite seen both ways. Left: eight normalised tables joined by foreign keys. Right: eight questions, each answered by exactly one table.

02 · How each database stores and finds a rowOne Server With an Index, or a Ring of Servers With a Hash — Why the Models Differ

PostgreSQL keeps rows in one place and builds sorted indexes on top, so it can find a row by any column. Cassandra decides which machines hold a row by hashing one key, and only that key. Every modelling rule in the rest of this chapter comes from this one difference in how a row is found.

Start with a tiny task: "find order 42". Both databases can do it, but they do it in very different ways, and the difference explains why you cannot model them the same.

In PostgreSQL, the table (called the heap) is a pile of 8 KB pages, and rows sit in them in roughly the order they were written. Nothing is sorted. To find order 42 quickly, PostgreSQL keeps a second structure: a B-tree index, a sorted tree whose last level points at the exact page and slot where the row lives.

With 30 million orders, that tree is about 3 levels deep. A lookup reads about 4 pages: root, middle, leaf, then the heap page. The top levels are almost always in memory, so it takes about a millisecond.

The important part: you can build as many such trees as you like, on any column. Every tree is another way in to the same single copy of the row.

Cassandra has no such trees by default. It spreads rows over many machines (nodes), and it needs to know which node before it can look anywhere. So it takes the partition key (for example order_id), runs it through a hash function, and the result (called a token) says which node owns the row.

The nodes are arranged on a conceptual ring, each owning slices of the token range. The default hash is called Murmur3, and the token is a number between about -9.2 quintillion and +9.2 quintillion. You never see it unless you ask.

To survive a dead machine, Cassandra stores each row on several nodes. The number of copies is the replication factor (RF). With RF = 3, the row lives on the node that owns the token and the next two different nodes around the ring. These three are the row's replicas.

PostgreSQL: index first, then the heap Cassandra: hash first, then the owner B-tree root page B-tree middle page B-tree leaf page key 42 → (heap page 7, slot 3) Heap page 7 (8 KB) the row for order 42 is here about 4 page reads, one machine, and any column can have its own tree order_id = 42 token = hash(42) N1 N2 N3 N4 N5 N6 token owner N2, copies on N3 and N4 (RF = 3) one hop, no scan, but only by this key
Fig. 18.3 — "Find order 42" both ways. PostgreSQL walks a sorted tree to a page. Cassandra hashes the key and goes straight to the owning node (N2) and its two replicas (N3, N4). Six nodes drawn for clarity; a real ring has many.

Relational · PostgreSQL

The primary key is a B-tree. Any other column can get its own index. The planner picks one.

find42.sqlruns offline
SELECT * FROM orders
WHERE order_id = 42;
-- EXPLAIN shows:
--  Index Scan using orders_pkey
--  (about 4 page reads)

Cassandra · CQL

The partition key is hashed. The row is on the owning node and two more. No other path exists.

find42.cqlruns offline
SELECT * FROM orders
WHERE order_id = 42;
-- TRACING ON shows:
--  coordinator -> replica N2
--  (one partition read)

The shift: Same text, different machinery: SQL searches a sorted structure, CQL jumps by hash. That is why CQL has no "any column" WHERE.

Bridge: how a token is computed and which three nodes own it

Let us trace one order through the ring, with six nodes and RF = 3. The numbers below are illustrative; real Murmur3 tokens are 64-bit and you can see them with the token() function.

The partition key is the order id. Cassandra turns its bytes into one 64-bit number with the Murmur3 hash. The result looks random, and that is the point: neighbouring keys land on different nodes, so load spreads evenly.

Each node owns slices of the number line. With vnodes (virtual nodes) a node owns many small slices rather than one big one; the default is 16 slices per node. The node that owns the slice containing our token is the first replica. The next two different nodes found by walking round the ring are the other two.

tracing order 42 through the ringruns offline
# illustrative values, 6 nodes, RF=3
order_id            = 3f2a9c1e-...-42
token(order_id)     = 4,611,686,018,427,387,904   (64-bit number, looks random)
slice containing it = owned by N2   -> first replica
walk clockwise      = N3 (different node) -> second replica
                      N4 (different node) -> third replica
coordinator = the node the app happened to call, say N5
N5 sends the write to N2, N3, N4 and waits for 2 of 3 answers (LOCAL_QUORUM)

Relational habit

One primary takes the write. A standby copies it. If the primary dies, someone must be promoted.

failover.txtruns offline
primary: writes + reads
standby: copy, read-only
primary dies -> failover
(seconds to minutes of
 writes refused)

Cassandra habit

Any replica can take the write. If one dies the others carry on.

replicas.txtruns offline
N2, N3, N4 all accept writes
N3 dies -> N2 + N4 answer
(2 of 3 = quorum, no pause)
N3 returns -> hinted writes
and repair catch it up

The shift: Relational has one place that is allowed to write, so it must be replaced when it fails. Cassandra has no special node, so there is nothing to replace.

Bridge: one read, step by step, with the bloom filter

Take the read "orders of customer C7", after the day described above. It is asked at 20:30 of a node that holds C7's partition, with a memtable and two SSTables.

First the node looks in the memtable, which is a fast in-memory lookup by key. It finds the two orders from 19:00. Then it asks each SSTable's bloom filter, a few kilobytes of memory that can say "definitely not here" or "maybe here". SSTable 1 says maybe; SSTable 2 says maybe.

For each "maybe" the node looks in a small index to find the byte position of C7's partition inside the file, and reads that slice. A read can therefore cost one disk seek per SSTable that might hold the key. This is why compaction matters: ten SSTables means up to ten seeks, two means two.

Finally the node merges all the pieces by column timestamp and returns the newest. The coordinator may have asked two replicas and compares their answers. If they disagree, it returns the newest and quietly repairs the stale one (read repair).

one read on one replicaruns offline
# illustrative, read of customer C7
step                      result
memtable lookup           found orders C, D (19:00)
SSTable 1 bloom filter    maybe  -> index lookup -> read slice -> orders A, B
SSTable 2 bloom filter    maybe  -> index lookup -> read slice -> orders C, D
SSTable 3 bloom filter    no (skip, no disk read)
merge by timestamp        A(delivered) B C D   -> return to coordinator
cost = 1 memtable + 2 disk slices

Relational · PostgreSQL

The planner picks a plan and tells you the cost with EXPLAIN.

explain.sqlruns offline
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders
WHERE customer_id = $1;
-- Index Scan ... Buffers: hit=5
-- Execution Time: 0.12 ms

Cassandra · CQL

You ask for a trace and see which SSTables were touched.

trace.cqlruns offline
TRACING ON;
SELECT * FROM orders_by_customer
WHERE customer_id = ?;
-- Merged data from memtable and
--   2 sstables
-- Read 4 live rows, 0 tombstones

The shift: Both show you the work. In SQL the work depends on the plan chosen. In CQL it depends on how many files hold the partition.

Bridge: what happens inside one node when you write and read

A write must be fast even at thousands per second per node. Cassandra gets this by never updating a file in place. A write is two cheap steps: append one line to a log on disk (the commit log, so the write survives a crash) and put the row into a sorted structure in memory (the memtable). Then it answers "done".

When the memtable is full, it is written to disk as one new file called an SSTable (sorted string table). SSTables are never edited. Over time there are many of them, so a background job called compaction merges them into fewer, bigger files and throws away data that was overwritten or deleted.

A read therefore may have to look at the memtable and several SSTables, because the newest copy of a row could be in any of them. Each SSTable has a bloom filter, a tiny summary that says "this key is definitely not in this file", which lets the read skip most files. The newest timestamp wins when copies disagree.

PostgreSQL does something different: an UPDATE writes a new row version into the heap and marks the old one dead, and a background job called VACUUM later reclaims the space. Both engines clean up behind the scenes, but PostgreSQL edits pages and Cassandra only adds files.

WRITE PATH Write arrives INSERT / UPDATE 1 Commit log disk, append only 2 Memtable RAM, kept sorted 3 Flush to SSTable disk, never edited 4 Compaction merge files, drop old client gets "done" after 1 and 2 READ PATH Read arrives one partition key Check memtable newest data in RAM Bloom filter, SSTables skip files without the key Merge copies newest timestamp wins writes only append; reads may combine several files
Fig. 18.4 — inside one Cassandra node. Writes append (commit log, memtable, later an SSTable). Reads may need to combine the memtable and several SSTables, and the newest timestamp wins.

Bridge: what one partition goes through in a day

Take the partition for one customer, customer_id = C7, on one replica. It is easiest to see as a story with times.

At 09:00 C7 places an order. The row is appended to the commit log and put in the memtable. At 12:30 another order arrives; same two steps. At 13:15 the first order's status changes to "delivered", which is just another write of the same key with a newer timestamp. Nothing on disk is changed in place.

At 14:00 the memtable is full (it holds many customers, not only C7) and is flushed. Now C7's three writes are in SSTable 1. At 19:00 two more orders arrive, and by 20:00 a second flush puts them in SSTable 2. A read for C7 now has to look in the memtable, SSTable 1 and SSTable 2, and merge. At 03:00 a compaction merges SSTable 1 and 2 into SSTable 3 and drops the old "placed" version of the first order, because the "delivered" version is newer.

one partition across a dayruns offline
# illustrative, customer C7, one replica
time   event                       memtable      SSTables
09:00  write order A (placed)      A1            -
12:30  write order B (placed)      A1 B1         -
13:15  write order A (delivered)   A2 B1         -
14:00  memtable flushed            (empty)       S1: A2 B1   (the memtable keeps only the newest A)
19:00  write orders C, D           C1 D1         S1
20:00  memtable flushed            (empty)       S1, S2: C1 D1
-- read for C7 at 20:30: look at memtable + S1 + S2, merge, newest wins
03:00  compaction S1 + S2          (empty)       S3: A2 B1 C1 D1   -- fewer files to read

Relational · PostgreSQL

An UPDATE changes the row version on a heap page. VACUUM cleans up later.

update.sqlruns offline
UPDATE orders
SET status = 'delivered'
WHERE order_id = $1;
-- new tuple written, old one dead
-- VACUUM reclaims the old tuple

Cassandra · CQL

The same statement writes a newer version. Compaction removes the older one.

update.cqlruns offline
UPDATE orders_by_customer
SET status = 'delivered'
WHERE customer_id = ?
  AND placed_at = ? AND order_id = ?;
-- new cell, newer timestamp
-- compaction drops the old cell

The shift: Both engines keep an old version for a while and tidy up later. In Cassandra the tidy-up is the way the database works, not an extra job, so you plan for it.

Notice what this design is good at: writes are sequential and cheap, and a read for one partition key goes to one place. Notice what it cannot do: it has no tree to answer "give me every order over 50 dollars", because the data is organised by key hash, not by value.

That is the reason for most rules below. Cassandra gives you very fast answers to questions shaped like its keys, and nothing at all for the others.

Relational → Cassandra: Primary key

The relational habit: a primary key is the unique name of a row. You pick the column (or columns) that make each row different, add indexes for the rest, and the key plays no part in speed or placement.

The Cassandra replacement: the primary key has two jobs. The first part, the partition key, decides which nodes hold the row. The rest, the clustering columns, decide how rows are sorted inside that partition. Uniqueness is only a side effect of the two together.

Relational · PostgreSQL

Key = identity. One row per order, found by order id.

orders.sqlruns offline
CREATE TABLE orders (
  order_id    uuid PRIMARY KEY,
  customer_id uuid NOT NULL,
  placed_at   timestamptz NOT NULL,
  total_cents int
);

Cassandra · CQL

Key = placement. All orders of one customer share a partition, newest first.

orders_by_customer.cqlruns offline
CREATE TABLE orders_by_customer (
  customer_id uuid,
  placed_at   timestamp,
  order_id    uuid,
  total_cents int,
  PRIMARY KEY ((customer_id),
               placed_at, order_id)
) WITH CLUSTERING ORDER BY
  (placed_at DESC, order_id ASC);

The shift: A relational key answers "is it the same row?". A Cassandra key answers "where is the row, and what is next to it?".

  1. Write the question: "20 newest orders of one customer."
  2. Equality part becomes the partition key: customer_id, because the question names one customer.
  3. Sort part becomes the clustering columns: placed_at newest first, then order_id to keep two orders at the same instant apart.
  4. Check uniqueness last: the full key must name one row: (customer_id, placed_at, order_id) does.

The trap: picking the key only for uniqueness, as you would in PostgreSQL. The table works for "get order by id" and for nothing else.

what the naive key gives youruns offline
# illustrative
PRIMARY KEY (order_id)        -- every order is its own partition
30,000,000 partitions, 1 row each, spread by hash of order_id
SELECT ... WHERE customer_id = ?   -- ❌ TRAP: no partition key given
-- the customer's 40 orders sit on up to 40 different nodes

Relational → Cassandra: Insert, update and upsert

The relational habit: INSERT creates a row and fails if the key already exists. UPDATE changes a row that must exist. To avoid races, read the row first, check, then write.

The Cassandra replacement: INSERT and UPDATE do the same thing: write the listed columns for this key, creating the row if needed. There is no read before the write and no error for "already exists". If two writes collide, the one with the newer timestamp wins.

Relational · PostgreSQL

Duplicate key is an error. To overwrite, say so.

upsert.sqlruns offline
INSERT INTO orders (order_id, status)
VALUES (42, 'placed');
-- again: ERROR duplicate key
INSERT ... ON CONFLICT (order_id)
DO UPDATE SET status = 'placed';

Cassandra · CQL

Same statement twice is fine. The second write simply replaces the first.

upsert.cqlruns offline
INSERT INTO orders (order_id, status)
VALUES (42, 'placed');
-- again: fine, same result
UPDATE orders SET status = 'cooking'
WHERE order_id = 42;
-- creates the row if it was missing

The shift: Relational asks "does it exist?" before it writes. Cassandra never asks, which is what makes writes fast and what makes duplicates silent.

  1. Make writes safe to repeat: a write that can be retried with the same result needs no check.
  2. Choose the key on purpose: two different things with the same key become one row.
  3. Use IF NOT EXISTS only when you truly need "first writer wins": it costs about four round trips between replicas.

The trap: expecting a duplicate error. Two apps create order 42 with different totals and nobody is told.

two writers, one keyruns offline
# illustrative cqlsh session
INSERT INTO orders (order_id, total_cents) VALUES (42, 1800);   -- app A, t=100
INSERT INTO orders (order_id, total_cents) VALUES (42, 2450);   -- app B, t=101
SELECT total_cents FROM orders WHERE order_id = 42;
 2450      -- ❌ TRAP: A's order silently replaced, no error anywhere
INSERT INTO orders (order_id, total_cents) VALUES (42, 9) IF NOT EXISTS;
 [applied] False   -- the lightweight transaction says "already there"

Relational → Cassandra: Finding a row: index vs partition key

The relational habit: "I need to find customers by phone number, so I add an index on phone." Every column is searchable once it has a tree.

The Cassandra replacement: only the partition key is a fast path. For a second way in, write a second table whose partition key is the new lookup column (for example customers_by_phone). Indexes exist (SAI, covered later) but they are for filtering inside a design, not a substitute for one.

Relational · PostgreSQL

One table, a second B-tree on phone.

customers.sqlruns offline
CREATE TABLE customers (
  customer_id uuid PRIMARY KEY,
  phone text UNIQUE,
  name  text
);
-- UNIQUE builds a B-tree on phone

Cassandra · CQL

Two tables. The lookup table maps phone to customer id.

customers.cqlruns offline
CREATE TABLE customers_by_phone (
  phone text PRIMARY KEY,
  customer_id uuid
);
CREATE TABLE customers_by_id (
  customer_id uuid PRIMARY KEY,
  phone text, name text
);

The shift: In SQL an access path is an index you add later. In CQL it is a table you decide on now and write to every time.

  1. List every column you search by: phone, id, email ...
  2. One table per search column: its key is the column, its other columns are what the screen needs.
  3. Write them together: one logged batch, or one write each from the app (see the consistency section).

The trap: adding a legacy secondary index on a column the query does not give a partition key for. It works on a laptop and gets slower with every node.

what the coordinator does without a partition keyruns offline
# illustrative, 9-node cluster, WHERE city = 'Pune' on an indexed column
coordinator contacts N1 N2 N3 N4 N5 N6 N7 N8 N9   -- ❌ TRAP: all nodes, every time
each node scans its local index, returns matches
latency = slowest node; adding nodes does not help

03 · The primary key is the whole designPartition Key, Clustering Columns and the Rules of the WHERE Clause

In Cassandra the primary key has two halves. The partition key says which machines hold the rows, and the clustering columns say how the rows in that partition are sorted. Your WHERE clause must walk the key from the left, so choosing the key is the same job as choosing the queries you can ever ask.

Here is a story from the QuickBite rider team. While a rider is on a delivery, the phone sends its position every 5 seconds. The customer's map shows the rider moving, and support wants to replay a route when a customer complains.

The first design is natural: a table rider_track with the rider id as the partition key and the time as the clustering column. "Give me this rider's positions, in time order" is exactly one partition read. It works in testing, and it works for the first month.

Then one night the on-call engineer sees a compaction that will not finish, and read latency for riders who have been active a long time creeps from 5 ms to 400 ms. The reason is arithmetic. A rider sends 12 positions a minute, 17,280 a day. Over a year that is 6.3 million rows in one partition, about 300 MB at roughly 50 bytes a row.

A partition is the unit that lives on one set of replicas and is read together. A partition of 300 MB has to be written, compacted, repaired and streamed as one lump. The usual guideline is to keep a partition under about 100 MB and about 100,000 rows. It is a guideline, not a hard limit, but ignoring it is how the 400 ms arrives.

Relational · PostgreSQL

A rider has many rows. They sit wherever the heap had room, and an index lists where.

rider_track.sqlruns offline
CREATE TABLE rider_track (
  rider_id uuid,
  at       timestamptz,
  lat      double precision,
  lon      double precision,
  PRIMARY KEY (rider_id, at)
);
-- index entries point at scattered pages

Cassandra · CQL

One partition per rider keeps rows together, but with no limit it grows forever.

rider_track.cql (v1, grows)runs offline
CREATE TABLE rider_track (
  rider_id uuid,
  at       timestamp,
  lat      double,
  lon      double,
  PRIMARY KEY ((rider_id), at)
);
-- ❌ TRAP: unbounded partition

The shift: In PostgreSQL a big table is just a big table. In Cassandra every partition must be small enough to be moved and read whole.

Make the invisible visible: where one rider's rows sit physically in each database.

PostgreSQL heap: rows land wherever there is room Cassandra partition: rows stay together, sorted page 7 R3 · R7 08:00:05 · R41 page 913 R88 · R7 08:00:10 · R9 page 2204 R7 08:00:15 · R2 · R50 R7's last hour = about 720 rows in up to 720 different pages Partition: rider_id = R7 08:00:05 18.5204 73.8567 08:00:10 18.5206 73.8570 08:00:15 18.5209 73.8574 08:00:20 18.5213 73.8579 ... sorted by time ... one seek, then walk forward: 720 rows in order
Fig. 18.5 — where one rider's rows physically sit. PostgreSQL scatters them and uses an index to find them. Cassandra keeps a partition's rows next to each other, sorted by the clustering column.

The four parts of a key

A Cassandra primary key can have up to four kinds of piece. Each has a plain-words meaning:

Static columns solve a common join. An order has one status and one customer, but several order lines. In PostgreSQL that is two tables joined on order_id. In Cassandra you can put the header values in the partition as static columns, and the lines as normal rows, so one read returns both.

Relational · PostgreSQL

Header table and line table, joined on order_id.

order_and_lines.sqlruns offline
SELECT o.status, l.line_no, l.item_name
FROM orders o
JOIN order_lines l USING (order_id)
WHERE o.order_id = 42
ORDER BY l.line_no;

Cassandra · CQL

One partition: status is static, lines are rows.

orders_by_id.cqlruns offline
CREATE TABLE orders_by_id (
  order_id  uuid,
  line_no   int,
  status    text STATIC,
  item_name text,
  PRIMARY KEY ((order_id), line_no)
);
SELECT status, line_no, item_name
FROM orders_by_id WHERE order_id = ?;

The shift: The join is gone because the header was stored inside the lines' partition. One read, one place.

The rules of the WHERE clause

Because rows are found by hash and then walked in sorted order, the allowed queries follow three simple rules. Take the key PRIMARY KEY ((rider_id, day), at):

  1. Rule 1, partition key: you must give an equality (or an IN list) for every partition-key column. Missing one means Cassandra cannot compute the hash.
  2. Rule 2, clustering prefix: restrict clustering columns from the left, with no gaps. If you have two, you cannot skip the first and restrict the second.
  3. Rule 3, one range, last: a range (>, <, BETWEEN) is allowed only on the last clustering column you restrict. Everything before it must be an equality.
PRIMARY KEY ((rider_id, day), at) rider_id day at (clustering) partition key = hashed together sorted inside WHERE rider_id = R7 AND day = D ✓ OK: one partition ... AND day = D AND at >= 08:00 AND at < 09:00 ✓ OK: range on the last clustering column WHERE rider_id = R7 ✗ NO: day (part of the partition key) missing WHERE day = D ✗ NO: rider_id missing, no hash possible WHERE rider_id = R7 AND day = D AND lat > 18.5 ✗ NO: lat is not a key column (needs ALLOW FILTERING) WHERE rider_id = R7 AND day IN (D1, D2) ✓ OK: two partitions, two reads
Fig. 18.6 — which WHERE clauses a key allows. Green rows hit a known partition. Red rows cannot be answered without scanning, so Cassandra refuses them unless you add ALLOW FILTERING.

Bridge: IN, ranges and why order matters

Two more questions come up as soon as you write real queries. "Can I ask for several customers at once?" and "Can I ask for a time range?" Both are allowed, but only in the shapes the key can answer.

IN on the partition key is allowed. Cassandra sends one read per listed value, from the coordinator, and merges the answers. Five values in the list means five partition reads, so keep the list short: a hundred values is a hundred reads from one machine and a likely timeout.

A range on a clustering column is the strength of the model. Because rows are sorted, "the orders between two dates" is a start position and a stop position, read in one pass. You get this free from the key, not from an index.

Relational · PostgreSQL

BETWEEN uses a B-tree range scan. IN becomes an index lookup per value.

range.sqlruns offline
SELECT * FROM orders
WHERE customer_id = $1
  AND placed_at BETWEEN $2 AND $3;
-- customer_id IN (...) is also fine

Cassandra · CQL

The range is a slice of a sorted partition. IN means one partition read per value.

range.cqlruns offline
SELECT * FROM orders_by_customer
WHERE customer_id = ?
  AND placed_at >= ?
  AND placed_at <= ?;
-- IN (a,b,c) = 3 separate reads

The shift: Both allow ranges and IN. The difference is cost: Cassandra tells you it is cheap only when the data is already laid out in that order.

ALLOW FILTERING, in plain words

ALLOW FILTERING is the flag that tells Cassandra: "I know this query breaks the rules; run it anyway by reading rows and discarding the ones that do not match." It is fine on a tiny table or inside one partition you already named. On a big table it means a full scan.

Treat the error message that asks you to add it as a design warning. The fix is nearly always a new table, not the flag.

Bridge: sizing a partition by hand

Before you commit to a key, do the arithmetic. It takes two minutes and prevents the 400 ms story above. The formula is: rows per partition x bytes per row = bytes per partition. Compare both numbers with the guideline of about 100,000 rows and 100 MB.

The bytes per row is the size of the clustering values plus the size of each regular column, plus a little overhead per cell. For an estimate, add up the column sizes and add 50 percent.

Let us do three tables. First orders_by_customer: a row has placed_at (8 bytes), order_id (16), restaurant_name (about 20), status (about 8) and total_cents (4), so about 56 bytes, say 85 with overhead. An average customer has 40 orders a year, so 40 x 85 = 3.4 KB. A heavy customer with 2,000 orders has 170 KB. No bucket needed, even after ten years.

Second orders_by_restaurant_day, where a row is about 120 bytes. A busy restaurant has 1,500 orders a day: 1,500 rows x 120 = 180 KB per partition, safe. Now see why the day is in the key. Without it, that restaurant would collect 1,500 x 365 x 5 years = 2.7 million rows, 330 MB: far past the guideline.

Third rider_track: 17,280 rows x 50 bytes = 864 KB a day. Without the day, the partition would reach 100,000 rows after about 5.8 days.

partition-size worksheetruns offline
# illustrative, formula: rows x bytes = partition size (guideline 100,000 rows / 100 MB)
table                      rows/partition          bytes/row  partition size   verdict
orders_by_customer         40/yr, heavy 2,000      85         3.4 KB / 170 KB  ✓ no bucket
orders_by_restaurant_day   1,500 busy day          120        180 KB           ✓ day bucket
orders_by_restaurant (no day)  2,700,000 in 5 yrs  120        330 MB           ✗ too big
rider_track (day bucket)   17,280                  50         864 KB           ✓
rider_track (no bucket)    6,300,000 in 1 yr       50         315 MB           ✗ too big

Relational · PostgreSQL

Size is a disk question. A table can have a billion rows and only B-trees to grow.

size.sqlruns offline
SELECT pg_size_pretty(
  pg_total_relation_size('orders'));
-- one number for the whole table;
-- no per-key limit to worry about

Cassandra · CQL

Size is per partition. Check the biggest one, not the average.

size.shruns offline
nodetool tablehistograms \
    quickbite orders_by_customer
# look at the 99th percentile and
# the max of partition size,
# not the mean

The shift: In PostgreSQL you watch the table. In Cassandra you watch the largest partition, because that is the lump that has to move together.

Bridge: composite partition keys and the hot partition

A partition is also the unit of load. All reads and writes for one partition go to the same three replicas. If one partition is far hotter than the others, those three machines work hard while the rest idle, however many nodes you add. This is called a hot partition.

Consider QuickBite's "restaurants of a city" screen. A naive key is city. Mumbai has 1,800 restaurants, so one partition has 1,800 rows, which is a fine size. But every customer opening the app in Mumbai reads that same partition, 3,000 times a second at lunch. Three nodes carry the whole city.

The fix is not to make the partition smaller but to spread the reads: add a small number to the key, for example ((city, shard), restaurant_id) where shard is 0 to 7 and a restaurant picks a shard from a hash of its id. A read asks all 8 shards (8 partition reads) and merges them. Load is now spread over up to 24 replicas rather than 3.

The general lesson: size and heat are separate checks. A partition can be small and still be too popular.

Relational · PostgreSQL

A hot row is a lock fight. You add a read replica to spread reads.

hot.sqlruns offline
-- all reads of city = 'Mumbai'
SELECT * FROM restaurants
WHERE city = 'Mumbai';
-- fix: read replicas, or a cache

Cassandra · CQL

A hot partition is a hot set of three nodes. Spread it with a shard number.

hot.cqlruns offline
CREATE TABLE restaurants_by_city (
  city text, shard int,
  restaurant_id uuid, name text,
  PRIMARY KEY ((city, shard),
               restaurant_id)
);
-- read shards 0..7 and merge

The shift: In PostgreSQL you scale reads by adding copies of the whole database. In Cassandra you scale by making sure the key spreads the work.

Fixing the rider table: time buckets

The cure for an unbounded partition is a bucket: add a slice of time to the partition key so a partition only collects one slice. For riders, one day is natural: 17,280 rows and about 0.9 MB per partition, well inside the guideline.

The price is that a query now names the bucket. "Last hour" is one partition. "Last three days" is three reads (one per day) that the app issues and merges.

Key: (rider_id) only Key: ((rider_id, day), at) ONE partition for R7: 6,307,200 rows after a year about 300 MB, still growing day 1 ................................ day 365 compaction, repair, streaming move it as one lump reads of old data get slower every week day 1 17,280 day 2 17,280 day 3 17,280 ... ... day 365 17,280 each day is its own small partition (about 0.9 MB, illustrative) "today" and "yesterday" are known partitions old days can expire with a TTL
Fig. 18.7 — bucketing. Without a bucket the partition for one rider grows for ever. With the day in the partition key each partition has a known maximum size (86,400 s divided by 5 s = 17,280 rows).

Relational → Cassandra: The WHERE clause

The relational habit: WHERE can name any column in any combination. The planner decides whether to use an index, a scan or a join, and it gets better as statistics grow.

The Cassandra replacement: the WHERE clause is a map reference into the key: equality on every partition-key column, then a left-to-right prefix of the clustering columns, with a range allowed only on the last one you use. Anything else is refused.

Relational · PostgreSQL

Any combination works. The planner finds a path.

track.sqlruns offline
SELECT * FROM rider_track
WHERE rider_id = $1
  AND lat > 18.5
  AND at >= now() - interval '1h';
-- index on (rider_id, at) is used,
-- lat is checked row by row

Cassandra · CQL

The key decides. Non-key columns are filtered by the app.

track.cqlruns offline
SELECT at, lat, lon
FROM rider_track
WHERE rider_id = ?
  AND day = ?
  AND at >= ? AND at < ?;
-- then filter lat in the app

The shift: In SQL the WHERE clause describes what you want. In CQL it describes where to walk.

  1. Name the partition: list every partition-key column with =.
  2. Walk the clustering columns: equality for each, left to right, then at most one range.
  3. Filter the rest in the app: or build another table whose key matches that filter.

The trap: adding ALLOW FILTERING to make the error go away.

filtering a big tableruns offline
# illustrative, table with 2 billion rows over 9 nodes
SELECT * FROM rider_track WHERE lat > 18.5 ALLOW FILTERING;
-- ❌ TRAP: reads every row of every partition on every node
ReadTimeout: Operation timed out - received only 3 responses.

Relational → Cassandra: ORDER BY

The relational habit: ORDER BY is a runtime choice. Ask for newest first today and by price tomorrow; the database sorts the result for you.

The Cassandra replacement: order is fixed when the table is created, by the clustering columns and CLUSTERING ORDER BY. A read just walks the partition forward (or backward). If you need a second order, you need a second table.

Relational · PostgreSQL

Sort at read time, any column.

sort.sqlruns offline
SELECT * FROM orders
WHERE customer_id = $1
ORDER BY placed_at DESC;
-- or ORDER BY total_cents DESC
-- both work; the planner sorts

Cassandra · CQL

Sort order is part of the table.

sort.cqlruns offline
CREATE TABLE orders_by_customer (
  ...
  PRIMARY KEY ((customer_id),
               placed_at, order_id)
) WITH CLUSTERING ORDER BY
  (placed_at DESC, order_id ASC);
-- by total_cents? another table

The shift: Relational sorts the answer. Cassandra stores the data already sorted and only reads it.

  1. Decide the order each screen needs: newest first, oldest first, by score.
  2. Make that the clustering order: first clustering column is the main sort.
  3. One table per different order: "newest" and "most expensive" are two tables.

The trap: trying ORDER BY on a column that is not a clustering column, or in an order the table was not declared with.

what Cassandra saysruns offline
# illustrative
SELECT * FROM orders_by_customer
WHERE customer_id = ? ORDER BY total_cents DESC;
InvalidRequest: Order by currently only supports the ordering of
columns following their declared order in the PRIMARY KEY   -- ❌ TRAP

Relational → Cassandra: Buckets for growing data

The relational habit: a table can grow forever. Add an index on time, and perhaps use table partitioning to drop old months. The size of "a partition" is the database's concern.

The Cassandra replacement: add a time bucket (hour, day, month) or another divider to the partition key, so each partition stays under about 100 MB and 100,000 rows. The size of a partition is now your concern, and you check it with arithmetic before launch.

Relational · PostgreSQL

One big table, a time index, optional partitioning.

track_pg.sqlruns offline
CREATE TABLE rider_track (
  rider_id uuid, at timestamptz,
  lat float8, lon float8
) PARTITION BY RANGE (at);
CREATE INDEX ON rider_track
  (rider_id, at);

Cassandra · CQL

The bucket is in the partition key itself.

track_cql.cqlruns offline
CREATE TABLE rider_track (
  rider_id uuid,
  day      date,
  at       timestamp,
  lat double, lon double,
  PRIMARY KEY ((rider_id, day), at)
);

The shift: PostgreSQL splits a table to manage it. Cassandra splits a partition to keep it small enough to exist.

  1. Estimate rows per partition: writes per second times seconds in the bucket.
  2. Estimate bytes: rows times (sum of column sizes plus overhead), keep under ~100 MB.
  3. Pick the bucket: hour, day or month so both numbers stay under the guideline.
  4. Make the app compute the bucket: from the timestamp it already has.

The trap: a partition with no bound. It looks fine for weeks and then reads slow down and compaction falls behind.

checking partition sizesruns offline
# illustrative nodetool output, no bucket
$ nodetool tablehistograms quickbite rider_track
Partition Size (bytes): 50% 214,000   95% 98,000,000   Max 312,000,000
Cell Count:             50% 4,300     95% 1,900,000     Max 6,300,000
# ❌ TRAP: the biggest partition is 312 MB, over three times the guideline

04 · The modelling method, step by stepFrom Entities to Tables, or From Questions to Tables — Both Ways, Whole QuickBite

A relational designer draws entities, removes repetition, and lets queries come later. A Cassandra designer writes the queries first, then derives each table from one query, and accepts repetition. This section walks both methods on QuickBite and ends with the complete schema each way.

Imagine two engineers get the same one-page brief for QuickBite: customers order from restaurants, restaurants have menus, orders have lines and a status that changes, and riders deliver while the customer watches a map.

Ana works in PostgreSQL. She spends the first day on a diagram of boxes and lines, and decides the key of every box. She does not think about screens yet, because she knows she can add an index or a join for any screen later.

Dev works in Cassandra. On the first day he does not draw a table at all. He walks through the app screen by screen and writes down every read and every write each screen causes. He ends the day with a list of nine questions and how often each is asked.

By the second day both have a design, and the two designs share almost no table names. Fig. 18.8 puts the two methods side by side.

Relational method Cassandra method 1 Conceptual ERD boxes and lines for customers, orders ... 1 Conceptual ERD (kept) same boxes; only for understanding 2 Normal forms remove repeated facts (1NF, 2NF, 3NF) 2 Workflow + access patterns Q1 ... Qn, with frequency and ordering 3 Tables, keys, constraints CREATE TABLE with PK, FK, UNIQUE 3 Logical (Chebotko) diagram one table per Q: key columns marked 4 Write the app any query is allowed; add an index when slow 4 Physical design types, partition sizes, time buckets, TTL 5 Tune with EXPLAIN indexes, query rewrites, partitioning 5 Optimise split big partitions, merge tables, drop unused queries are the OUTPUT of the design queries are the INPUT of the design
Fig. 18.8 — the two methods step by step. The first box is the same in both (understand the business). The second box is where they split: relational normalises, Cassandra collects queries.

Step 2 in practice: the access-pattern list

The list of questions is the main deliverable of a Cassandra design, so write it as a table: what is asked, what is given, what comes back, in what order, how often. Here is Dev's list for QuickBite.

QuickBite access patterns (frequencies are illustrative)
QQuestionGivenReturnsHow often
Q1My orderscustomer id20 newest orders, newest firstvery high
Q2One order with linesorder idheader + every line, by line numbervery high
Q3Restaurant menurestaurant iditems grouped by categoryvery high
Q4Today's orders for a restaurantrestaurant id + dayorders newest firsthigh
Q5Order status timelineorder idstatus events in time orderhigh
Q6Rider live positionrider idlatest pointvery high, write every 5 s
Q7Login by phonephonecustomer idhigh
Q8Customer profilecustomer idname, phone, emailhigh
Q9Replay a routerider id + daypoints in time orderlow

Bridge: how to collect access patterns without guessing

New Cassandra designers often stall on step 2: "how do I know the queries before the app exists?" You do not need all of them, only the ones that carry the product. Use three sources, in this order.

Screens. Open the design mock-ups. Every list, detail page and map is at least one read. For each, write who asks, what they give, what they get back, how many rows, and in what order. QuickBite has about nine such screens. Background jobs and events. Anything that runs without a person: sending a receipt after delivery, paying a restaurant weekly, expiring old rider positions. Each is a read, and often a scan, which you must plan separately, usually with a table built for the job. Numbers. For each query, estimate how often it runs and how big its answer is. A query that runs 900 times a second and returns 20 rows deserves its own table. A query that runs twice a day for an admin can use a slower path, such as an export to a warehouse.

Keep the list short and honest. If a question is rare and slow is acceptable, do not build a table for it; send it to an analytics store instead.

Relational habit

Collect the entities. Queries can be invented later.

collect.txtruns offline
needed now: customers, orders,
  restaurants, riders
needed later: unknown reports
(answer: SQL can do them)

Cassandra habit

Collect the queries, with who asks and how often.

collect.txtruns offline
Q1 my orders       900/s  20 rows
Q4 restaurant board 900/s  ~15 rows
Q9 route replay    2/min   720 rows
report: weekly payout (batch job)

The shift: A Cassandra design is only as good as its list of questions. Rare questions go to another system.

A good test of the list is to read it aloud to a teammate who knows the product but not Cassandra. If they say "you forgot the screen where support looks up an order by the customer's phone number", you have found a missing table (here, a lookup from phone to customer, then customer to orders) before writing any code.

Also write down the write side of every item. A screen that only reads still depends on someone writing the data it shows, and each of those writes will have to reach every table that serves the screen. A design with six read tables and an unclear write path is half a design.

Finally, mark the queries that are allowed to be stale. "My orders" can lag a second behind a new order; "is this order paid?" at checkout cannot. That mark decides, later, which reads need a stronger consistency level and which can be served by any one replica.

Plan to revisit the list every quarter. The cost of changing it is a new table and a backfill, so the earlier a gap is found the cheaper it is.

Step 3: the mapping rules

There are five rules for turning one query into one table. They are mechanical, which is the good news: two engineers following them reach nearly the same table.

  1. Equality columns, partition key: columns the query tests with = go in the partition key. Q1: customer_id.
  2. Order and range columns, clustering: columns the query sorts or ranges on become clustering columns, in that order. Q1: placed_at newest first.
  3. Uniqueness columns, clustering: add whatever else makes two rows different. Q1: order_id.
  4. Everything else is a plain column: the fields the screen shows. Q1: restaurant name, status, total.
  5. Check size: estimate rows and bytes per partition; add a bucket if they can grow without a bound.

Now apply it to the four most important questions, one duo each, before the full schema.

Relational · PostgreSQL

Q1. Join orders to restaurants to show the name.

q1.sqlruns offline
SELECT o.order_id, o.placed_at,
       r.name, o.total_cents
FROM orders o
JOIN restaurants r USING (restaurant_id)
WHERE o.customer_id = $1
ORDER BY o.placed_at DESC LIMIT 20;

Cassandra · CQL

Q1. The name is copied into the row, so no join.

q1.cqlruns offline
SELECT order_id, placed_at,
       restaurant_name, total_cents
FROM orders_by_customer
WHERE customer_id = ?
LIMIT 20;
-- already sorted, newest first

The shift: The join happened once, at write time, when the order was saved.

Relational · PostgreSQL

Q4. Filter by restaurant and date, any index.

q4.sqlruns offline
SELECT * FROM orders
WHERE restaurant_id = $1
  AND placed_at::date = current_date
ORDER BY placed_at DESC;

Cassandra · CQL

Q4. Restaurant and day are the partition key.

q4.cqlruns offline
SELECT * FROM orders_by_restaurant_day
WHERE restaurant_id = ?
  AND day = ?;
-- newest first, one partition

The shift: The date is not a filter any more; it is part of where the row lives.

Relational · PostgreSQL

Q5. Status history is another child table.

q5.sqlruns offline
SELECT status, at
FROM order_status_events
WHERE order_id = $1
ORDER BY at;

Cassandra · CQL

Q5. Events are rows in the order's partition.

q5.cqlruns offline
SELECT status, event_id
FROM order_events_by_order
WHERE order_id = ?;
-- event_id is a timeuuid, so rows
-- are already in time order

The shift: A child table with a foreign key becomes rows in the parent's partition.

Relational · PostgreSQL

Q6. Latest position: find the max time per rider.

q6.sqlruns offline
SELECT DISTINCT ON (rider_id) *
FROM rider_locations
WHERE rider_id = $1
ORDER BY rider_id, at DESC;

Cassandra · CQL

Q6. Keep one row per rider and overwrite it.

q6.cqlruns offline
UPDATE rider_latest
SET at = ?, lat = ?, lon = ?
WHERE rider_id = ?;
SELECT * FROM rider_latest
WHERE rider_id = ?;

The shift: Relational computes "the latest" by looking at history. Cassandra stores "the latest" as its own row.

Bridge: walking Q4 from the screen to the table to the CQL

Let us follow one question all the way down, because this is the exact routine you will repeat for every query. Q4 is "today's orders for a restaurant".

The screen. A tablet in the restaurant kitchen shows a list of today's orders, newest at the top, and refreshes every 10 seconds. With 9,000 restaurants that is about 900 reads per second across the platform. Each read asks for one restaurant's orders for the current day and nothing else. The sentence. "Given a restaurant id and a day, return its orders, newest first, with status and total." Read the sentence for the three things that decide the table: what is given with equality (restaurant id, day), what is the sort (placed_at, newest first), what is returned (status, total, customer name). The key. Both given values are equalities, so both go in the partition key. The sort goes in the clustering columns, descending. A tiebreaker, order_id, keeps two orders in the same millisecond apart. A catch to decide now. "Day" needs a time zone. A restaurant in Pune and a restaurant in London do not end their day at the same instant. Decide that the day is computed in the restaurant's local time zone, and store it that way, or one rush hour will be split between two partitions. The write. Every time an order is placed, the app writes one extra row into this table, as well as the others. Every status change rewrites the status cell in the same row.

Relational · PostgreSQL

Read: one filter, one sort, one index; the planner does the rest.

q4_read.sqlruns offline
SELECT order_id, status, total_cents
FROM orders
WHERE restaurant_id = $1
  AND placed_at >= $2
ORDER BY placed_at DESC;

Cassandra · CQL

Read: both given values name one partition.

q4_read.cqlruns offline
SELECT order_id, status, total_cents
FROM orders_by_restaurant_day
WHERE restaurant_id = ?
  AND day = ?;
-- 900 of these a second, each one
-- partition read

The shift: The relational read hides its cost in the planner. The Cassandra read shows its cost in the key, and the cost is always "one partition".

Relational · PostgreSQL

Write: one INSERT into orders. Q4 reads it by index.

q4_write.sqlruns offline
INSERT INTO orders
 (order_id, customer_id,
  restaurant_id, status,
  placed_at, total_cents)
VALUES ($1,$2,$3,'placed',$4,$5);

Cassandra · CQL

Write: the same order goes into several tables.

q4_write.cqlruns offline
BEGIN BATCH
 INSERT INTO orders_by_id ...;
 INSERT INTO orders_by_customer ...;
 INSERT INTO orders_by_restaurant_day
   ... VALUES (?, ?, ?, ?, ...);
 INSERT INTO order_events_by_order ...;
APPLY BATCH;

The shift: Relational writes once and reads many ways. Cassandra writes many times so each read is one way.

What you see: the cost of a new table, listed once so you can weigh it. For Q4 the extra write is 1 row per order, about 120 bytes, and 120,000 extra writes on a busy day, which is small. The saving is that 900 reads a second never scan.

Relational · PostgreSQL

A new requirement means a new query. Maybe a new index.

newreq.sqlruns offline
-- "orders by rider for payroll"
CREATE INDEX ON orders (rider_id, placed_at);

Cassandra · CQL

A new requirement means a new table, and a plan to fill it.

newreq.cqlruns offline
CREATE TABLE orders_by_rider_day (
  rider_id uuid, day date,
  placed_at timestamp, order_id uuid,
  total_cents int,
  PRIMARY KEY ((rider_id, day),
               placed_at, order_id)
);

The shift: The cost of change moves from "build an index" to "build a table and backfill it".

Bridge: writing one order into four tables, and what if the third write fails

This is the question every relational engineer asks next, so it is worth looking at now, even though the consistency section covers it in full.

In PostgreSQL, "place an order" is one transaction: insert the order, insert its lines, insert the first status event, commit. If any statement fails, everything rolls back, and nobody ever sees half an order. The database promises it.

In Cassandra the same business action is four writes to four tables, and they may live on different nodes. Suppose the first two succeed and the process crashes before the third. The customer sees the order in "my orders", but the restaurant's board does not show it. The kitchen never cooks it.

Cassandra offers a logged batch: you give it all four writes and it records the intent in a log on other nodes first. If you crash, the cluster finishes the batch for you. It is atomic in the sense that all writes will eventually apply. It is not isolated: a reader can briefly see one table updated and another not.

So the design rule is: write the copies in one logged batch, make every write safe to repeat (it is an upsert, so repeating is harmless), and let the screens tolerate a short moment of disagreement. The consistency section gives the exact tools.

Relational · PostgreSQL

One transaction, all or nothing, and isolated.

place_order.sqlruns offline
BEGIN;
INSERT INTO orders ...;
INSERT INTO order_items ...;
INSERT INTO order_status_events ...;
COMMIT;
-- crash before COMMIT = nothing saved

Cassandra · CQL

One logged batch. All copies will apply, but not instantly together.

place_order.cqlruns offline
BEGIN BATCH
 INSERT INTO orders_by_id ...;
 INSERT INTO orders_by_customer ...;
 INSERT INTO orders_by_restaurant_day ...;
 INSERT INTO order_events_by_order ...;
APPLY BATCH;
-- crash = the cluster finishes it

The shift: Relational keeps tables in step with a transaction. Cassandra keeps copies in step with a batch, and accepts a moment of lag between them.

Now the complete designs. First the relational schema that Ana produces. Read it as "eight things, each stored once, connected by foreign keys".

quickbite-relational.sqlruns offline
-- PostgreSQL 18 · the whole relational design
CREATE TABLE customers (
  customer_id uuid PRIMARY KEY,
  name        text NOT NULL,
  phone       text NOT NULL UNIQUE,
  email       text,
  created_at  timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE restaurants (
  restaurant_id uuid PRIMARY KEY,
  name          text NOT NULL,
  city          text NOT NULL
);
CREATE TABLE menu_items (
  item_id       uuid PRIMARY KEY,
  restaurant_id uuid NOT NULL REFERENCES restaurants,
  category      text NOT NULL,
  name          text NOT NULL,
  price_cents   int  NOT NULL,
  available     boolean NOT NULL DEFAULT true
);
CREATE TABLE orders (
  order_id      uuid PRIMARY KEY,
  customer_id   uuid NOT NULL REFERENCES customers,
  restaurant_id uuid NOT NULL REFERENCES restaurants,
  status        text NOT NULL,
  placed_at     timestamptz NOT NULL,
  total_cents   int NOT NULL
);
CREATE TABLE order_items (
  order_id    uuid REFERENCES orders,
  line_no     int,
  item_id     uuid NOT NULL REFERENCES menu_items,
  qty         int NOT NULL,
  unit_price_cents int NOT NULL,   -- snapshot of the price
  PRIMARY KEY (order_id, line_no)
);
CREATE TABLE order_status_events (
  event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_id uuid NOT NULL REFERENCES orders,
  status   text NOT NULL,
  at       timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE riders (rider_id uuid PRIMARY KEY, name text NOT NULL);
CREATE TABLE rider_locations (
  rider_id uuid REFERENCES riders,
  at       timestamptz,
  lat double precision, lon double precision,
  PRIMARY KEY (rider_id, at)
);
-- indexes added when queries are slow:
CREATE INDEX ON orders (customer_id, placed_at DESC);
CREATE INDEX ON orders (restaurant_id, placed_at DESC);
CREATE INDEX ON order_status_events (order_id, at);

And here is the complete Cassandra keyspace that Dev produces from his nine questions. Each table carries the number of the question it answers.

quickbite-cassandra.cqlruns offline
-- Apache Cassandra 5.0 · the whole query-first design
CREATE KEYSPACE quickbite WITH replication =
  {'class': 'NetworkTopologyStrategy', 'dc1': 3};
USE quickbite;

-- Q8 customer profile
CREATE TABLE customers_by_id (
  customer_id uuid PRIMARY KEY,
  name text, phone text, email text, created_at timestamp);
-- Q7 login by phone
CREATE TABLE customers_by_phone (
  phone text PRIMARY KEY, customer_id uuid);
-- Q3 menu, grouped by category
CREATE TABLE menu_by_restaurant (
  restaurant_id uuid, category text, item_id uuid,
  name text, price_cents int, available boolean,
  PRIMARY KEY ((restaurant_id), category, item_id));
-- Q2 one order, header as static columns, lines as rows
CREATE TABLE orders_by_id (
  order_id uuid, line_no int,
  customer_id uuid STATIC, restaurant_id uuid STATIC,
  status text STATIC, placed_at timestamp STATIC,
  total_cents int STATIC,
  item_id uuid, item_name text, qty int, unit_price_cents int,
  PRIMARY KEY ((order_id), line_no));
-- Q1 my orders
CREATE TABLE orders_by_customer (
  customer_id uuid, placed_at timestamp, order_id uuid,
  restaurant_name text, status text, total_cents int,
  PRIMARY KEY ((customer_id), placed_at, order_id))
  WITH CLUSTERING ORDER BY (placed_at DESC, order_id ASC);
-- Q4 restaurant's orders for a day
CREATE TABLE orders_by_restaurant_day (
  restaurant_id uuid, day date, placed_at timestamp, order_id uuid,
  customer_name text, status text, total_cents int,
  PRIMARY KEY ((restaurant_id, day), placed_at, order_id))
  WITH CLUSTERING ORDER BY (placed_at DESC, order_id ASC);
-- Q5 status timeline
CREATE TABLE order_events_by_order (
  order_id uuid, event_id timeuuid, status text, note text,
  PRIMARY KEY ((order_id), event_id));
-- Q6 latest rider position
CREATE TABLE rider_latest (
  rider_id uuid PRIMARY KEY,
  at timestamp, lat double, lon double, order_id uuid);
-- Q9 route replay, one partition per rider per day, expires in 7 days
CREATE TABLE rider_track (
  rider_id uuid, day date, at timestamp, lat double, lon double,
  PRIMARY KEY ((rider_id, day), at))
  WITH default_time_to_live = 604800
  AND compaction = {'class': 'TimeWindowCompactionStrategy',
                    'compaction_window_unit': 'DAYS',
                    'compaction_window_size': 1};

Count the difference. Ana has eight tables and three indexes, and everything is stored once. Dev has nine tables, and an order is written into four of them (orders_by_id, orders_by_customer, orders_by_restaurant_day, order_events_by_order) every time one is placed.

That is the price, and the next section shows how to pay it safely. The reward is that none of the nine reads does a join, a sort or a scan.

Chebotko-style logical diagram: one box per query. K = partition key, C = clustering (arrow = order), S = static Q1 orders_by_customer customer_id K placed_at C ↓ order_id C ↑ restaurant_name status total_cents Q4 orders_by_restaurant_day restaurant_id K day K placed_at C ↓ order_id C ↑ status total_cents Q2 orders_by_id order_id K line_no C ↑ status S customer_id S item_name qty Q5 order_events_by_order order_id K event_id (timeuuid) C ↑ status note Q9 rider_track rider_id K day K at C ↑ lat lon Q6 rider_latest rider_id K at lat lon order_id one "order placed" event is written to the first four tables (4 copies of the facts it needs)
Fig. 18.9 — the logical design for six of the nine QuickBite tables (the lookup tables for Q3, Q7 and Q8 are left out for space). Each box is built from exactly one question.

Relational → Cassandra: Design order: entities first or queries first

The relational habit: start from the nouns of the business, draw the ERD, normalise it, and only then think about queries. The schema is stable; queries come and go.

The Cassandra replacement: start from the verbs of the product: each screen and background job becomes a query or write. The tables are derived from them. When a new screen appears, expect a new table.

Relational habit

Think nouns: customer, order, restaurant, rider.

steps.txtruns offline
1. entities and relationships
2. normalise to 3NF
3. create tables, keys, FKs
4. write queries against them
5. add indexes where it hurts

Cassandra habit

Think verbs: show my orders, mark delivered.

steps.txtruns offline
1. list screens and jobs
2. write each query: given, returns
3. one table per query
4. choose partition + clustering keys
5. write to every table that needs it

The shift: Relational design is stable and asks questions later. Cassandra design is driven by the questions and changes when they change.

  1. Interview the app: walk every screen and write down what it reads and writes.
  2. Write queries as sentences: "Given a customer id, return the 20 newest orders with restaurant name and total."
  3. Derive a table per sentence: using the five mapping rules above.
  4. Review the list again: if two queries differ only in a filter, they might share one table.

The trap: drawing the ERD, converting it one-to-one into tables, and only then asking what queries to support.

the one-to-one portruns offline
# illustrative
ERD -> 8 tables -> 8 tables in CQL, same keys
first query "orders by customer"  -- ❌ TRAP: partition key is order_id
InvalidRequest: ... might involve data filtering
fix after launch = new table + backfill 30M rows

Relational → Cassandra: Normalising and denormalising

The relational habit: store each fact once, in one table. A restaurant's name lives in restaurants; everything else holds the id. A rename is one UPDATE.

The Cassandra replacement: store the fact in every table that needs it for a single read. The restaurant name is copied into orders_by_customer so "my orders" needs no second lookup. Decide for each copied column whether it is a snapshot (fine) or must follow changes (a cost).

Relational · PostgreSQL

Order rows hold an id. The name is joined in.

normal.sqlruns offline
-- orders stores restaurant_id only
SELECT o.order_id, r.name
FROM orders o
JOIN restaurants r USING (restaurant_id)
WHERE o.customer_id = $1;
-- rename = 1 UPDATE on restaurants

Cassandra · CQL

Orders hold the name as it was at order time.

denormal.cqlruns offline
INSERT INTO orders_by_customer
 (customer_id, placed_at, order_id,
  restaurant_name, total_cents)
VALUES (?, ?, ?, 'Spice Hut', ?);
-- rename = past orders keep the old name

The shift: A copy is not duplicate-by-accident; it is a decision about which facts freeze at write time and which are fetched again.

  1. List the columns each screen shows: these are the columns the table needs.
  2. Mark each as snapshot or live: an order total is a snapshot; a restaurant phone number may need to be live.
  3. For live columns, keep one lookup table: and join in the app, or accept a background fix-up job.

The trap: copying a column that changes often, then having to rewrite millions of rows for each change.

rename a restaurant that sits in 600,000 order rowsruns offline
# illustrative
UPDATE orders_by_customer SET restaurant_name = 'Spice Hut 2' ...
-- ❌ TRAP: needs the key of every row: (customer_id, placed_at, order_id)
-- 600,000 writes plus a scan to find them; so store the id, or freeze the name

Relational → Cassandra: Diagram: ERD vs Chebotko diagram

The relational habit: the deliverable is an entity-relationship diagram, with boxes for things and lines (one-to-many, many-to-many) for how they connect.

The Cassandra replacement: the deliverable is a Chebotko diagram: one box per table, with each column marked K (partition key), C (clustering, with an arrow for order) or S (static), and one query label per table. A table with no query label is a mistake.

Relational habit

ERD: things and lines.

erd.txtruns offline
[customers] 1 --- * [orders]
[orders] 1 --- * [order_items]
[restaurants] 1 --- * [orders]
-- lines are foreign keys

Cassandra habit

Chebotko: tables, keys, and the query each answers.

chebotko.txtruns offline
Q1 orders_by_customer
  customer_id K
  placed_at   C v
  order_id    C ^
  total_cents

The shift: An ERD describes the world. A Chebotko diagram describes the queries.

  1. Draw one box per table: with the table name and the query number.
  2. Mark every key column: K, C (with direction) or S.
  3. Trace each query through its table: if a column is missing, add it; if a column is never read, remove it.

The trap: a table drawn without a query, or a query whose columns are not all in one table.

a table nobody readsruns offline
# illustrative design review
orders_by_status   (status K, placed_at C)    Q?  none
-- ❌ TRAP: no question owns this table; and status has only 5 values,
-- so 5 giant partitions would hold every order

05 · RelationshipsTranslating Every Relational Tool — JOIN, Foreign Keys, UNIQUE, Aggregates, Paging, Indexes

A relational database gives you a toolbox for questions you have not thought of yet: JOIN, foreign keys, UNIQUE, GROUP BY, OFFSET, CREATE INDEX. Cassandra has none of these as free, cluster-wide features. This section takes each tool, shows what it does inside PostgreSQL, and shows the Cassandra habit that replaces it.

Here is a story from QuickBite. The "My orders" screen shows, for one customer, their last 20 orders. Each line has the restaurant name, the item names, the total and the status.

In PostgreSQL this is one query joining orders, restaurants, order_items and menu_items. It takes about 4 ms on a warm database, and nobody thinks about it.

The team ports the four tables to Cassandra one for one. Now there is no JOIN, so the application does the join itself: one read for the orders, then one read per restaurant and one read per order for its items. For 20 orders that is about 1 + 20 + 20 = 41 separate reads, each a network round trip.

At 2,000 screen views a second that becomes 82,000 reads a second, and the page that took 4 ms now takes 180 ms at the 99th percentile. The database is not slow. The design is asking it to do a relational job.

Make the invisible visible: how many reads the "My orders" screen needs in each world.

reads per screen view (illustrative numbers)runs offline
# illustrative output: 20 orders on the screen, 2 items each
                         round trips   work done
PostgreSQL, 1 JOIN       1             planner joins 4 tables inside the server
Cassandra, 1:1 port      1 + 20 + 20   the application joins; 41 trips, one slow trip slows the page   ✗
Cassandra, designed      1             one partition, rows already hold the names   ✓

Why: a join is work. Relational databases do the work when you read. Cassandra expects the work to be done when you write, so that a read is only "go to one partition and read".

Bridge: what a JOIN really is, and why Cassandra leaves it out

A JOIN takes rows from two tables and matches them by a shared value. To do that on one PostgreSQL server, the planner looks up the matching rows in an index and glues them together in memory.

In Cassandra the rows of one table are spread across many machines, chosen by the partition key. The customer's row may be on node 2, their orders on node 5, the restaurant on node 9. A join would mean pulling pieces from many machines and gluing them in the middle, at unpredictable cost.

Cassandra's promise is the opposite: every read costs about the same however large the cluster is. To keep that promise it only offers reads that go to one partition. Anything that would cross partitions is something you design away, or do in your own code on purpose.

Relational → Cassandra: JOIN becomes a pre-joined table

The relational habit: store each fact once, in its own table, and join at read time. A restaurant's name lives in one row; every order points to it by restaurant_id.

The Cassandra replacement: decide the screen first, then build a table whose rows are exactly that screen. The restaurant name is copied into every order row. The join is done once, at write time, by your application.

Relational · PostgreSQL

Join four tables at read time.

my_orders.sqlruns offline
SELECT o.id, r.name, o.total, o.status
FROM orders o
JOIN restaurants r ON r.id = o.restaurant_id
WHERE o.customer_id = 7
ORDER BY o.placed_at DESC
LIMIT 20;

Cassandra · CQL

One table that already holds the name.

my_orders.cqlruns offline
SELECT order_id, restaurant_name,
       total, status
FROM orders_by_customer
WHERE customer_id = 7
LIMIT 20;
-- rows are stored newest first

The shift: from "join when you read" to "copy when you write".

Where the join happens Relational · read time Cassandra · write time customers orders order_items menu_items JOIN planner + indexes 4 tables touched on every page view order placed orders_by_customer name + items copied in orders_by_restaurant_day same facts, other key read = 1 partition, 0 joins cost = N copies to write
Fig. 18.10 — The join does not disappear. Relational pays for it on every read, Cassandra pays once when the row is written.

The table behind the Cassandra query is declared once. Its clustering order stores the newest order first, so LIMIT 20 reads the first 20 rows on disk with no sorting.

orders_by_customer.cqlruns offline
CREATE TABLE quickbite.orders_by_customer (
  customer_id     uuid,
  placed_at       timestamp,
  order_id        uuid,       -- tie-breaker: two orders in the same millisecond
  restaurant_id   uuid,
  restaurant_name text,      -- ✅ copied in: the "join" is done at write time
  total_cents     int,
  status          text,
  PRIMARY KEY ((customer_id), placed_at, order_id)
) WITH CLUSTERING ORDER BY (placed_at DESC, order_id ASC);
  1. Write the screen as a sentence: "for one customer, newest orders first, with restaurant name and total".
  2. List every column the screen shows: each one becomes a column in the table, even if it also lives in another table.
  3. Pick the key from the sentence: "for one customer" is the partition key, "newest first" is the clustering column.
  4. Write every copy together: when an order is placed, the application inserts into every table that shows it (the logged batch in section 06 keeps them in step).

The trap: the copied restaurant name can go stale. If the restaurant renames itself, old order rows still show the old name. That is often correct (an old receipt should show the name at the time), and when it is not, you update the copies on purpose.

the symptom of joining in application coderuns offline
# illustrative output: client log, 1:1 port of the schema
GET /my-orders  customer=7
  read orders            3 ms
  read restaurant x20   41 ms   (20 round trips, run in parallel; the slowest one decides)
  read order_items x20  58 ms
total 102 ms at p50, 180 ms at p99   ✗ one slow node slows the whole page

Relational → Cassandra: one-to-many becomes one partition with many rows

The relational habit: a child table with a foreign key to the parent: many order_items rows point to one orders row. To get the children you filter by the parent id (and a B-tree index finds them).

The Cassandra replacement: make the parent id the partition key and let every child be one clustered row inside that partition. All children of one parent sit together on disk, sorted, so reading them is one sequential read.

Relational · PostgreSQL

Child rows point at the parent by id.

order_items.sqlruns offline
CREATE TABLE order_items (
  id       bigserial PRIMARY KEY,
  order_id bigint REFERENCES orders(id),
  item_id  bigint,
  qty      int
);
CREATE INDEX ON order_items(order_id);

Cassandra · CQL

The order and its lines share one partition; header columns are static.

orders_by_id.cqlruns offline
CREATE TABLE orders_by_id (
  order_id  uuid,
  status    text static,   -- header
  total     int static,    -- header
  line_no   int,
  item_name text,
  qty       int,
  PRIMARY KEY ((order_id), line_no)
);

The shift: from "children find their parent through an index" to "children are stored inside the parent's partition".

Here is what the Cassandra table orders_by_id looks like on disk for order 42. The partition key is written once. The header columns (status, total) are static, meaning stored once per partition and shared by every row in it. The lines are clustered rows in line_no order.

If the app also needs to read lines on their own, without the header, a separate order_items_by_order table is the alternative. The single table is the better default when you always show header and lines together.

What you see now: one partition holding a header and three child rows, and the one query that reads them.

partition for order 42, as storedruns offline
# illustrative output
partition key: order_id = 42     static: status='preparing', total=2450
  line_no=1  item_name='Margherita'   qty=1
  line_no=2  item_name='Garlic bread' qty=2
  line_no=3  item_name='Cola'         qty=2
SELECT * FROM orders_by_id WHERE order_id = 42;   ✓ one partition: header + 3 lines in order
SELECT * FROM orders_by_id WHERE item_name = 'Cola';   ✗ not the partition key
  1. Find the parent id the app always has in hand: to show an order, the app has the order id.
  2. Make it the partition key: the parent id goes first in PRIMARY KEY, in double brackets if there are several columns.
  3. Give each child a clustering column: a line number, a time, or an id that gives each child its own place in the partition.
  4. Estimate the partition size: children per parent times row size. 12 lines at 100 bytes is 1.2 KB, tiny. A customer's lifetime of orders may not be.

The trap: a parent with no upper limit on children, such as "all events of a restaurant, ever". One partition then grows without end. The rule of thumb is to keep a partition below roughly 100 MB and 100,000 rows, and to add a time bucket to the key when a parent can grow past that (see the bucketing map in section 03).

the warning when a partition gets hugeruns offline
# illustrative output: system.log
WARN  Writing large partition quickbite/events_by_restaurant:r-17 (412.7 MiB) to sstable ...
# reads of this partition now take seconds and use lots of memory   ✗

Relational → Cassandra: many-to-many becomes two mirrored tables

The relational habit: a junction table (also called a link or bridge table). A restaurant has many cuisines and a cuisine has many restaurants, so a third table holds pairs of ids, and either question is answered with a join through it.

The Cassandra replacement: look at which directions the app really asks. If both ("restaurants serving pizza" and "cuisines of this restaurant"), build one table per direction. Each is keyed by the thing you start from, and the app writes both rows together.

Relational · PostgreSQL

One junction table, two joins.

junction.sqlruns offline
CREATE TABLE rest_cuisine (
  restaurant_id bigint REFERENCES restaurants,
  cuisine_id    bigint REFERENCES cuisines,
  PRIMARY KEY (restaurant_id, cuisine_id)
);
SELECT r.name FROM restaurants r
JOIN rest_cuisine rc ON rc.restaurant_id=r.id
WHERE rc.cuisine_id = 5;

Cassandra · CQL

One table per question.

mirrors.cqlruns offline
CREATE TABLE restaurants_by_cuisine (
  cuisine text, restaurant_id uuid,
  name text,
  PRIMARY KEY ((cuisine), restaurant_id));

CREATE TABLE cuisines_by_restaurant (
  restaurant_id uuid, cuisine text,
  PRIMARY KEY ((restaurant_id), cuisine));

The shift: from "one link table, many questions" to "one table per direction you ask".

Many-to-many: restaurants and cuisines Relational Cassandra restaurants rest_cuisine cuisines both questions = JOIN through the middle table one write restaurants_by_cuisine partition: cuisine cuisines_by_restaurant partition: restaurant each question = 1 partition the app writes both rows
Fig. 18.11 — One junction table answers both questions with a join. Cassandra keeps one table per direction and writes both together.

Adding one pair means two inserts, one per table. Because the two rows must agree, they go in one logged batch (explained in the next section).

tag a restaurant with a cuisineruns offline
BEGIN BATCH
  INSERT INTO restaurants_by_cuisine (cuisine, restaurant_id, name)
    VALUES ('pizza', 11111111-aaaa-4bbb-8ccc-000000000001, 'Luigi''s');
  INSERT INTO cuisines_by_restaurant (restaurant_id, cuisine)
    VALUES (11111111-aaaa-4bbb-8ccc-000000000001, 'pizza');
APPLY BATCH;
  1. List the directions: write each question as "given X, list Y". Two questions, two tables.
  2. Drop the directions nobody asks: if the app never lists restaurants by cuisine, only one table exists.
  3. Copy what the screen shows: the restaurant name goes into restaurants_by_cuisine so the list needs no second read.
  4. Write both rows in one batch: the two tables are copies of one fact.

The trap: a very popular value makes a very big partition. All restaurants for 'pizza' in a whole country would live in one partition and one set of replicas. Add a region or a bucket to the partition key, such as (cuisine, city).

hot partition, seen from nodetoolruns offline
# illustrative output: nodetool tablehistograms quickbite restaurants_by_cuisine
Partition Size (bytes)   99th: 38,000,000   Max: 214,000,000   ✗ one cuisine = one huge partition
# fix: PRIMARY KEY ((cuisine, city), restaurant_id)

Relational → Cassandra: a child table becomes a collection or UDT in the row

The relational habit: normalise. Phone numbers, tags or addresses go into their own table, one row each, so nothing is repeated and each can be queried alone.

The Cassandra replacement: when a small group of values is always read together with its parent and never searched alone, put it inside the parent row. A set, list or map holds simple values; a user-defined type (UDT, a named bundle of fields) holds a small structure.

Relational · PostgreSQL

A child table and a join for the addresses.

addresses.sqlruns offline
CREATE TABLE addresses (
  id          bigserial PRIMARY KEY,
  customer_id bigint REFERENCES customers,
  label       text,
  street      text,
  city        text
);
-- read: JOIN customers + addresses

Cassandra · CQL

Addresses live inside the customer row.

addresses.cqlruns offline
CREATE TYPE address (
  street text, city text);

CREATE TABLE customers_by_id (
  customer_id uuid PRIMARY KEY,
  name        text,
  tags        set<text>,
  addresses   map<text, frozen<address>>
);

The shift: from "one fact, one row, in its own table" to "a small group of facts, one cell group in its parent".

Reading the customer returns the addresses in the same single read. Writing to one element does not rewrite the rest.

use the collectionsruns offline
UPDATE customers_by_id SET tags = tags + {'vegan'}
  WHERE customer_id = 11111111-aaaa-4bbb-8ccc-000000000007;

UPDATE customers_by_id
  SET addresses['home'] = {street: '12 Elm St', city: 'Leeds'}
  WHERE customer_id = 11111111-aaaa-4bbb-8ccc-000000000007;

SELECT name, tags, addresses FROM customers_by_id
  WHERE customer_id = 11111111-aaaa-4bbb-8ccc-000000000007;
  1. Test "read together, never alone": if the app always shows the addresses with the customer and never asks "all customers in Leeds", embed them.
  2. Test "small": a collection is read whole, so keep it to tens of elements, not thousands. Check the current docs for limits.
  3. Choose the shape: set for unique values, list for ordered values (appends are fine, edits by position are costly), map for labelled values.
  4. Freeze nested types: a UDT inside a collection is written frozen<...>, which means it is replaced as a whole, not edited field by field.

The trap: using a collection as a table. A list of every order a customer ever placed grows without bound, is read in full on every query, and cannot be filtered. Unbounded children belong in clustering rows (the one-to-many map above), not in a collection.

a collection that grew too largeruns offline
CREATE TABLE customers_bad (
  customer_id uuid PRIMARY KEY,
  order_ids   list<uuid>      -- ❌ TRAP: 50,000 orders later, every read pulls all of them
);

Relational → Cassandra: the foreign key becomes application discipline

The relational habit: declare REFERENCES and let the database refuse an order for a customer who does not exist, and refuse to delete a customer who still has orders.

The Cassandra replacement: there is no foreign key. Nothing checks that the id you write exists. The application checks first (a read), or the design makes a dangling id harmless, and a cleanup job removes orphans.

Relational · PostgreSQL

The database enforces the link.

fk.sqlruns offline
ALTER TABLE orders
  ADD FOREIGN KEY (customer_id)
  REFERENCES customers(id)
  ON DELETE RESTRICT;

INSERT INTO orders (customer_id)
VALUES (9999);
-- ERROR: key not present

Cassandra · CQL

The database accepts any id; the app guards it.

no_fk.cqlruns offline
-- no REFERENCES exists in CQL
INSERT INTO orders_by_customer
  (customer_id, placed_at, order_id)
VALUES (9999, toTimestamp(now()), uuid());
-- ✅ accepted, no check at all

-- app: SELECT 1 FROM customers_by_id
--      WHERE customer_id = ?

The shift: from "the database guards integrity" to "the application and the design guard it".

  1. Decide if it matters: for an order, a customer id that came from the logged-in session is already known to exist. No check is needed.
  2. Check at the edge: if the id comes from outside, read the parent first. The read is cheap (one partition by key).
  3. Plan deletes: deleting a customer means deleting from every table that holds their rows. List those tables once, in code, and test it.
  4. Keep money and stock elsewhere: where a dangling reference is a real loss, keep that data in PostgreSQL (section 07 shows the split).

The trap: deleting the parent and leaving the children. In PostgreSQL ON DELETE CASCADE would remove them. In Cassandra nothing happens, and the orphans sit in orders_by_customer under an id with no customer.

orphans after deleting the parentruns offline
DELETE FROM customers_by_id WHERE customer_id = 9999;
SELECT count(*) FROM orders_by_customer WHERE customer_id = 9999;
-- illustrative output: 37   ❌ TRAP: children are still there; nothing cascaded

Relational → Cassandra: UNIQUE becomes the primary key or a lightweight transaction

The relational habit: UNIQUE (email). Two people cannot register the same email, because the second insert fails.

The Cassandra replacement: only the primary key is unique, because a second write with the same key replaces the first. To make an email unique, make it the primary key of its own table (customers_by_email) and insert with IF NOT EXISTS, a lightweight transaction (LWT) that checks and writes as one step.

Relational · PostgreSQL

A constraint rejects the duplicate.

unique.sqlruns offline
ALTER TABLE customers
  ADD UNIQUE (email);

INSERT INTO customers (email)
VALUES ('a@x.com');   -- ok
INSERT INTO customers (email)
VALUES ('a@x.com');
-- ERROR: duplicate key

Cassandra · CQL

The key is unique; IF NOT EXISTS claims it.

claim_email.cqlruns offline
CREATE TABLE customers_by_email (
  email       text PRIMARY KEY,
  customer_id uuid);

INSERT INTO customers_by_email
  (email, customer_id)
VALUES ('a@x.com', uuid())
IF NOT EXISTS;

The shift: from "a constraint on any column" to "uniqueness belongs to the key, and checking costs a slow lightweight transaction".

The result of an IF NOT EXISTS tells you whether you won. It carries a column named [applied].

claiming the same email twiceruns offline
# illustrative output (cqlsh)
 [applied]
-----------
      True        <- first claim wins: row written

 [applied] | email   | customer_id
-----------+---------+-------------
     False | a@x.com | 3f9c...      <- second claim loses and sees the winner
  1. Make a table whose key is the value: customers_by_email with email as the key.
  2. Claim first, then write the rest: run the IF NOT EXISTS insert; only if [applied] is true, write the customer row and the other tables.
  3. Handle the loser: on False, tell the user the email is taken. Clean up a claim if later steps fail.
  4. Use sparingly: an LWT runs a Paxos round with about four round trips and is much slower than a normal write. Do it for sign-up, not for every click.

The trap: checking with a SELECT and then inserting. Two requests can both see "not found" and both write, and the later write silently replaces the earlier one (last write wins).

check-then-insert raceruns offline
-- request A and request B run at the same moment
SELECT * FROM customers_by_email WHERE email = 'a@x.com';   -- A: no row   B: no row
INSERT INTO customers_by_email (email, customer_id) VALUES ('a@x.com', uuid());
-- ❌ TRAP: both succeed; B overwrote A; two people believe they own the email

Relational → Cassandra: COUNT / SUM / GROUP BY becomes a number kept up to date

The relational habit: store the raw rows and compute the totals when someone asks: SELECT restaurant_id, count(*), sum(total) ... GROUP BY restaurant_id. The database scans and groups.

The Cassandra replacement: decide which totals the screen needs (for example "orders per restaurant per day") and keep a table holding that number. Either write the total with every event (a counter table, see section 06) or compute it in a background job. Reading it is then one partition.

Relational · PostgreSQL

Group the raw rows on demand.

daily_totals.sqlruns offline
SELECT restaurant_id,
       count(*), sum(total_cents)
FROM orders
WHERE placed_at::date = '2026-11-23'
GROUP BY restaurant_id;

Cassandra · CQL

Read a number that was kept up to date.

daily_totals.cqlruns offline
CREATE TABLE orders_per_day (
  restaurant_id uuid,
  day           date,
  orders        counter,
  PRIMARY KEY ((restaurant_id), day));

UPDATE orders_per_day SET orders = orders + 1
WHERE restaurant_id = ? AND day = ?;

The shift: from "compute the answer when asked" to "keep the answer up to date as events arrive".

Cassandra does have count(*), sum, avg, min, max and a GROUP BY. They work well inside one partition. They are not a shortcut across the cluster: without a partition key the query scans every partition on every node.

aggregates that are fine vs aggregates that scanruns offline
-- ✅ one partition: reads only that customer's rows
SELECT count(*), sum(total_cents) FROM orders_by_customer
WHERE customer_id = 11111111-aaaa-4bbb-8ccc-000000000007;

-- ❌ TRAP: no partition key: visits every partition on every node
SELECT count(*) FROM orders_by_customer;
-- illustrative output: ReadTimeout after 12000 ms (table has 2 billion rows)
  1. Name the number: "orders per restaurant per day", "unread messages per user".
  2. Give it a key: restaurant and day form the key, so reading one day is one row.
  3. Update it on write: a counter increment, or a write of a computed value. Do not read, add and write back.
  4. Accept approximate: counters can drift if a write is retried. For money use a ledger of events instead and total it elsewhere.

The trap: running analytics queries on the operational cluster. A dashboard that asks for "orders by city this month" scans everything and slows the live app. Send events to an analytics store (Kafka to a warehouse, or Spark) instead.

Relational → Cassandra: OFFSET becomes a paging state

The relational habit: page 5 is LIMIT 20 OFFSET 80. The database counts and skips 80 rows, then returns 20. It works, though it gets slower the deeper the page.

The Cassandra replacement: there is no OFFSET. The driver asks for a page of rows (the fetch size) and gets back a paging state, an opaque bookmark. To get the next page you send the bookmark back. You can only move forward from where you are, not jump to page 5.

Relational · PostgreSQL

Skip rows by count.

offset.sqlruns offline
SELECT id, total
FROM orders
WHERE customer_id = 7
ORDER BY placed_at DESC
LIMIT 20 OFFSET 80;

Cassandra · CQL

Continue from a bookmark, or from the last key.

keyset.cqlruns offline
-- page 1
SELECT * FROM orders_by_customer
WHERE customer_id = 7 LIMIT 20;
-- next page: after the last row seen
SELECT * FROM orders_by_customer
WHERE customer_id = 7
  AND placed_at < ?   -- last placed_at
LIMIT 20;

The shift: from "skip N rows" to "continue from where the last page ended".

With the Java driver the bookmark is handed back for you. The code below fetches one page, keeps the bookmark, and uses it for the next page.

PagedOrders.java (driver 4.x)runs offline
PreparedStatement ps = session.prepare(
    "SELECT order_id, total_cents FROM quickbite.orders_by_customer WHERE customer_id = ?");

BoundStatement first = ps.bind(customerId).setPageSize(20);          // page size, not LIMIT
ResultSet page1 = session.execute(first);
ByteBuffer bookmark = page1.getExecutionInfo().getPagingState();     // null when no more rows

// later request: send the bookmark back (it can travel to the browser as a token)
BoundStatement next = ps.bind(customerId).setPageSize(20).setPagingState(bookmark);
ResultSet page2 = session.execute(next);                             // ✅ continues, no skipping
  1. Choose "load more", not "jump to page": design the screen as an infinite scroll or Next button.
  2. Hand the bookmark to the client: encode it (for example base64) as a cursor in your API.
  3. Keep the same query: a bookmark is only valid for the same statement and the same bound values.
  4. If you must jump: store a page number in the clustering key, or use a keyset (the second query in the duo above).

The trap: trying to fake OFFSET by reading and throwing away rows. Reading 8,000 rows to show rows 8,001 to 8,020 does all the work of reading them, and the cost grows with every page.

fake offset: cost grows with the page numberruns offline
# illustrative output: client log
page  1: read    20 rows   4 ms
page 50: read 1,000 rows  71 ms   ✗ rows 1..980 fetched only to be dropped
page 400: read 8,000 rows 590 ms  ✗

Relational → Cassandra: CREATE INDEX becomes SAI, a view, or a table you build

The relational habit: a query is slow because a column is not indexed, so add CREATE INDEX. The planner uses it for any query that filters on that column, with no change to the application.

The Cassandra replacement: first ask whether the question deserves its own table keyed by that column. That is the normal answer. For some queries, a Storage-Attached Index (SAI, new in Cassandra 5.0) is a reasonable extra tool. The older secondary index, SASI and materialized views are weaker choices.

Relational · PostgreSQL

Add an index and ask anything.

index.sqlruns offline
CREATE INDEX orders_status_idx
  ON orders (status);

SELECT * FROM orders
WHERE status = 'late';

Cassandra · CQL

Build the table for the question.

late_orders.cqlruns offline
CREATE TABLE late_orders_by_city (
  city     text,
  placed_at timestamp,
  order_id  uuid,
  PRIMARY KEY ((city), placed_at, order_id)
);
SELECT * FROM late_orders_by_city
WHERE city = 'Leeds' LIMIT 50;

The shift: from "index the column, ask anything" to "the key is the index, so build a table per question".

Finding rows by a column that is not the partition key Index query, no partition key Table built for the question coordinator coordinator n1 n1 n2 n2 n3 n3 n4 n4 n5 n5 n6 n6 asks 6 of 6 nodes slower as the ring grows token says: n4 (plus its copies) same speed at 6 or 600 nodes
Fig. 18.12 — Without the partition key, a query fans out to the whole ring. A table keyed by the question goes straight to its owners.

Why is the index query slow at scale? Data is split across nodes by partition key. An index on status is stored beside the data on each node, so "which orders are late?" has no partition key to route by. The coordinator must ask nodes, and the more nodes you add, the more it asks.

Ways to find rows by a non-key column in Cassandra 5.0
OptionPick it whenCost or catch
Hand-built table (default)The query is frequent or must be fast and predictable.You write it yourself on every change; more disk; keep copies in step.
SAI (CREATE INDEX ... USING 'sai')Extra filters inside one partition, or occasional searches with a modest result; supports ranges and several columns.Without the partition key the query can still touch many nodes. Check the current docs for limits.
Legacy secondary indexRarely: low-cardinality column, always used together with the partition key.Asks every node when the partition key is missing; poor for high or very low cardinality.
Materialized viewNot for production in Cassandra 5.0.Experimental and off by default; known repair and consistency problems.
SASIDo not start new work with it.Deprecated in favour of SAI.

A short example of SAI. The index is declared with the usual CREATE INDEX syntax plus USING 'sai', and it works best when the query also gives the partition key.

sai.cqlruns offline
CREATE INDEX orders_status_sai
  ON quickbite.orders_by_customer (status) USING 'sai';

-- ✅ partition key given: one partition, status filtered by the index
SELECT * FROM quickbite.orders_by_customer
WHERE customer_id = 11111111-aaaa-4bbb-8ccc-000000000007 AND status = 'late';

-- ⚠ no partition key: allowed with SAI, but it can fan out across the ring
SELECT * FROM quickbite.orders_by_customer WHERE status = 'late' LIMIT 50;
  1. Ask "is this a main screen?": if yes, it earns its own table.
  2. Ask "do I always have the partition key?": if yes, an index inside the partition is cheap, and SAI fits.
  3. Ask "is this an occasional lookup or admin search?": then SAI without the partition key may be acceptable, with a LIMIT and a timeout you have tested.
  4. Never reach for ALLOW FILTERING as a fix: it only turns off the safety check; the scan stays.

The trap: adding an index (or ALLOW FILTERING) to make a relational-shaped query run, and finding it works in test with 10,000 rows and times out in production with 2 billion.

works small, fails bigruns offline
# illustrative output (cqlsh)
cqlsh> SELECT * FROM orders_by_customer WHERE status = 'late' ALLOW FILTERING;
test cluster, 10 k rows:       41 ms
production, 2 billion rows:    ReadTimeout: Operation timed out - received only 0 responses   ✗

One more tool from the relational box is ORDER BY. It follows the same idea as the others: the sort order is chosen when the table is created (CLUSTERING ORDER BY), not when you ask. That is covered in the ORDER BY map in section 03. And "find the row by its id" is the primary key lookup in section 02.

06 · ConsistencyTransactions, Consistency and Deletes — What ACID Becomes in Cassandra

PostgreSQL gives you ACID transactions on one server: several changes succeed together or not at all, and nobody sees half of them. Cassandra keeps many copies of each row on many machines and lets you choose, per query, how many copies must agree. This section maps transactions, consistency, deletes, expiry and counting.

Here is a QuickBite incident. A rider taps "delivered". The app updates two tables: orders_by_customer, so the customer sees "Delivered", and orders_by_restaurant_day, so the restaurant's dashboard closes the order.

The first write succeeds. Then the node handling the second write is restarted for patching, and the write times out. The app logs an error and moves on.

The customer now sees "Delivered". The restaurant dashboard still says "Preparing", and the restaurant is told there are 14 late orders when there are none. Support finds it two days later by comparing the tables.

In PostgreSQL this could not happen: both updates would sit inside BEGIN ... COMMIT. In Cassandra the two tables are separate partitions, perhaps on separate machines, and there is no transaction around them unless you ask for one.

Make the invisible visible: the two tables after the half-finished update.

two copies of one fact, now disagreeingruns offline
# illustrative output
orders_by_customer         order 42   status = delivered     ✓ written
orders_by_restaurant_day   order 42   status = preparing     ✗ write timed out; never retried
# the app saw an error, did not retry, and no transaction undid the first write

Why: every denormalised table is a separate write. Keeping them in step is now a job for you, using a batch, a retry, or a repair job.

Bridge: what ACID promises, and what Cassandra offers instead

ACID is four promises. Atomic: all changes in a transaction happen or none do. Consistent: constraints still hold afterwards. Isolated: concurrent transactions do not see each other's half-done work. Durable: once committed, it survives a crash.

Cassandra keeps durability (a commit log on disk before it replies). It gives atomicity only inside a batch. It gives no isolation across rows, and no constraints beyond the primary key. In return you get a database that keeps taking writes while nodes fail.

What Cassandra adds is a dial: the consistency level, which says how many of the copies (replicas) must answer before a read or write counts as done.

Relational → Cassandra: BEGIN / COMMIT becomes a logged batch, or a lightweight transaction

The relational habit: wrap related changes in one transaction and trust the database to commit all or none. A conditional change is UPDATE ... WHERE status = 'preparing' inside the transaction, with a row lock.

The Cassandra replacement: use a logged batch to make several writes (in several tables) eventually all apply. It is atomic but not isolated. For a conditional change on one row, use a lightweight transaction (LWT), written IF, which is correct for one partition but slow.

Relational · PostgreSQL

One transaction around both changes.

deliver.sqlruns offline
BEGIN;
UPDATE orders
  SET status = 'delivered'
  WHERE id = 42;
INSERT INTO order_events
  (order_id, status)
  VALUES (42, 'delivered');
COMMIT;

Cassandra · CQL

A logged batch over both tables.

deliver.cqlruns offline
BEGIN BATCH
  UPDATE orders_by_customer
    SET status = 'delivered'
    WHERE customer_id = ? AND placed_at = ?
      AND order_id = ?;
  UPDATE orders_by_restaurant_day
    SET status = 'delivered'
    WHERE restaurant_id = ? AND day = ?
      AND placed_at = ? AND order_id = ?;
APPLY BATCH;

The shift: from "the database isolates and rolls back" to "the batch guarantees every part eventually lands, and you accept brief disagreement".

Logged batch keeping two tables in step app BEGIN BATCH coordinator batchlog copies on 2 other nodes orders_by_customer orders_by_restaurant_day 1 save plan 2 apply both 3 all applied: batchlog entry deleted. Coordinator died: a replica replays the plan. Not isolated: a reader may see table 1 updated a moment before table 2.
Fig. 18.14 — If the coordinator dies after step 1, another node replays the saved plan. All parts eventually apply, but readers can see one before the other.

The coordinator first stores the plan (the batchlog) on two other nodes. Then it applies the writes. If it dies halfway, another node finds the plan and finishes the job, so you never end with only one table updated forever.

What a logged batch does not give you is isolation. A reader can see table 1 updated and table 2 not yet. It also does not make writes faster; it is slower than separate writes because of the batchlog. The server warns at 5 KiB of batch size and rejects at 50 KiB.

For "only if it is still in this state", use an LWT. It checks and writes in one agreed step, using the Paxos protocol (about four round trips between replicas).

claim a delivery with IFruns offline
-- only one rider can take the order: the first claim wins
UPDATE quickbite.deliveries_by_order
SET rider_id = 11111111-aaaa-4bbb-8ccc-0000000000f1, status = 'assigned'
WHERE order_id = 11111111-aaaa-4bbb-8ccc-000000000042
IF status = 'ready';
-- illustrative output:  [applied] = True   (or False plus the current status)
  1. List the copies of the fact: every table that stores "status" gets the same update.
  2. Put them in one logged batch: keep it small (a handful of statements, a few KB). Never use it to load bulk data.
  3. Make writes safe to repeat: updates that set a value (status = 'delivered') are idempotent, so a retry of the whole batch is harmless.
  4. Use IF only for real races: two riders, one slot; one username; one coupon. Everything else uses a normal write.

The trap: putting statements for many different partitions into an unlogged batch "for speed". The coordinator becomes a bottleneck for all of them, and nothing protects you from partial failure.

oversized batch, as the server reports itruns offline
# illustrative output: system.log
WARN  Batch for [quickbite.events_by_order] is of size 18.2KiB, exceeding specified threshold of 5.0KiB by 13.2KiB.
ERROR Batch too large   (fail threshold 50.0KiB)   ✗ one hot coordinator, all-or-nothing retries

A word about the future. Cassandra 6.0 is in alpha as this is written (not for production). Its headline feature, Accord, adds general ACID transactions across partitions, written BEGIN TRANSACTION ... COMMIT TRANSACTION, switched on per table. That would cover cases a batch cannot. Today you design with batches and LWTs; check the current docs before relying on Accord.

Relational → Cassandra: one truth becomes tunable consistency (R + W > RF)

The relational habit: one primary server holds the truth. Read replicas may lag a little, and you route important reads to the primary. Either you read the latest or you read something stale; there is no dial per query.

The Cassandra replacement: every row has RF copies (replication factor, usually 3). For each query you choose a consistency level (CL): how many replicas must answer. If writes reach W replicas and reads ask R replicas and R + W > RF, every read overlaps a replica that has the latest write.

Relational · PostgreSQL

Choose primary or replica for a read.

replicas.sqlruns offline
-- app config, not SQL:
--   writes  -> primary
--   reads   -> replica (may lag)
--   must-be-fresh -> primary

SHOW synchronous_commit;
-- on = wait for the standby too

Cassandra · CQL

Pick a level per statement.

levels.cqlruns offline
-- cqlsh: applies to the next statements
CONSISTENCY LOCAL_QUORUM;

INSERT INTO orders_by_customer (...);
-- RF=3: 2 of 3 replicas must ack

SELECT * FROM orders_by_customer
WHERE customer_id = ?;  -- 2 of 3 answer

The shift: from "which server do I ask" to "how many copies must agree, chosen per question".

Quorum write plus quorum read, RF = 3 replica A value v2 replica B value v2 replica C still v1 writer CL = QUORUM (2) copy to C still travelling reader CL = QUORUM (2) reads v2 from B and v1 from C: newest timestamp wins, returns v2 W + R = 2 + 2 = 4 is greater than RF = 3, so the groups must overlap
Fig. 18.13 — Write to 2 of 3 and read from 2 of 3: any two groups of two out of three share a replica, so the read sees the newest version.

The numbers, worked by hand for RF = 3. A quorum is a majority: floor(RF / 2) + 1, which is 2 here.

Consistency levels with RF 3 (one datacentre)
Write CLRead CLW + RStrong?If one replica is down
ONE (1)ONE (1)2No, can read staleWorks
QUORUM (2)ONE (1)3No (3 is not more than 3)Works
ONE (1)QUORUM (2)3NoWorks
QUORUM (2)QUORUM (2)4Yes (4 > 3)Works with 2 of 3 up
ALL (3)ONE (1)4YesWrites fail, 1 down

With several datacentres, LOCAL_QUORUM counts only replicas in the local datacentre. It gives the same overlap there without waiting for a slow link between regions, and it is the usual choice.

  1. Start from the question: "can this read be a few seconds old?" A product list can. "Is this seat free?" cannot.
  2. Pick the pair: LOCAL_QUORUM writes and LOCAL_QUORUM reads for the strong default; LOCAL_ONE for fast, tolerant reads like a rider map.
  3. Check the arithmetic: write W plus read R must be greater than RF if you need the latest value.
  4. Plan for outages: with RF 3 and quorum, one node can be down and everything still works. Two down, and quorum is gone.

The trap: carrying over "the database is always consistent". With the default level of ONE on both sides, a customer can place an order and not see it on the next screen, because the read hit a replica that had not yet got the write.

read-your-own-write failingruns offline
# illustrative output: write CL ONE, read CL ONE, RF 3
t=0 ms   INSERT order 42   acked by replica A (1 of 3)         -> app says "order placed"
t=3 ms   SELECT my orders  served by replica C (not yet updated)  -> order 42 missing   ✗
# fix: LOCAL_QUORUM for both, or read the order id returned by the write

If one replica missed a write, the next quorum read notices and repairs it quietly (read repair), and a scheduled nodetool repair fixes the rest. Section 08 covers repair.

Bridge: last write wins, with no lock to stop it

In PostgreSQL, two people editing the same row take turns: one waits on a lock, or one fails and retries. In Cassandra nobody waits. Every write carries a timestamp, and when two writes hit the same cell, the one with the later timestamp wins. This is last write wins (LWW).

Writes are also upserts: INSERT and UPDATE are the same thing. If the row exists it is changed, and if not it is created. There is no "duplicate key" error and no read before the write.

Relational · PostgreSQL

Row lock: the second editor waits.

lock.sqlruns offline
-- session A
BEGIN;
SELECT * FROM orders
  WHERE id = 42 FOR UPDATE;
-- session B blocks here until
-- A commits or rolls back

Cassandra · CQL

No lock: both writes land, the later one stays.

lww.cqlruns offline
-- client A, at 10:00:00.120
UPDATE orders SET status = 'ready'
 WHERE id = 42;
-- client B, at 10:00:00.118
UPDATE orders SET status = 'cooking'
 WHERE id = 42;
-- result: 'ready' (later timestamp)

The shift: from "serialise the writers" to "let everyone write, and decide the winner by timestamp".

The winner is decided by the timestamp, not by which request arrived last at the server. Writers' clocks that disagree can pick a wrong winner, so keep clocks synchronised (NTP) on app servers and nodes. Write each fact so that "latest wins" is what you mean, or make the rows append-only (each event its own row) so nothing is overwritten.

What you see: two writers fighting over one cell, and a safer shape.

overwrite vs appendruns offline
# illustrative output
one cell, two writers:     order 42 status  -> 'ready' (t=...120) beats 'cooking' (t=...118)   status 'cooking' lost
event rows, same writers:  order 42  t=...118 cooking | t=...120 ready      ✓ both kept; the latest is read by clustering order

Relational → Cassandra: DELETE becomes a tombstone

The relational habit: DELETE removes the row. It is gone; the space is reclaimed later by vacuum, and nothing about the delete lives on in a way you must manage.

The Cassandra replacement: a delete writes a new record called a tombstone, a marker that says "this was deleted at time T". It must travel to all replicas, and be kept for gc_grace_seconds (default 864000, which is 10 days) so a replica that was offline cannot bring the old value back.

Relational · PostgreSQL

The row is removed.

delete.sqlruns offline
DELETE FROM cart_items
WHERE cart_id = 5
  AND item_id = 9;

SELECT count(*) FROM cart_items
WHERE cart_id = 5;
-- the row is simply not there

Cassandra · CQL

A marker is written; the row stays on disk for now.

delete.cqlruns offline
DELETE FROM cart_items
WHERE cart_id = 5
  AND item_id = 9;
-- writes a tombstone:
-- (cart 5, item 9) deleted at T
-- reads skip it, but must read it
-- gc_grace_seconds = 864000

The shift: from "delete erases" to "delete writes a marker that is kept, then cleaned up later".

Why a tombstone is kept for gc_grace_seconds tombstone kept: gc_grace 10 days node C is down for 11 days 0 2 4 6 8 10 12 14 16 18 day DELETE (day 0) day 10: compaction may purge day 12: C returns, offers old row
Fig. 18.15 — A delete is a marker. If a replica misses it and the marker is purged first, that replica later offers the old row as live data.

Walk the timeline. At day 0 the tombstone is written to replicas A and B. Replica C is down and misses it. If the tombstone were purged at day 5, then at day 12 C would return, still hold the live row, and the cluster would see the row as alive on one copy and "no information" on the others. The old row would be copied back. This is a zombie row.

The rule: every replica must be repaired (see nodetool repair, section 08) at least once inside the gc_grace_seconds window. Within that window, compaction keeps the tombstone. After it, compaction may remove the tombstone along with the data it covers.

  1. Prefer not to delete: keep a status column such as cancelled, or set a TTL (next map) so expiry removes data.
  2. Delete whole partitions, not many cells: one partition tombstone is cheaper than 50,000 row tombstones.
  3. Schedule repair inside the window: every node repaired at least every 10 days, many teams do it weekly.
  4. Watch tombstones per read: the server warns at 1,000 scanned tombstones in one read (tombstone_warn_threshold) and fails the query at 100,000 (tombstone_failure_threshold).

The trap: using Cassandra as a queue. A job table where workers insert a row, process it, then delete it piles up tombstones at the front of the partition. Each poll for "the oldest job" has to read through all of them before finding a live row.

queue anti-pattern: reads slow down as jobs are processedruns offline
CREATE TABLE jobs (queue text, id timeuuid, payload text, PRIMARY KEY ((queue), id));
SELECT * FROM jobs WHERE queue = 'emails' LIMIT 1;    -- "next job"
-- ❌ TRAP: after 1 million inserts and deletes the oldest 999,999 rows are tombstones
-- illustrative output: TombstoneOverwhelmingException: Scanned over 100001 tombstones; query aborted

For queues use a tool made for it, such as Kafka (Chapter E17), or keep jobs in PostgreSQL where a delete is cheap.

Relational → Cassandra: a cleanup job becomes TTL

The relational habit: a nightly job runs DELETE FROM sessions WHERE expires_at < now(). It scans, deletes and leaves bloat for vacuum.

The Cassandra replacement: give each write a time to live (TTL) in seconds, or set default_time_to_live on the table. After that time the data stops being returned and is cleaned in compaction. No job, no explicit delete.

Relational · PostgreSQL

A cleanup query removes old rows.

cleanup.sqlruns offline
-- cron: every night at 03:00
DELETE FROM rider_pings
WHERE pinged_at <
      now() - interval '7 days';

Cassandra · CQL

Data expires by itself.

ttl.cqlruns offline
CREATE TABLE rider_track (
  rider_id uuid, day date,
  at timestamp,
  lat double, lon double,
  PRIMARY KEY ((rider_id, day), at)
) WITH default_time_to_live = 604800;
-- 7 days, then gone

The shift: from "a job deletes old rows" to "each row carries its own expiry".

A TTL can also be set per write, and you can ask how long a cell has left.

per-write TTLruns offline
INSERT INTO login_codes (phone, code) VALUES ('+447700900123', '481516')
USING TTL 300;                         -- five minutes

SELECT code, TTL(code) FROM login_codes WHERE phone = '+447700900123';
-- illustrative output: 481516 | 212   (seconds left)
  1. Decide the retention: "keep rider pings 7 days".
  2. Set it on the table: default_time_to_live, so no writer can forget it.
  3. Pair it with the compaction that matches: for time-series data, TimeWindowCompactionStrategy drops whole expired files at once (section 08).
  4. Remember expiry is a tombstone: an expired cell becomes a tombstone when it expires, and it is purged after the grace period.

The trap: a TTL on part of a row. If you update one column with USING TTL and leave the others, they live on while that column vanishes, and the row looks half empty. Set TTL for the whole row on insert, or use the table default.

half-expired rowruns offline
UPDATE orders SET status = 'ready' USING TTL 60 WHERE id = 42;
-- ❌ TRAP: after 60 seconds status reads null; the other columns of order 42 are still there

Relational → Cassandra: UPDATE x = x + 1 becomes a counter column

The relational habit: UPDATE posts SET likes = likes + 1. Under a row lock it is exact, and it is safe inside a transaction.

The Cassandra replacement: a counter column in its own table. You add or subtract; you never set a value. A normal int column cannot be incremented safely, because that would be a read, add, write with last-write-wins in between.

Relational · PostgreSQL

Increment under a row lock.

likes.sqlruns offline
UPDATE posts
SET likes = likes + 1
WHERE id = 7;

SELECT likes FROM posts
WHERE id = 7;

Cassandra · CQL

A counter table; only + and - are allowed.

likes.cqlruns offline
CREATE TABLE post_likes (
  post_id uuid PRIMARY KEY,
  likes   counter
);
UPDATE post_likes SET likes = likes + 1
WHERE post_id = ?;
SELECT likes FROM post_likes
WHERE post_id = ?;

The shift: from "read the number, add one" to "send the delta and let the database merge it".

Rules for counters. A counter table holds only the key and counter columns. You cannot set a counter or give it a TTL. Counters are not idempotent: if a write times out and you retry, the increment may be applied twice, so treat the value as approximate.

what counters refuseruns offline
UPDATE post_likes SET likes = 100 WHERE post_id = ?;
-- ❌ InvalidRequest: counters can only be incremented or decremented, never set
INSERT INTO post_likes (post_id, likes) VALUES (?, 1);
-- ❌ InvalidRequest: INSERT is not supported on counter tables
  1. Ask "does an off-by-one matter?": likes, views and unread badges are fine. Balances and stock are not.
  2. Use a separate table: keep counters apart from other columns.
  3. For exact numbers: insert one event row per action and total them later in a batch job, or keep the count in PostgreSQL.

The trap: using a counter for inventory or payments. After a timeout and a retry, the counter may be off by one, and nothing tells you.

08 · Running itRunning It and Choosing It — Replication, Repair, Compaction, Code, Migration, and When Not to Use Cassandra

Modelling is half the job. The other half is running a cluster: how many copies, where they live, how nodes are added, how copies are kept equal, and how files on disk are tidied. This section also shows driver and Spring code beside JPA, how schema changes work when the key is the design, how to migrate, and how to choose between Cassandra and its neighbours.

Here is a QuickBite story. Black Friday is two weeks away. The PostgreSQL primary that stores rider locations sits at 82% CPU and 91% disk. The relational habit is to buy a bigger machine, add a read replica, or split the table by hand.

The team moved the rider-location data to a three-node Cassandra cluster in the spring. The same night, load doubles. Nobody buys a bigger machine. They start three new nodes, wait while the cluster streams data to them, and run a cleanup on the old nodes. The application is not changed or restarted.

That is what Cassandra's design trades for. You gave up joins and transactions, and in return the cluster grows by adding machines of the same size, and a failed machine is not an emergency.

Make the invisible visible: a cluster before and after adding nodes. Each node owns slices of the token ring, so new nodes take slices from the old ones.

nodetool status, before and afterruns offline
# illustrative output
BEFORE                                          AFTER (3 nodes added)
UN  10.0.1.11  412 GiB  33.3%  rack1            UN  10.0.1.11  206 GiB  16.7%  rack1
UN  10.0.1.12  405 GiB  33.3%  rack1            UN  10.0.1.12  203 GiB  16.7%  rack1
UN  10.0.1.13  418 GiB  33.4%  rack1            UN  10.0.1.13  209 GiB  16.7%  rack1
                                                UN  10.0.1.14  205 GiB  16.7%  rack1   ✓ new
                                                UN  10.0.1.15  207 GiB  16.7%  rack1   ✓ new
                                                UN  10.0.1.16  203 GiB  16.6%  rack1   ✓ new
# UN = Up, Normal. "Owns" is the share of the token ring each node holds.

Relational → Cassandra: scale up and copy becomes scale out with replication

The relational habit: one primary takes all the writes. When it is full, you move to a bigger server (scale up), add read replicas for reads, and, as a last resort, shard by hand in the application or with a tool such as Citus.

The Cassandra replacement: every node accepts reads and writes. The partition key's hash (the token) decides which nodes own a row. You add more nodes of the same size (scale out), and a setting called the replication factor (RF) says how many nodes keep a copy of each row.

Relational · PostgreSQL

One writer; add a replica for reads.

scale_up.sqlruns offline
-- write path: still one primary
-- 1. bigger VM (restart, minutes)
-- 2. read replica:
--    pg_basebackup -h primary ...
-- 3. app routes reads to replica
-- 4. later: shard by hand, or Citus

Cassandra · CQL

Pick RF per keyspace; add nodes.

scale_out.cqlruns offline
CREATE KEYSPACE quickbite
WITH replication = {
  'class': 'NetworkTopologyStrategy',
  'dc_eu': 3
};
-- scale: start more nodes, no app change
-- then: nodetool cleanup (old nodes)

The shift: from "one machine that grows" to "many equal machines, each owning a slice, with copies".

The rules for running it. NetworkTopologyStrategy (NTS) is the replication strategy to use in production, even with one datacentre: it knows about datacentres and racks, and spreads copies across racks so one rack failing loses at most one copy. SimpleStrategy ignores topology and is for tests only.

NetworkTopologyStrategy: dc_eu 3, dc_us 3 dc_eu (RF 3) node 1 node 2 node 3 3 copies of every partition app LOCAL_QUORUM dc_us (RF 3) node 4 node 5 node 6 3 copies of every partition app LOCAL_QUORUM async async
Fig. 18.16 — Each datacentre has its own full set of copies. Local quorum keeps reads and writes inside the local datacentre.

To add a second datacentre, change the keyspace, start the new nodes, and tell them to copy from the old datacentre. The application keeps using its local datacentre's nodes through LOCAL_QUORUM.

add dc_us to a live keyspaceruns offline
cqlsh> ALTER KEYSPACE quickbite WITH replication =
         {'class': 'NetworkTopologyStrategy', 'dc_eu': 3, 'dc_us': 3};

# on each new dc_us node, once started: copy existing data from dc_eu
nodetool rebuild -- dc_eu

# on each old node after adding nodes anywhere in the ring: drop data it no longer owns
nodetool cleanup quickbite
  1. Choose RF 3 per datacentre: it allows one node down at quorum with no loss of service.
  2. Spread across racks or zones: three copies in one rack die together.
  3. Add nodes one at a time (or a few): each streams its share. Watch nodetool status until all are UN.
  4. Size for headroom: keep disk well under about half full where the compaction strategy needs room to work (check the current docs for your strategy).

The trap: thinking of a replica as a backup you can ignore. Copies drift apart whenever a node misses writes (it was down, or a write timed out). Without repair, a delete's tombstone can be lost and zombie rows return (section 06).

symptom of a cluster that is never repairedruns offline
# illustrative output
nodetool repair_admin list          # last successful repair of this node: 34 days ago   ✗ window is 10 days
# deleted orders reappear in the customer's list after node 3 comes back

Repair and compaction: the two housekeeping jobs

Repair compares the copies of the data on the replicas and copies missing pieces across. It is how replicas that missed a write, or a tombstone, catch up. Run it on every node at least once within gc_grace_seconds (10 days by default); many teams schedule it weekly, using a tool such as Cassandra Reaper or the built-in scheduling in recent versions (check the current docs).

Compaction is how Cassandra tidies disk. Writes land in a memtable, and when it fills it is flushed as an immutable file called an SSTable. Files are never edited, so over time one row may be spread across many SSTables. Compaction merges them, throws away overwritten values and expired tombstones, and keeps reads fast. You choose a strategy per table.

Compaction strategies, and which table shape each fits
OptionPick it whenCost or catch
STCS size-tiered (the long-time default)Write-heavy tables with no strong read-latency target.Needs a lot of free disk during big merges; a row can sit in many files.
LCS leveledRead-heavy tables with frequent updates; wants few files per read.More disk I/O from rewriting; heavy on write-heavy loads.
TWCS time-windowTime series written once and expired by TTL (sensor and ping data).Bad if rows are updated or deleted later, or written out of time order.
UCS unified (new in 5.0)One strategy that can behave like the others through its settings; a good thing to try on new tables.Newer, so read the current docs and test before relying on it.
choose a strategy per tableruns offline
-- time series with TTL: one-day windows
ALTER TABLE quickbite.rider_track WITH compaction = {
  'class': 'TimeWindowCompactionStrategy',
  'compaction_window_unit': 'DAYS',
  'compaction_window_size': 1
};

-- 5.0: unified strategy, defaults
ALTER TABLE quickbite.orders_by_customer WITH compaction = {'class': 'UnifiedCompactionStrategy'};

A first set of nodetool commands

nodetool is the command-line tool that talks to one running node. These six cover most first checks.

nodetool basicsruns offline
nodetool status                              # is every node UN (Up, Normal)? how big, how much of the ring?
nodetool tablestats quickbite.orders_by_customer   # sizes, SSTable count, read/write latency, tombstones per read
nodetool tablehistograms quickbite orders_by_customer   # partition size and latency percentiles
nodetool compactionstats                     # merges running now, and how many are waiting
nodetool repair -pr quickbite                # repair the ranges this node is primary for; run on every node
nodetool describecluster                     # schema agreement: all nodes should show one schema version

What you see: the healthy and unhealthy reading of two of them.

reading the outputruns offline
# illustrative output
nodetool status          UN 10.0.1.11 ... | DN 10.0.1.12 ...      ✗ DN = Down; hints pile up on others
tablestats               SSTable count: 412    ✗ compaction is behind (reads touch many files)
                         Average tombstones per slice (last five minutes): 8,200   ✗ delete-heavy pattern
tablehistograms 99th     Partition Size: 214 MB   ✗ over the ~100 MB guideline

Application code both ways: JPA repository vs Cassandra repository

The code that talks to the database changes shape too. A JPA entity describes objects and their links, and the framework writes the joins. A Spring Data Cassandra class describes one table and its key, and a repository method is one query on that key.

Relational · PostgreSQL

Entities link to each other; JPA joins.

Order.java (JPA)runs offline
@Entity
class Order {
  @Id UUID id;
  @ManyToOne Customer customer;
  @OneToMany List<Item> items;
}
interface OrderRepo
  extends JpaRepository<Order, UUID> {
  List<Order> findByCustomerId(UUID id);
}

Cassandra · CQL

One class per table; the key is explicit.

OrderByCustomer.javaruns offline
@Table("orders_by_customer")
class OrderByCustomer {
  @PrimaryKey OrderKey key;
  String restaurantName;
  int totalCents;
}
interface OrderRepo extends
  CassandraRepository<
    OrderByCustomer, OrderKey> {
  Slice<OrderByCustomer>
    findByKeyCustomerId(UUID id, Pageable p);
}

The shift: from "an object graph the framework joins" to "a flat row per table, loaded by its partition key".

The key class is where the primary key from the CQL lives. The partition key and the clustering column are both spelled out.

OrderKey.java (Spring Data Cassandra)runs offline
@PrimaryKeyClass
public class OrderKey implements Serializable {

    @PrimaryKeyColumn(name = "customer_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
    private UUID customerId;                                   // partition key: "for one customer"

    @PrimaryKeyColumn(name = "placed_at", ordinal = 1, type = PrimaryKeyType.CLUSTERED,
                      ordering = Ordering.DESCENDING)
    private Instant placedAt;                                  // clustering column: newest first

    @PrimaryKeyColumn(name = "order_id", ordinal = 2, type = PrimaryKeyType.CLUSTERED)
    private UUID orderId;                                      // tie-breaker for equal times

    // constructor, getters, equals and hashCode omitted
}

Using it. The repository returns a Slice, which holds one page and a pointer to the next, and fits the paging-state idea from the pagination map.

MyOrdersService.javaruns offline
Slice<OrderByCustomer> page1 =
    repo.findByKeyCustomerId(customerId, CassandraPageRequest.first(20));

Slice<OrderByCustomer> page2 = page1.hasNext()
    ? repo.findByKeyCustomerId(customerId, page1.nextPageable())   // ✅ continues from the bookmark
    : Slice.empty();
application.ymlruns offline
spring:
  cassandra:
    contact-points: 127.0.0.1:9042       # a few nodes; the driver discovers the rest
    local-datacenter: dc_eu              # required: the driver prefers this datacentre
    keyspace-name: quickbite
    schema-action: none                  # ✅ the schema is managed by migrations, not by the app

Dependency names (check the current docs for versions): spring-boot-starter-data-cassandra for Spring Data, or org.apache.cassandra:java-driver-core for the plain Apache Cassandra Java driver 4.x.

When you need control, for instance a batch, use the driver directly. Prepare each statement once, bind values many times, and set the consistency level on the batch.

DeliverOrder.java (driver 4.x, logged batch)runs offline
PreparedStatement byCustomer = session.prepare(
    "UPDATE quickbite.orders_by_customer SET status = ? WHERE customer_id = ? AND placed_at = ? AND order_id = ?");
PreparedStatement byRestaurant = session.prepare(
    "UPDATE quickbite.orders_by_restaurant_day SET status = ? "
  + "WHERE restaurant_id = ? AND day = ? AND placed_at = ? AND order_id = ?");

BatchStatement batch = BatchStatement.newInstance(DefaultBatchType.LOGGED)
    .add(byCustomer.bind("delivered", customerId, placedAt, orderId))
    .add(byRestaurant.bind("delivered", restaurantId, day, placedAt, orderId))
    .setConsistencyLevel(DefaultConsistencyLevel.LOCAL_QUORUM);

session.execute(batch);   // idempotent (sets a value), so a retry of the whole batch is safe

The trap: letting the framework create tables for you in production (schema-action: create), or putting ALLOW FILTERING in a repository method to make a query compile. Both hide the design question you were meant to answer.

Relational → Cassandra: ALTER and migrate becomes add a column, or new table plus backfill

The relational habit: the schema follows the data. A new question means a new index or a new JOIN, and a changed column means ALTER TABLE or a migration script (Flyway, Liquibase).

The Cassandra replacement: adding a column is cheap and safe. But the primary key cannot be changed, and the key is the answer to a question. A new question means a new table. You create it, write to both tables, copy the old rows across (backfill), move reads, and drop the old table.

Relational · PostgreSQL

One migration answers the new question.

V12__late.sqlruns offline
-- Flyway migration V12
CREATE INDEX orders_status_placed_idx
  ON orders (status, placed_at);

ALTER TABLE orders
  ADD COLUMN coupon_code text;

Cassandra · CQL

Add a column freely; new question, new table.

v12.cqlruns offline
-- ✅ cheap: adds an empty column
ALTER TABLE orders_by_customer
  ADD coupon_code text;

-- new question = new table
CREATE TABLE late_orders_by_city (
  city text, placed_at timestamp,
  order_id uuid,
  PRIMARY KEY ((city), placed_at, order_id));

The shift: from "change the schema in place" to "add tables beside the old ones and move over".

A new question: relational vs Cassandra Relational CREATE INDEX or new JOIN planner answers it today Cassandra 1 create new table 2 dual-write old + new 3 backfill old rows 4 switch reads to new table 5 drop old table Steps 2 and 3 overlap: new writes go to both tables while history is copied. Keep the old table until the new one is checked.
Fig. 18.17 — The same new question costs one statement in PostgreSQL and a small migration in Cassandra, because the key decides the table.

Things that cannot be changed with ALTER: the partition key, the clustering columns and their order. Changing a column type is limited to a few compatible cases (check the current docs). Dropping a column is allowed, but its data is not reclaimed at once.

what ALTER refusesruns offline
ALTER TABLE orders_by_customer DROP PRIMARY KEY;       -- ❌ no such statement
ALTER TABLE orders_by_customer ALTER placed_at TYPE text;
-- ❌ InvalidRequest: cannot change the type of a clustering column
-- the only route: new table with the new key + backfill + switch
  1. Create the new table: with the key that fits the new question. Keep the migration script in version control (a migration tool or plain numbered .cql files).
  2. Dual-write: deploy code that writes both tables in one logged batch. From now on new data is in both.
  3. Backfill history: copy old rows with a job (Spark, or an application loop reading with paging state). Writes are upserts, so a job that is stopped and restarted is safe.
  4. Compare, switch, drop: read a sample from both and compare, move reads to the new table, then stop writing the old table and drop it later.

The trap: a schema change run while nodes disagree, or two people changing the schema at once. Schemas must agree on every node before the next change.

check schema agreement before the next changeruns offline
nodetool describecluster
# illustrative output
Schema versions:
    3f1c...: [10.0.1.11, 10.0.1.12]
    9a7e...: [10.0.1.13]            ✗ node 13 is behind; wait or fix before ALTER again

Migrating a relational system without a big-bang rewrite

The earlier incident (a one-to-one port of the schema) shows what not to do. A safer path moves one screen at a time and keeps PostgreSQL as the system of record until the new tables are proven.

Relational habit

Move the tables, then fix the queries.

relational_port.txtruns offline
1. export every table
2. create same tables in new DB
3. import all rows
4. point app at new DB
5. fix queries that fail
   (JOINs, indexes, UNIQUE...)

Cassandra habit

Move one query at a time, tables follow queries.

query_first_port.txtruns offline
1. list the queries (Q1..Qn)
2. design one table per query
3. change events -> Kafka -> tables
4. backfill, compare, switch
5. next screen
(PostgreSQL stays the truth)

The shift: from "move the schema" to "move the questions, one at a time".

  1. List the real queries: from application code and from pg_stat_statements in PostgreSQL. Cross out the ones that need joins across many tables or exact multi-row transactions; those stay behind.
  2. Pick the first candidate: a high-volume, write-heavy, single-key-lookup workload (rider locations, order timeline, activity feed), not the checkout.
  3. Feed it from changes: publish events from PostgreSQL with the outbox pattern, and have a consumer write the Cassandra tables (Chapter E17). This also gives you replay for the backfill.
  4. Backfill and compare: load history, then read a sample from both stores for a week and diff them.
  5. Switch reads, keep the way back: feature-flag the read path per screen. PostgreSQL still holds the truth, so you can switch back.
  6. Retire only what moved: drop the PostgreSQL table when nothing reads it. The relational foundations, including indexes and transactions, are in Chapter E8.

The trap: moving everything because "Cassandra scales". Orders with payments, stock levels, and anything needing a multi-row exact transaction fit PostgreSQL better. Use both: polyglot persistence (section 07 returns to this).

The stack table: Cassandra and its neighbours

Cassandra is one choice among several. The real question is which access pattern you have. This table gives the alternatives, why you would pick each, and when to switch away from Cassandra. It uses no benchmark numbers; test with your own workload.

Choosing a store for QuickBite-style data. Switch when the "Cost or catch" starts to hurt.
OptionPick it whenCost or catch
Apache Cassandra 5.0Huge write volume, access by key, time-ordered data, many datacentres, no single point of failure, a team that can run a cluster.No joins or multi-table transactions; you design a table per query; repair and compaction are your job. Switch away when queries are ad hoc or consistency must be exact.
ScyllaDBYou want the Cassandra data model and CQL, with an engine written in C++ and fewer, larger nodes.A separate project, so licence, features and tooling differ from Apache Cassandra; check the current docs. Same modelling rules.
Amazon KeyspacesYou want CQL-compatible access with no cluster to run, on AWS.It is compatible, not identical: some CQL features differ, and cost follows usage. Check which features you rely on.
DynamoDBYou are on AWS and want serverless key-value access. It uses the same query-first modelling idea (single-table design).Different API and limits, tied to AWS. Moving off later means rewriting the data access.
PostgreSQL (+ Citus)You need joins, ad hoc questions, exact transactions, constraints. Citus spreads tables across nodes when one server is not enough.Writes on one primary hit a ceiling; sharding with Citus brings its own design choices (distribution key). Cross-shard joins cost more.
MongoDBDocuments with varying shape, flexible queries on many fields, secondary indexes as the norm.Different consistency and sharding model; evaluate against your write rate and operations skills.
Bigtable / HBaseWide-column data in a Google Cloud or Hadoop setting, with sorted row keys and scans over key ranges.Different model from CQL's tables; tied to its ecosystem.

A practical rule for senior interviews: say what the access patterns are before naming a database. If the answer is "look up by id, append events, read the latest N, at very high volume", Cassandra fits. If the answer is "any filter, any join, exact money", it does not.

What you see now: the one-line test to run before choosing, as a short checklist.

five questions before choosing Cassandraruns offline
1. Can I list every query now?                      yes -> ✓    "we will add reports later" -> ✗
2. Does each query have one natural partition key?  yes -> ✓    "filter on any column"      -> ✗
3. Is the write rate more than one primary can take, or must it span regions?   yes -> ✓
4. Can a read be a little stale, and can I live without multi-row transactions?  yes -> ✓
5. Can the team run repair, compaction, upgrades? (or can I buy it managed)      yes -> ✓

07 · Real-time case studiesFive Real-Time Systems, Each Modelled Both Ways

This section takes five products that real teams build on Cassandra: chat, QuickBite orders, IoT sensor readings, a social feed, and leaderboards with counters. For each one you see the relational design, the access-pattern list, the Cassandra tables, the exact CQL, the partition-size arithmetic, and what breaks when you keep the relational habit. The last case is the honest one: where Cassandra is the wrong tool.

Start with a Monday-morning request. The QuickBite product manager writes: "Chat between customers and riders goes live in six weeks. Plan for 10 million people opening the app every day, about 8 messages each. Open a chat and the last 50 messages must appear in under 50 ms."

That is 80 million messages a day, about 926 per second on average and roughly 9,000 per second at the lunch peak. Every message is shown to at least two people, so reads are several times higher.

A relational designer starts by drawing the entities. A Cassandra designer starts by listing what each screen asks. Both reach a working system, but the two lists look nothing alike, and the second list decides the tables.

The earlier sections gave you the single moves one at a time: design order, the WHERE-clause rules, bucketing, the Chebotko diagram. Here you put them together five times on whole products.

How every case is laid out

Each case follows the same six steps, so you can compare them line by line. Every step shows the relational version on the left and the Cassandra version on the right.

  1. Requirement: the product ask in plain words, with real numbers, and the question each side asks first.
  2. Schema: the PostgreSQL tables on one side, the Cassandra tables (one per question) on the other.
  3. Writes: the SQL transaction versus the CQL, including how denormalised copies are kept in step.
  4. Reads: the SQL query with its joins versus one partition read in CQL.
  5. Partition-size math: how big the table and index get on one machine versus how big one partition gets.
  6. What breaks: what the relational design does under load, and what happens if you port it to Cassandra one-to-one.

Two extra steps appear in every case. Step 1b follows one real request through both databases, so you see which pages, partitions and replicas are touched and what grows as data grows. Step 7 hands the team a new product requirement three months later, because the real test of a model is how it survives a question nobody planned for.

Watch the pattern in Step 7. The relational team nearly always answers with one DDL statement, such as an index or a column. The Cassandra team answers with one of four moves: use an index inside a known partition, add a derived table with a dual write and a backfill, filter at read time, or move the question to a stream. Knowing which move fits is the senior skill.

The five cases and the map entries they use
CaseCore questionPartition ideaMap entries
a. Chatlast 50 messages, inbox, unread(conversation, week)bucketing, order by, aggregate
b. QuickBite ordersorders by customer, live orders per restaurant, timelineone table per screen, static columnsone-to-many, transaction, join
c. IoT time seriesrecent readings, latest value, expiry(sensor, day), TTL, TWCSTTL, delete, bucketing
d. Social feedhome feed, profile, followersper-follower inbox, sharded followersmany-to-many, join, pagination
e. Leaderboard and limitstop riders, counters, where not to use itcounter table, snapshot tablecounter, consistency, unique

Case a · Chat: messages, inbox, unread counts

Step 1 · The requirement and what each side asks first

QuickBite chat has four screens. Opening a chat shows the newest 50 messages and loads older ones as you scroll up. The inbox lists every chat you are in, newest activity first, each with a one-line preview and an unread badge such as "3" or "99+". Tapping a chat marks it read.

Sizes for planning: 10 million daily users, 8 messages each, chats of 2 people (about 95% of chats) up to rider-support groups with 500 people. The busiest group gets 5,000 messages a day. These numbers are illustrative, but they are the right order of magnitude.

Relational · PostgreSQL

The designer lists things and relationships first. Questions come later, and the planner will answer any of them.

entities.txtruns offline
users
conversations
members  (user <-> conversation)
messages

-- later: any question, answered
-- by joins and an index

Cassandra · CQL

The designer lists the screens first. Each line below will become its own table.

questions.txtruns offline
Q1 last 50 messages of a chat
Q2 inbox of a user + preview
Q3 unread count per chat
Q4 mark a chat as read
Q5 who is in this chat

The shift: the relational list names nouns; the Cassandra list names screens, because screens are what tables are built for.

Access patterns for chat (the Cassandra design input)
QueryAsks forNeedsRate (illustrative)
Q1last 50 messages of one chat, then older pagesone chat, newest first~30,000 per second at peak
Q2all chats of one user with previewone user, all chats~5,000 per second
Q3unread count per chat, capped at 99+messages after a markerwith Q2, up to 50 per inbox open
Q4set the read markerone user, one chat~3,000 per second
Q5members of a chat (to deliver a message)one chat, all usersone per message sent
Chat: four joined tables versus one table per screen Relational: join at read time users conversations members messages Inbox = 3 joins + subqueries every screen shares every table Cassandra: one table per screen Q1 last 50 Q2 inbox Q5 members messages_by_conversationPK ((conv, week), msg_id) inbox_by_userPK ((user_id), conversation_id) members_by_conversationPK ((conv_id), user_id) each read = one partition
Fig. 18.18 — Chat both ways. Left: four normalised tables that every screen joins. Right: three tables, each built for one screen. Q3 and Q4 live inside inbox_by_user (see step 2).

Step 1b · Trace one real request, both ways

Designs look equal on paper. A trace shows the difference. Follow one action: Asha opens conversation c-91, a rider-support group of 40 people with 1,200 messages a day, and scrolls up until she is three pages back (150 messages down from the newest).

The app asks for the page that ends just before the oldest message she has already seen. Both databases get the same question: "the next 50 messages older than 09:12 yesterday, newest first".

Relational · PostgreSQL

The planner walks the composite index, then visits the heap for each hit.

plan.txtruns offline
# illustrative EXPLAIN (ANALYZE, BUFFERS)
Limit  (rows=50)
 -> Index Scan Backward
    using messages_conv_sent_idx
    Index Cond: conv_id = 91
            AND sent_at < '...09:12'
    Buffers: shared hit=6 read=46
 Execution Time: 38 ms (cold chat)

Cassandra · CQL

The coordinator finds the partition, and a replica reads 50 rows in a row.

trace.txtruns offline
# illustrative cqlsh TRACING ON
Preparing statement
Executing single-partition query on
  messages_by_conversation
Acquiring sstable references
Bloom filter: 2 of 5 sstables may match
Merged memtable + 2 sstables
Read 50 live rows, 0 tombstones
Request complete: 2.1 ms (replica)

The shift: relational touches one index leaf and then up to 50 scattered heap pages; Cassandra touches one partition whose rows are already stored together.

Now the same trace in words, one line at a time. First the relational path:

  1. Parse and plan: PostgreSQL sees conv_id = 91 and sent_at < ..., finds the index on (conv_id, sent_at DESC), and decides to read it backwards. The sort is free because the index is already in order.
  2. Walk the index: it descends the B-tree from the root to the leaf that holds conversation 91 near 09:12. With 7 billion rows the tree is about 5 levels deep, so that is 5 page reads, the top ones always in cache.
  3. Visit the heap: each index entry points at a row in the table file. Messages were stored in the order they were sent, across all chats, so the 50 messages of chat 91 sit on up to 50 different 8 KB pages. An old chat is not in memory, so most of these are disk reads.
  4. Return: 50 rows go back to the app. Page 2 repeats the same walk with a smaller sent_at bound.

Now the Cassandra path, with a three-replica keyspace and the read at LOCAL_QUORUM (two of three local replicas must answer):

  1. Hash the key: the driver hashes the partition key (c-91, 202647) with Murmur3 to a token, looks up which three nodes own that token, and sends the request to one of them. That node becomes the coordinator. No central lookup is involved.
  2. Ask two replicas: the coordinator asks the fastest replica for the rows and a second replica for a short fingerprint (a digest) of the same rows. If the two agree, the read is consistent; if not, Cassandra repairs the stale copy (consistency).
  3. Read inside the replica: the replica checks a small in-memory filter (a Bloom filter) for each data file, finds the partition's start through its index, and merges what it finds in the memtable and the matching files.
  4. Stream the rows: because the clustering order is newest first, the 50 rows are the first 50 in the partition. They are stored next to each other, so this is one sequential read.
  5. Page: the reply carries a paging state. The next scroll sends it back and the replica resumes at that exact row; there is no OFFSET to recount.
What grows with data size, per request
What growsRelationalCassandra
Table gets 10x biggerindex depth may add one level; cold heap pages more oftennothing for this request; more nodes share the data
Chat gets 10x more messagesindex range is longer, same 50 rows readthe weekly bucket keeps the partition bounded; add a smaller bucket if needed
Old chat that nobody openedevery heap page is a disk readthe partition is already one contiguous run in a few files
Concurrent readerscontend for the same primary's cache and CPUspread over the three replicas of each partition

Say it plainly in an interview: the relational read cost is shaped by where rows landed on disk, while the Cassandra read cost is shaped by the key you chose. Asha's scroll is cheap in Cassandra because "messages of one chat, newest first" was decided at design time and is now a physical fact on disk, not something the planner has to rediscover.

Step 2 · The schema

The relational side keeps one fact in one place: a message exists once, in messages. The index on (conv_id, sent_at DESC) is added so that Q1 does not scan the whole table.

The Cassandra side puts the messages of one chat in one partition per week. The week number is the bucket: without it, a group chat would grow one partition forever.

Relational · PostgreSQL

Normalised tables with foreign keys.

chat.sqlruns offline
CREATE TABLE messages (
  id        bigserial PRIMARY KEY,
  conv_id   bigint REFERENCES conversations,
  sender_id bigint REFERENCES users,
  body      text NOT NULL,
  sent_at   timestamptz DEFAULT now()
);
CREATE INDEX ON messages (conv_id, sent_at DESC);
CREATE TABLE members (
  conv_id bigint REFERENCES conversations,
  user_id bigint REFERENCES users,
  last_read_at timestamptz,
  PRIMARY KEY (conv_id, user_id)
);

Cassandra · CQL

One table per question. Partition key picks the machine, clustering key sorts the rows.

chat.cqlruns offline
CREATE TABLE messages_by_conversation (
  conversation_id uuid,
  week_id    int,     -- 202647 = ISO week
  message_id timeuuid,
  sender_id  uuid,
  body       text,
  PRIMARY KEY ((conversation_id, week_id),
                message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);

The shift: relational keeps one copy and indexes it; Cassandra stores the sort order in the table itself, so no index is needed to read newest-first.

Two more Cassandra tables serve the inbox and the member list. The inbox keeps the preview and the read marker in the same row, so Q2, Q3 and Q4 all touch one partition per user.

chat.cql (continued)runs offline
CREATE TABLE inbox_by_user (
  user_id          uuid,
  conversation_id  uuid,
  last_message_id  timeuuid,
  last_sender_id   uuid,
  last_preview     text,      -- first 80 characters
  last_at          timestamp,
  last_read_id     timeuuid,  -- the read marker
  PRIMARY KEY ((user_id), conversation_id)
);

CREATE TABLE members_by_conversation (
  conversation_id uuid,
  user_id         uuid,
  joined_at       timestamp,
  PRIMARY KEY ((conversation_id), user_id)
);

Notice what the inbox does not do: it does not sort by last_at. A clustering column cannot change once a row is written, so sorting by "latest activity" would mean deleting and re-inserting a row on every message and leaving a tombstone each time. The inbox has at most a few hundred rows per user, so the app reads them all and sorts them in memory.

The trap: putting last_at in the clustering key because "the inbox must be sorted". Every new message becomes a delete plus an insert in every member's partition, and tombstones pile up in exactly the partitions you read most.

Step 3 · The writes

Sending one message is one transaction in PostgreSQL. In Cassandra it is one write to the message table plus one inbox update per member. For a two-person chat that is three rows in three partitions.

Relational · PostgreSQL

One transaction updates both tables.

send.sqlruns offline
BEGIN;
INSERT INTO messages (conv_id, sender_id, body)
VALUES (77, 5, 'on my way');
UPDATE conversations SET last_msg_at = now()
 WHERE id = 77;
COMMIT;

Cassandra · CQL

Write the message, then its copies. Binding values come from the app.

send.cqlruns offline
INSERT INTO messages_by_conversation
  (conversation_id, week_id, message_id,
   sender_id, body)
VALUES (?, ?, ?, ?, ?);

The shift: relational protects consistency with one transaction; Cassandra gives up the single transaction and rebuilds consistency with a batch or a worker.

The inbox copies must follow. For a two-person chat use a logged batch: it guarantees all three rows are eventually applied even if the coordinator dies halfway. USING TIMESTAMP is the message time in microseconds, so if two messages arrive out of order the newer one still wins (last write wins).

send-batch.cqlruns offline
BEGIN BATCH
  INSERT INTO messages_by_conversation
    (conversation_id, week_id, message_id, sender_id, body)
  VALUES (:conv, :week, :mid, :me, :text);

  UPDATE inbox_by_user USING TIMESTAMP :ts
    SET last_message_id = :mid, last_sender_id = :me,
        last_preview = :preview, last_at = :sent_at
  WHERE user_id = :me    AND conversation_id = :conv;

  UPDATE inbox_by_user USING TIMESTAMP :ts
    SET last_message_id = :mid, last_sender_id = :me,
        last_preview = :preview, last_at = :sent_at
  WHERE user_id = :other AND conversation_id = :conv;
APPLY BATCH;

A 500-person group cannot use that batch: 500 updates in one batch would blow past the batch-size warning (5 KiB) and fail threshold (50 KiB). Write the message row first, then publish a "message sent" event to Kafka (Chapter E17) and let workers update the 500 inbox rows in small groups, each in its own partition.

Marking a chat read is a single-partition write, no batch needed:

mark-read.cqlruns offline
UPDATE inbox_by_user SET last_read_id = :latest_seen
WHERE user_id = :me AND conversation_id = :conv;

Step 4 · The reads

Relational · PostgreSQL

Q1 is an index range scan on messages.

q1.sqlruns offline
SELECT * FROM messages
 WHERE conv_id = 77
 ORDER BY sent_at DESC
 LIMIT 50;

Cassandra · CQL

Q1 is one partition, rows already newest first.

q1.cqlruns offline
SELECT message_id, sender_id, body
FROM messages_by_conversation
WHERE conversation_id = ? AND week_id = ?
LIMIT 50;

The shift: relational finds rows through an index and sorts if needed; Cassandra jumps to one partition and reads from the top.

If the current week has fewer than 50 rows, the app reads the previous week's partition for the rest. Paging back to older messages uses the paging state from the driver (pagination), not OFFSET.

The inbox is where the relational query gets heavy. It joins members to the latest message and counts unread rows with a subquery per chat.

inbox.sqlruns offline
SELECT c.id, m.body AS preview, m.sent_at,
       (SELECT count(*) FROM messages x
         WHERE x.conv_id = c.id
           AND x.sent_at > mem.last_read_at) AS unread
FROM members mem
JOIN conversations c ON c.id = mem.conv_id
JOIN LATERAL (SELECT * FROM messages
               WHERE conv_id = c.id
               ORDER BY sent_at DESC LIMIT 1) m ON true
WHERE mem.user_id = 5
ORDER BY m.sent_at DESC;   -- 300 chats = 600 index probes
inbox.cqlruns offline
-- Q2 + Q4 marker: one partition, all chats of the user
SELECT conversation_id, last_preview, last_at,
       last_sender_id, last_read_id
FROM inbox_by_user WHERE user_id = ?;

-- Q3: unread for ONE visible chat, capped at 100 rows
SELECT message_id FROM messages_by_conversation
WHERE conversation_id = ? AND week_id = ?
  AND message_id > ?          -- the last_read_id
LIMIT 100;                    -- show "99+" if 100 return

Unread is not a counter here, on purpose. A counter column cannot be reset to zero, and a retried increment can be applied twice. A capped read of "rows after the marker" is one cheap partition slice, never wrong by more than the cap, and it needs no extra table. The app runs it only for the chats visible on screen, in parallel.

Step 5 · Partition-size and table-size math

Relational · PostgreSQL

The question is how big the table and index get.

size.txtruns offline
80M msgs/day x 90 days = 7.2B rows
row ~ 120 B     -> ~860 GB heap
index ~ 40 B/row -> ~290 GB
write rate: 926/s avg, ~9k/s peak
all of it on one primary

Cassandra · CQL

The question is how big ONE partition gets.

size.txtruns offline
row ~ 200 B (ids 32 + body ~100 + overhead)
busiest group: 5,000/day x 7 = 35,000 rows
35,000 x 200 B     = 7 MB      OK
1:1 chat: 30/day x 7 = 210 rows = 42 KB
1 year, no bucket: 1.8M rows = 365 MB  BAD

The shift: relational asks whether the whole table fits one machine; Cassandra asks whether one partition stays under about 100 MB and 100,000 rows.

Weekly buckets keep the busiest group at 35,000 rows, safely under the guideline. Monthly buckets would give 150,000 rows, over it. The bucket size is chosen from the busiest realistic partition, not the average one.

messages_by_conversation: one partition per chat per week (c-77, 202647) this week m9021 m9020 m9019 m9018 ... older rows ... 35,000 rows newest row first (c-77, 202646) m8100 m8099 m8098 m8097 ... older rows ... 33,600 rows newest row first (c-77, 202645) m7200 m7199 m7198 m7197 ... older rows ... 36,100 rows newest row first LIMIT 50 stops inside this partition Each frame is a separate partition with its own token, so it can live on different machines. Scrolling back = the same query with week_id - 1. A quiet 1:1 chat has 210 rows per frame; a hot group has 35,000. Same code for both.
Fig. 18.19 — Weekly buckets of one chat. The first 50 rows come from the newest partition; an older page repeats the query with the previous week_id.

Step 6 · What breaks

Relational · PostgreSQL

At 80M messages a day one PostgreSQL primary carries every write, and the inbox probes 600 index entries per open.

breaks.txtruns offline
index on (conv_id, sent_at) grows to ~290 GB
inbox open = 300 lateral probes + 300 counts
fix: shard by conv_id (Citus) and cache inbox
-- the fix is real, and it is sharding by
-- the same key Cassandra uses from day one

Cassandra · CQL

The one-to-one port: copy messages and members as they are, then query by sender.

breaks.cqlruns offline
CREATE TABLE messages (
  id timeuuid PRIMARY KEY,
  conv_id uuid, sender_id uuid, body text);
SELECT * FROM messages
 WHERE conv_id = ? ALLOW FILTERING;
-- ❌ TRAP: asks every node about every row

The shift: relational degrades slowly and you can shard later; a one-to-one port to Cassandra fails at the first query that is not by primary key.

what-the-port-printsruns offline
# illustrative output on a 12-node cluster, 4 billion rows
cqlsh> SELECT * FROM messages WHERE conv_id = 77 ALLOW FILTERING;
ReadTimeout: Operation timed out - received only 0 responses.
# the query touches all 12 nodes; each scans its share of 4B rows   ✗

Step 7 · A new requirement arrives

Three months after launch, support asks for a new feature: "search a conversation for messages sent by one person, for example everything a rider wrote in the last month." This is the test of a design. The question did not exist when the tables were designed.

Relational · PostgreSQL

The relational team adds an index and ships the same day.

new.sqlruns offline
CREATE INDEX CONCURRENTLY msgs_sender_idx
  ON messages (conv_id, sender_id, sent_at DESC);

SELECT * FROM messages
WHERE conv_id = 91 AND sender_id = 5
  AND sent_at > now() - interval '30 days'
ORDER BY sent_at DESC;

Cassandra · CQL

The Cassandra team has two honest options. The cheap one is a storage-attached index inside the partition.

new.cqlruns offline
CREATE INDEX msgs_sender_sai
ON messages_by_conversation (sender_id)
USING 'sai';

SELECT message_id, body
FROM messages_by_conversation
WHERE conversation_id = ? AND week_id = ?
  AND sender_id = ?;

The shift: relational adds an access path to existing data with one DDL statement; Cassandra can do that only when the query still names the partition key, and otherwise needs a new table (secondary index).

The SAI query above names the whole partition key, so the index is used only to filter rows inside one partition. That is the safe use. The same index without conversation_id and week_id would consult every node. Check the current 5.0 docs for the exact query rules.

The second option is a new table, because "all messages by one sender, across chats" is a new question with a new key.

messages_by_sender.cqlruns offline
CREATE TABLE messages_by_sender (
  sender_id       uuid,
  month           int,
  message_id      timeuuid,
  conversation_id uuid,
  body            text,
  PRIMARY KEY ((sender_id, month), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);

Adding a table to a live system follows five steps. This is the pattern behind every schema change in Cassandra.

  1. Create the table: it is online and empty; nothing else notices.
  2. Dual write: change the send path so every new message also writes messages_by_sender. Deploy it first, so no new message is missed.
  3. Backfill: a batch job (Spark, or a script that pages through messages_by_conversation) copies old rows. It runs slowly on purpose to leave room for live traffic. The same row written twice is harmless: it is an upsert.
  4. Verify: compare counts for a sample of senders; read both ways for a week.
  5. Switch reads: the new screen reads the new table. Keep the dual write for as long as the screen exists.
Options for the new requirement
OptionPick it whenCost or catch
Add a SAI index, keep the partition key in the querythe search is inside one chat and week, and you want it this weekqueries that skip the partition key query every node; index files use disk and slow writes a little
New table plus dual write plus backfillthe question is across chats, or must be fast at any sizeyou write each message once more, you own a backfill job, and storage grows by one copy
Push to a search engine (OpenSearch/Elasticsearch) fed by Kafkathe need is free-text search, spelling, rankinganother system to run and keep in step; best when users type words, not pick a sender

The trap: answering the new request with ALLOW FILTERING on sender_id because "it works on my laptop". It reads every partition and times out as soon as the table is large.

Case b · QuickBite orders: history, live board, order detail, timeline

Step 1 · The requirement and what each side asks first

This case goes deeper into the QuickBite design from section 04, using its exact tables and its access patterns Q1, Q2, Q4 and Q5. Here you add the numbers, the write paths, and what breaks.

QuickBite takes 2 million orders a day: about 23 per second on average, 250 per second at lunch. There are 20,000 restaurants; the busiest takes 600 orders a day. An order moves through six states: PLACED, ACCEPTED, PREPARING, READY, PICKED_UP, DELIVERED.

Relational · PostgreSQL

Entities first: a customer has many orders, an order has many lines and many status events.

erd.txtruns offline
customers 1--* orders *--1 restaurants
orders 1--* order_items
orders 1--* order_status_events
-- any report later, via joins

Cassandra · CQL

Screens first. The four order screens from section 04, one table each.

questions.txtruns offline
Q1 my orders, newest first, 20/page
Q2 one order: header + every line
Q4 restaurant X today, newest first
Q5 one order's status timeline
+ place an order, change its status
  (= write every copy of Q1,Q2,Q4,Q5)

The shift: relational describes what exists; Cassandra describes what is asked, and every write becomes 'update all the copies'.

Orders: one transaction, or one batch of four copies Relational: one transaction BEGIN ... COMMIT (one order + its status) orders order_items order_events Each table holds a fact once. Screens join the tables. Cassandra: one logged batch BEGIN BATCH ... APPLY BATCH orders_by_customerQ1 orders_by_restaurant_day Q4 orders_by_idQ2 order_events_by_orderQ5 Same order written 4 times, once per screen. Each screen reads one partition. A status change touches the same 4 places.
Fig. 18.20 — An order write both ways. Relational: one row per fact, joined later. Cassandra: one row set per screen, written together.

Step 1b · Trace one real request, both ways

Follow one action: at 19:30, restaurant r-7 opens today's dashboard on its tablet. By then it has taken 380 orders today. The tablet shows each order's time, customer name, total, and status. It refreshes every 5 seconds, so this exact request repeats about 12 times a minute for each of 20,000 restaurants.

Relational · PostgreSQL

Index scan on orders, then one lookup in customers per row.

plan.txtruns offline
# illustrative EXPLAIN (ANALYZE)
Nested Loop  (rows=380)
 -> Index Scan orders_rest_placed_idx
    Cond: restaurant_id = 7
      AND placed_at >= current_date
 -> Index Scan customers_pkey  (x380)
    Cond: customer_id = o.customer_id
 Execution Time: 11 ms (warm)

Cassandra · CQL

One partition, one table, names already inside.

trace.txtruns offline
# illustrative cqlsh TRACING ON
Executing single-partition query on
  orders_by_restaurant_day
Partition (r-7, 2026-11-23)
Merged memtable + 1 sstable
Read 380 live rows, 0 tombstones
Request complete: 1.4 ms (replica)

The shift: relational does 1 range scan plus 380 point lookups every 5 seconds; Cassandra does one read of a partition about 46 KB in size.

The relational trace, step by step:

  1. Pick the access path: (restaurant_id, placed_at) is indexed, so the planner reads today's slice of restaurant 7's entries. 380 entries sit next to each other in the index.
  2. Fetch the rows: the order rows themselves were written through the day. Restaurant 7's orders are interleaved with those of every other restaurant, so 380 heap pages are visited, most of them hot because they are today's.
  3. Join: for each of the 380 orders the customer name is looked up by primary key. That is 380 more index probes; the planner chooses a nested loop because the outer side is small.
  4. Cost at scale: multiply by the polling. 20,000 tablets every 5 seconds is 4,000 of these queries per second, each with 380 joins, on the same primary that also takes the order writes.

The Cassandra trace for the same tablet. Reads here use LOCAL_QUORUM, so a tablet that has just written a status change sees it immediately (write quorum plus read quorum exceeds the replication factor):

  1. Locate: the partition key is (r-7, 2026-11-23). Its token maps to three replicas in the local datacentre; the driver sends the query to one of them as coordinator.
  2. Read quorum: the coordinator asks one replica for data and one for a digest. Both must answer for LOCAL_QUORUM to succeed (consistency).
  3. Read the partition: 380 rows, 120 B each, about 46 KB, newest first in the clustering order, from the memtable and usually one data file.
  4. Return, filter on the tablet: the app hides DELIVERED rows. The database never knew about "open"; it just handed back the day.
What grows with data size, per request
What growsRelationalCassandra
Orders table 10x biggerindex deeper by about one level; heap pages colder for older daysunchanged: the partition is one day of one restaurant
Restaurant gets busierrange and joins grow with its orderspartition grows; at 600 rows it is 72 KB, far below the guideline
More tablets pollingthe primary's CPU is shared with writesload spreads over each restaurant's three replicas
Customer renames themselfone UPDATE, all screens agreeold copies of the name stay until rewritten; accept or backfill

The tablet is the clearest example of the whole chapter. Relational asks one question of many tables and assembles the answer 12 times a minute per restaurant. Cassandra assembled the answer once, when each order changed, and now just hands it over. The price is paid at write time (four copies) and in accuracy rules (names can be stale).

Step 2 · The schema

Relational · PostgreSQL

Orders, lines and events are separate tables, joined by order_id.

orders.sqlruns offline
CREATE TABLE orders (
  order_id      uuid PRIMARY KEY,
  customer_id   uuid REFERENCES customers,
  restaurant_id uuid REFERENCES restaurants,
  status        text NOT NULL,
  placed_at     timestamptz NOT NULL,
  total_cents   int NOT NULL
);
CREATE INDEX ON orders
  (customer_id, placed_at DESC);
CREATE INDEX ON orders
  (restaurant_id, placed_at);
CREATE TABLE order_items (
  order_id uuid REFERENCES orders,
  line_no  int, item_id uuid, qty int,
  unit_price_cents int,
  PRIMARY KEY (order_id, line_no)
);

Cassandra · CQL

The history list: customer is the partition, newest order first.

orders.cqlruns offline
CREATE TABLE orders_by_customer (
  customer_id     uuid,
  placed_at       timestamp,
  order_id        uuid,
  restaurant_name text,
  status          text,
  total_cents     int,
  PRIMARY KEY ((customer_id),
                placed_at, order_id)
) WITH CLUSTERING ORDER BY
    (placed_at DESC, order_id ASC);

The shift: relational splits an order into tables to avoid repeating data; Cassandra repeats on purpose so each screen needs one read.

The other three tables follow. orders_by_restaurant_day puts the date in the partition key (a bucket) because a restaurant's all-time orders would never stop growing. orders_by_id uses static columns: values stored once per partition and shown on every row. That is how the order header (customer, status, total) sits next to its line rows.

orders.cql (continued)runs offline
CREATE TABLE orders_by_restaurant_day (
  restaurant_id uuid, day date,
  placed_at     timestamp, order_id uuid,
  customer_name text, status text, total_cents int,
  PRIMARY KEY ((restaurant_id, day), placed_at, order_id)
) WITH CLUSTERING ORDER BY (placed_at DESC, order_id ASC);

CREATE TABLE orders_by_id (
  order_id      uuid,
  line_no       int,
  customer_id   uuid      STATIC,
  restaurant_id uuid      STATIC,
  status        text      STATIC,
  placed_at     timestamp STATIC,
  total_cents   int       STATIC,
  item_id       uuid,
  item_name     text,
  qty           int,
  unit_price_cents int,
  PRIMARY KEY ((order_id), line_no)
);

CREATE TABLE order_events_by_order (
  order_id uuid, event_id timeuuid,
  status   text, note text,
  PRIMARY KEY ((order_id), event_id)
);

The order lines are the one-to-many child rows: in orders_by_id each line is a clustering row under the order's partition, so reading one order reads header and lines in one go. unit_price_cents is a snapshot of the price at order time, so a later menu price change does not rewrite history.

Step 3 · The writes

Relational · PostgreSQL

One transaction inserts the order, its lines, and the first event.

place.sqlruns offline
BEGIN;
INSERT INTO orders (order_id, customer_id,
  restaurant_id, status, placed_at, total_cents)
VALUES (:oid, :cust, :rest, 'PLACED', now(), 1840);
INSERT INTO order_items VALUES
  (:oid, 1, :item7, 2, 790),
  (:oid, 2, :item9, 1, 260);
INSERT INTO order_status_events
  (order_id, status) VALUES (:oid, 'PLACED');
COMMIT;

Cassandra · CQL

One logged batch writes the same order into four tables, one per screen.

place.cqlruns offline
BEGIN BATCH
  INSERT INTO orders_by_id ...;     -- header
  INSERT INTO orders_by_id ...;     -- line 1
  INSERT INTO orders_by_id ...;     -- line 2
  INSERT INTO orders_by_customer ...;
  INSERT INTO orders_by_restaurant_day ...;
  INSERT INTO order_events_by_order ...;
APPLY BATCH;
-- each ... = full column list, below

The shift: relational makes one order consistent with one transaction; Cassandra makes the copies agree with a logged batch (transaction).

place-order.cqlruns offline
BEGIN BATCH
  INSERT INTO orders_by_id (order_id, line_no, customer_id, restaurant_id,
     status, placed_at, total_cents, item_id, item_name, qty, unit_price_cents)
  VALUES (:oid, 1, :cust, :rest, 'PLACED', :now, 1840, :item7, 'Paneer wrap', 2, 790);
  INSERT INTO orders_by_id (order_id, line_no, item_id, item_name, qty, unit_price_cents)
  VALUES (:oid, 2, :item9, 'Mango lassi', 1, 260);

  INSERT INTO orders_by_customer (customer_id, placed_at, order_id,
     restaurant_name, status, total_cents)
  VALUES (:cust, :now, :oid, 'Spice Lane', 'PLACED', 1840);

  INSERT INTO orders_by_restaurant_day (restaurant_id, day, placed_at, order_id,
     customer_name, status, total_cents)
  VALUES (:rest, :today, :now, :oid, 'Maya', 'PLACED', 1840);

  INSERT INTO order_events_by_order (order_id, event_id, status, note)
  VALUES (:oid, now(), 'PLACED', 'by customer');
APPLY BATCH;

A status change touches the same places. The three tables that hold a status cell get an in-place update (an upsert), and the timeline gets a new event row. The app already knows customer_id, restaurant_id, placed_at and day because the order token it holds carries them; otherwise it first reads them from the static columns of orders_by_id.

Relational · PostgreSQL

Two statements.

status.sqlruns offline
UPDATE orders SET status = 'PREPARING'
 WHERE order_id = :oid;
INSERT INTO order_status_events
  (order_id, status)
VALUES (:oid, 'PREPARING');

Cassandra · CQL

Four statements in one batch, each by full key.

status.cqlruns offline
BEGIN BATCH
  UPDATE orders_by_id
   SET status = 'PREPARING'
   WHERE order_id = ?;
  UPDATE orders_by_customer
   SET status = 'PREPARING'
   WHERE customer_id = ?
     AND placed_at = ? AND order_id = ?;
  UPDATE orders_by_restaurant_day
   SET status = 'PREPARING'
   WHERE restaurant_id = ? AND day = ?
     AND placed_at = ? AND order_id = ?;
  INSERT INTO order_events_by_order
   (order_id, event_id, status)
   VALUES (?, now(), 'PREPARING');
APPLY BATCH;

The shift: relational updates one row; Cassandra updates every copy it made, which is why copies are written from one code path only.

Step 4 · The reads

Relational · PostgreSQL

Q1 and Q4 filter orders and join for names.

reads.sqlruns offline
-- Q1: my orders, page 1
SELECT o.order_id, r.name, o.total_cents, o.status
FROM orders o JOIN restaurants r
  ON r.restaurant_id = o.restaurant_id
WHERE o.customer_id = :cust
ORDER BY o.placed_at DESC LIMIT 20;
-- Q4: restaurant today
SELECT o.*, c.name FROM orders o
JOIN customers c USING (customer_id)
WHERE o.restaurant_id = :rest
  AND o.placed_at >= current_date;

Cassandra · CQL

Each read names one partition. The names are already inside the row.

reads.cqlruns offline
-- Q1: my orders, page 1
SELECT order_id, restaurant_name,
       total_cents, status
FROM orders_by_customer
WHERE customer_id = ? LIMIT 20;
-- Q4: restaurant today
SELECT * FROM orders_by_restaurant_day
WHERE restaurant_id = ? AND day = ?;

The shift: relational joins at read time to get the restaurant name; Cassandra copied the name in at write time (join replacement).

order-detail.cqlruns offline
-- Q2: header + every line, one partition
SELECT customer_id, status, total_cents,
       line_no, item_name, qty, unit_price_cents
FROM orders_by_id WHERE order_id = ?;

-- Q5: the timeline, one partition, oldest first
SELECT event_id, status, note
FROM order_events_by_order WHERE order_id = ?;
order-detail-outputruns offline
# illustrative output of Q2: static columns repeat on each row, stored once
 customer_id | status    | total_cents | line_no | item_name   | qty
-------------+-----------+-------------+---------+-------------+-----
 c-9         | PREPARING |        1840 |       1 | Paneer wrap |   2
 c-9         | PREPARING |        1840 |       2 | Mango lassi |   1

Q4 is "today's orders", not "open orders", because the table is keyed by day, not by status. The restaurant tablet reads the whole day (at most 600 rows, about 70 KB) and hides DELIVERED rows on screen. That is intentional.

The trap: adding status to the key so that "open orders" is a partition read. Every status change then deletes a row and inserts a row elsewhere, so the tablet's partition fills with tombstones and gets slower as the day goes on.

the-trap.cqlruns offline
SELECT * FROM orders_by_restaurant_day
WHERE restaurant_id = ? AND day = ? AND status != 'DELIVERED';
-- ❌ TRAP: InvalidRequest: status is not a key column;
--          ALLOW FILTERING would read all 600 rows anyway
SELECT * FROM orders_by_restaurant_day
WHERE restaurant_id = ? AND day = ?;       -- ✅ read the day, filter in the app

Step 5 · Partition-size math

Relational · PostgreSQL

Size per day and per year, in one table.

size.txtruns offline
orders+items+events ~ 800 B per order
2M orders/day = 1.6 GB/day
x 365 = ~580 GB/year (heap)
indexes extra; one primary writes it all

Cassandra · CQL

Size per partition, four tables.

size.txtruns offline
by_customer row ~120 B; heavy user 360/year
  10 years = 3,600 rows = 430 KB   OK
by_restaurant_day row ~120 B
  busiest day 600 rows = 72 KB     OK
by_id: static ~100 B + 4 lines x 80 B
  = 0.5 KB                         OK
events: 7 x 60 B = 0.4 KB          OK

The shift: relational counts total bytes in one table; Cassandra counts bytes in the largest single partition.

Partition writes per order: 4 when placed (the lines share one partition), plus 4 for each of 5 status changes, so 24 in total. At 2 million orders a day that is about 48 million partition writes a day, roughly 560 per second on average and about 6,000 per second at lunch. Cassandra spreads these over the ring; each partition sees only a trickle.

The four order partitions, row by row orders_by_customer PK ((customer_id), placed_at, order_id) DESC partition: customer c-9 o412 PREPARING o398 DELIVERED o377 DELIVERED o351 DELIVERED newest first, ~3,600 rows in 10 years orders_by_restaurant_day PK ((restaurant_id, day), placed_at, order_id) DESC partition: r-12 | 2026-11-23 o412 PREPARING o411 READY o409 PICKED_UP o408 DELIVERED a day of orders, max ~600 rows, ~72 KB orders_by_id PK ((order_id), line_no) partition: order o-412 STATIC (once): c-9, PREPARINGtotal 1840, placed 12:01 line 1 Paneer wrap x2 line 2 Mango lassi x1 order_events_by_order PK ((order_id), event_id) ASC, partition o-412 PLACED 12:01 ACCEPTED 12:01 PREPARING 12:09 READY 12:21
Fig. 18.21 — The four order tables as partitions. Each screen reads exactly one of these rows-in-a-line.

Step 6 · What breaks

Be honest about orders: a single PostgreSQL node handles 2 million orders a day without trouble. The pressure that pushes teams to Cassandra is not raw size. It is a multi-region, always-writable service where a region can fail, plus reads that must stay local and fast everywhere.

Relational · PostgreSQL

What strains first as the product grows.

breaks.txtruns offline
Q4 on a hot day: 20,000 restaurants poll
  every 5 s = 4,000 reads/s of an index scan
Q2 = join of orders + items + customers
one region holds the primary; far users
  pay 150 ms per read round trip

Cassandra · CQL

The one-to-one port and its error.

breaks.cqlruns offline
CREATE TABLE orders (order_id uuid PRIMARY KEY,
  customer_id uuid, restaurant_id uuid,
  status text, total_cents int);
SELECT * FROM orders
 WHERE customer_id = ?;
-- ❌ TRAP: InvalidRequest: Cannot execute
--    this query as it might involve data
--    filtering ... ALLOW FILTERING

The shift: relational slows gradually and can be tuned with indexes and replicas; a direct port fails at once and the quick fix, a secondary index, queries every node.

Where the money lives matters. The order row of record, its payment, and its refunds belong in PostgreSQL (case e). The four Cassandra tables above are read models, rebuilt from the order events that come through Kafka. If a Cassandra table is lost, you replay the events; if the ledger were lost, you could not.

Step 7 · A new requirement arrives

Product asks: "The kitchen wants to see only orders in PREPARING, and the dispatcher wants only READY ones, for any restaurant, without scrolling through the whole day." A new access pattern, keyed by status.

Relational · PostgreSQL

An index on status makes it one more query.

new.sqlruns offline
CREATE INDEX CONCURRENTLY orders_rest_status
  ON orders (restaurant_id, status, placed_at);

SELECT * FROM orders
WHERE restaurant_id = 7
  AND status = 'READY'
  AND placed_at >= current_date;

Cassandra · CQL

A storage-attached index on status, always with the partition key in the query.

new.cqlruns offline
CREATE INDEX orders_status_sai
ON orders_by_restaurant_day (status)
USING 'sai';

SELECT * FROM orders_by_restaurant_day
WHERE restaurant_id = ? AND day = ?
  AND status = 'READY';

The shift: relational adds a multi-column index; Cassandra can index a column inside the partition because the query already names one partition.

Why this works where the first idea (status in the key) failed: the index is only a filter inside (restaurant_id, day), so a status change is an in-place update and never a delete plus an insert. The partition still has at most 600 rows, so the filter is cheap even without the index.

Now the harder variant: "show every READY order across the whole city so dispatchers can assign riders." The partition key is no longer known, because the answer spans restaurants.

ready_by_city.cqlruns offline
CREATE TABLE ready_orders_by_city (
  city        text,
  placed_at   timestamp,
  order_id    uuid,
  restaurant_id uuid,
  total_cents int,
  PRIMARY KEY ((city), placed_at, order_id)
) WITH default_time_to_live = 3600;   -- a READY row is stale after an hour

This is a queue-like table: rows are inserted when an order becomes READY and deleted when picked up. That is the delete-heavy pattern from deletes, so the design gives every row a TTL and reads only a recent window instead of deleting each row. Even so, a city-wide hot partition needs a time bucket in the key if volume is high.

  1. Decide how live it must be: if dispatch needs second-level accuracy, a stream consumer (Kafka) with its own state is a better home than a Cassandra table.
  2. Create the table, dual write, backfill: the READY transition already goes through your single batch path, so add the new table there. Nothing needs backfilling for a view that only holds the last hour.
  3. Read a window: dispatchers read the last 10 minutes of the city partition and filter in memory.
Options for the new requirement
OptionPick it whenCost or catch
SAI on status, partition key in the queryper-restaurant filtersneeds the partition key; cross-restaurant queries still scatter
Filter in the app after reading the daypartitions are small, as they are here (600 rows)reads the whole day each time; fine at 72 KB, wasteful at 100 MB
New table by city with TTL (dual write)a cross-restaurant live viewone more write per transition; hot partition risk; rows expire, not delete
Consume the Kafka order-events streamsecond-level dispatch decisionsanother service holds the state; easiest to reason about and to replay

For the rule behind this table, see secondary indexes and schema changes.

Case c · IoT sensor time series: buckets, TTL, TWCS, latest value

Step 1 · The requirement and what each side asks first

QuickBite puts a temperature and humidity sensor in every fridge at 20,000 restaurants and central kitchens: 50,000 sensors in total. Each one sends a reading every 10 seconds. Food-safety rules say a fridge above 5 °C for 20 minutes must raise an alert.

That is 8,640 readings per sensor per day, 432 million rows a day, 5,000 writes per second, all day and all night. Raw readings are kept 90 days; hourly summaries are kept 2 years.

Relational · PostgreSQL

Entities first: sites, sensors, and a very long readings table.

erd.txtruns offline
sites 1--* sensors 1--* readings
-- readings = 39 billion rows
-- in 90 days, indexed by (sensor, ts)

Cassandra · CQL

Charts first. Four screens, four tables.

questions.txtruns offline
Q1 chart: last hour of one sensor
Q2 chart: one sensor, one day
Q3 board: latest value of all
   sensors at one site
Q4 chart: hourly min/max/avg,
   last 30 days

The shift: relational stores the facts and lets queries slice them later; Cassandra decides the slices (hour, day, latest, hourly) now and stores one table for each.

Access patterns for sensors
QueryAsks forWindowRate
Q1readings of one sensor, last hour360 rows~200 per second
Q2readings of one sensor on one date8,640 rows~20 per second
Q3latest reading of every sensor at one siteup to 200 rows~300 per second
Q4hourly min, max, average, 30 days720 rows~50 per second
Sensor readings: one partition per sensor per day (s-501, 2026-11-23) today 00:19:50 00:19:40 00:19:30 00:19:20 newest first ... oldest last 120 rows so far (s-501, 2026-11-22) 23:59:50 23:59:40 23:59:30 23:59:20 newest first ... oldest last 8,640 rows, ~430 KB (s-501, 2026-11-21) 23:59:50 23:59:40 23:59:30 23:59:20 newest first ... oldest last 8,640 rows, ~430 KB Q1 at 00:20: last hour = tail of yesterday + head of today = 2 partitions Green cells are the last 60 minutes: 360 rows, read by two partition queries run together. No row of a sensor is ever scanned from a day that is not asked for. Each partition is closed after midnight: it stops growing, so it is easy to cache and compact.
Fig. 18.22 — Day buckets for one sensor. The bucket keeps each partition at about 8,640 rows; a question that crosses midnight reads two partitions.

Step 1b · Trace one real request, both ways

The same bucketing idea appears in Part A's rider_track table, which stores a rider's position per day with a 7-day TTL (see section 04). A fridge sensor is the same shape with a slower clock.

Follow one action: at 14:05 an operations engineer opens the chart for sensor s-501 and asks for the last hour. That is 360 readings, one every 10 seconds.

Relational · PostgreSQL

Partition pruning, then an index scan, then 360 heap visits.

plan.txtruns offline
# illustrative EXPLAIN (ANALYZE, BUFFERS)
Index Scan Backward
 using readings_2026_11_pkey
 Cond: sensor_id = 501
   AND ts >= now() - '1 hour'
 Rows: 360
 Buffers: shared hit=40 read=331
 Execution Time: 54 ms

Cassandra · CQL

One partition, one sequential read of 360 rows.

trace.txtruns offline
# illustrative cqlsh TRACING ON
Executing single-partition query on
  readings_by_sensor_day
Partition (s-501, 2026-11-23)
Merged memtable + 3 sstables (today)
Read 360 live rows, 0 tombstones
Request complete: 1.8 ms (replica)

The shift: relational has an index in sensor order but a heap in time order; Cassandra has the table itself in sensor-and-time order.

The relational path, step by step:

  1. Prune partitions: the ts bound tells PostgreSQL to read only the November partition. That part works well.
  2. Walk the index: (sensor_id, ts) lets it find the 360 entries in order. The index is not the problem.
  3. Fetch the rows: this is the surprise. Rows are stored in arrival order. Every 10 seconds 50,000 sensors write one row each, which is about 450 pages of data. Sensor 501's consecutive readings land on 360 different pages. One chart is 360 random page reads, about 330 of them from disk.
  4. Mitigations: cluster the table by sensor, use a BRIN or time-series extension such as TimescaleDB, or keep a per-sensor table. These work, and they are the relational ways to rebuild the same sensor-then-time layout.

The Cassandra path, with a read at LOCAL_ONE for dashboards. One replica is enough here because a chart tolerates a reading that is seconds late; this is the consistency trade you choose per query:

  1. Hash the key: (s-501, 2026-11-23) maps to three replicas. The driver prefers one in its own rack and datacentre.
  2. Find the files: TWCS keeps today's data in a few small files plus the memtable. A Bloom filter excludes every older file, so only 3 files are consulted.
  3. Read in order: within the partition, rows are sorted by ts descending. The first 360 rows are the last hour. They are contiguous on disk.
  4. Cross midnight: at 00:20 the app issues a second query for yesterday's partition and joins the two result lists. Two partitions, not a scan.
What grows with data size, per request
What growsRelationalCassandra
Sensors 10x moremore interleaving, more random pages per chartunchanged: partitions are per sensor and day
Retention longerbigger indexes and partitions to drop by handmore files; older windows are never touched by a recent read
Faster sampling (1 s)10x more rows to index8,640 rows becomes 86,400; bucket by hour if it grows further
Chart for last 7 daysstill one index scan, many more pages7 partition reads, run together

The heap-page surprise is worth remembering for any time-series talk. A B-tree index on sensor and time gives the right order in the index, but the table rows stay in arrival order. Cassandra and TimescaleDB both win by storing the data itself in sensor-then-time order; the index is not the cure, the layout is.

Step 2 · The schema

Relational · PostgreSQL

One big readings table, split by month so that old data can be dropped as a unit.

readings.sqlruns offline
CREATE TABLE readings (
  sensor_id  bigint NOT NULL,
  ts         timestamptz NOT NULL,
  temp_c     real,
  humidity   real,
  battery_mv int,
  PRIMARY KEY (sensor_id, ts)
) PARTITION BY RANGE (ts);
CREATE TABLE readings_2026_11
  PARTITION OF readings
  FOR VALUES FROM ('2026-11-01')
  TO ('2026-12-01');

Cassandra · CQL

The sensor and the day are the partition key; TTL and compaction are table options.

readings.cqlruns offline
CREATE TABLE readings_by_sensor_day (
  sensor_id  uuid,
  day        date,
  ts         timestamp,
  temp_c     float,
  humidity   float,
  battery_mv int,
  PRIMARY KEY ((sensor_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC)
  AND default_time_to_live = 7776000
  AND compaction = {
   'class': 'TimeWindowCompactionStrategy',
   'compaction_window_unit': 'DAYS',
   'compaction_window_size': 1};

The shift: relational makes the table big and drops months by hand; Cassandra gives every row a 90-day lifetime when it is written (TTL) and compacts by time window.

TTL (time to live) means "this value disappears after N seconds". 7,776,000 seconds is 90 days. The other two tables are small and plain.

readings.cql (continued)runs offline
-- Q3: latest value, one row per sensor, overwritten in place
CREATE TABLE latest_by_site (
  site_id    uuid,
  sensor_id  uuid,
  ts         timestamp,
  temp_c     float,
  humidity   float,
  PRIMARY KEY ((site_id), sensor_id)
);

-- Q4: hourly summary, written by a stream job (Flink/Spark)
CREATE TABLE hourly_by_sensor_month (
  sensor_id  uuid,
  month      int,        -- 202611
  hour_start timestamp,
  min_temp   float,
  max_temp   float,
  sum_temp   double,     -- average = sum_temp / n
  n          int,
  PRIMARY KEY ((sensor_id, month), hour_start)
) WITH CLUSTERING ORDER BY (hour_start DESC)
  AND default_time_to_live = 63072000;   -- 2 years

Cassandra does not compute the hourly average for you. In relational you write GROUP BY date_trunc('hour', ts) and the database scans 8,640 rows per day per sensor on every chart. In Cassandra a stream job (Kafka plus Flink or Spark) computes each hour once and writes it to its own table. That is the aggregate replacement.

Step 3 · The writes

Relational · PostgreSQL

Insert the reading, then upsert the latest row.

write.sqlruns offline
INSERT INTO readings
  (sensor_id, ts, temp_c, humidity)
VALUES (501, now(), 4.1, 61);
INSERT INTO sensor_latest
  (sensor_id, ts, temp_c)
VALUES (501, now(), 4.1)
ON CONFLICT (sensor_id) DO UPDATE
  SET ts = EXCLUDED.ts,
      temp_c = EXCLUDED.temp_c;

Cassandra · CQL

Two plain writes. Both are upserts, no check first.

write.cqlruns offline
INSERT INTO readings_by_sensor_day
  (sensor_id, day, ts, temp_c, humidity)
VALUES (?, ?, ?, 4.1, 61);

INSERT INTO latest_by_site
  (site_id, sensor_id, ts, temp_c)
VALUES (?, ?, ?, 4.1);

The shift: relational needs ON CONFLICT to overwrite; every Cassandra write is already an upsert (upsert).

There is no batch here, and that is a decision. If the second write is lost, the board shows a value that is 10 seconds old until the next reading overwrites it. A lost write costs nothing, so a logged batch would only add work. The gateway may group several readings of the same sensor and day into one single-partition batch; that kind of batch is cheap.

The trap: batching readings of 100 different sensors into one unlogged batch to "reduce round trips". The coordinator must forward each row to a different node, so one node does the work of 100 and becomes the bottleneck. Send them as 100 separate async writes instead.

Step 4 · The reads

Relational · PostgreSQL

Q1 and Q3 as SQL. Q3 needs a trick to get one row per sensor.

reads.sqlruns offline
-- Q1
SELECT ts, temp_c FROM readings
WHERE sensor_id = 501
  AND ts >= now() - interval '1 hour'
ORDER BY ts DESC;
-- Q3
SELECT DISTINCT ON (sensor_id)
       sensor_id, ts, temp_c
FROM readings
WHERE sensor_id IN (SELECT id FROM sensors
                    WHERE site_id = 12)
ORDER BY sensor_id, ts DESC;

Cassandra · CQL

Q1 is two partition reads. Q3 is one.

reads.cqlruns offline
-- Q1 (run for today and for yesterday)
SELECT ts, temp_c FROM readings_by_sensor_day
WHERE sensor_id = ? AND day = ?
  AND ts >= ?;
-- Q3
SELECT sensor_id, ts, temp_c
FROM latest_by_site
WHERE site_id = ?;

The shift: relational computes the latest row by scanning; Cassandra stored the latest row on purpose, so Q3 is a read of 200 small rows.

q4.cqlruns offline
-- Q4: 30 days of hourly summaries = 2 monthly partitions, read together
SELECT hour_start, min_temp, max_temp, sum_temp, n
FROM hourly_by_sensor_month
WHERE sensor_id = ? AND month = 202611;

The app divides sum_temp by n to get the average. Storing the sum and the count, not the average, is deliberate: two partial summaries can be added together later, but two averages cannot be averaged correctly.

Step 5 · Partition-size math

Relational · PostgreSQL

Total size and index.

size.txtruns offline
432M rows/day x 90 days = 39 billion rows
row ~ 50 B  -> ~1.9 TB heap
index (sensor, ts) ~ 40 B -> ~1.5 TB
5,000 inserts/s, each updating the index

Cassandra · CQL

Size of one partition at three sample rates.

size.txtruns offline
1 reading / 10 s: 8,640 rows x 50 B = 432 KB
1 reading / 1 s: 86,400 rows x 50 B = 4.3 MB
  (under 100 MB, at the 100,000 row limit)
1 / 100 ms: 864,000 rows -> bucket by HOUR
  36,000 rows x 50 B = 1.8 MB
no bucket, 90 days at 10 s: 777,600 rows
  = 39 MB but 7x the row guideline  BAD

The shift: relational asks about total rows and index depth; Cassandra asks what bucket keeps one partition under the guideline at the fastest sensor you will ever have.

The cluster as a whole stores the same 1.9 TB of raw data, times the replication factor of 3, so about 5.8 TB, spread across the nodes. That is a capacity-planning number, not a design limit: add nodes to add space.

TWCS drops a whole window; DELETE has to touch every row Cassandra: TTL + TWCS windowd-911 file windowd-31 file windowd-21 file windowd-11 file windowtodaymemtable oldest window: every row past its 90-day TTL whole file deleted, no row is read new data lands in today's window only never UPDATE or DELETE old rows by hand (it would drag old files back into play) Relational: two ways to expire A. DELETE FROM readingsWHERE ts < now() - '90 days' 432M rows deleted per day, each leaves a dead row, vacuum must rewrite pages (bloat, I/O) B. DROP TABLE readings_2026_08(a monthly partition) good: the same idea as TWCS, done by hand needs a job to create and drop partitions
Fig. 18.23 — Expiry both ways. Cassandra expires rows by time and removes whole files. PostgreSQL gets the same effect only with range partitions you create and drop yourself.

Step 6 · What breaks

Be fair to the relational side. PostgreSQL with range partitions, or the TimescaleDB extension, handles sensor data well on one site and with moderate volume. The case for Cassandra is a write rate that never sleeps (5,000 per second here), data in several regions, and a retention rule that is "drop everything older than 90 days" without a human.

Relational · PostgreSQL

What strains in a single relational table.

breaks.txtruns offline
DELETE of 432M rows/day -> bloat, long vacuum
one index on 39B rows: 5+ levels deep
Q3 scans back per sensor
fix: range partitions + a latest table
-- which is the Cassandra design,
-- built by hand

Cassandra · CQL

The relational habit applied to CQL: no bucket, manual deletes.

breaks.cqlruns offline
CREATE TABLE readings (
  sensor_id uuid, ts timestamp, temp_c float,
  PRIMARY KEY (sensor_id, ts));
-- ❌ TRAP: partition grows forever: 8,640/day
--    -> 3.1 million rows in a year
DELETE FROM readings WHERE sensor_id = ?
  AND ts < '2026-08-25';
-- ❌ TRAP: a range tombstone per call; reads
--    must skip them for 10 days (gc_grace)

The shift: relational pays for deletion with vacuum; Cassandra pays with tombstones, so it avoids deletion and lets TTL and compaction do the work.

There is one more rule for TTL tables. Cassandra removes a data file only when every cell in it is past its TTL and also past gc_grace_seconds (default 10 days, see deletes). Because nothing here is ever deleted by hand, you may lower gc_grace_seconds on this table; check the current docs for the repair implications before you do.

Step 7 · A new requirement arrives

Food-safety wants a new rule: "alert when any sensor in a store exceeds 8 °C at any time in the last 10 minutes." The question spans many sensors and a time window, and it must fire without anyone opening a screen.

Relational · PostgreSQL

One GROUP BY over a site and a window, run on a timer.

new.sqlruns offline
SELECT s.site_id, r.sensor_id,
       max(r.temp_c) AS peak
FROM readings r
JOIN sensors s ON s.id = r.sensor_id
WHERE r.ts > now() - interval '10 min'
GROUP BY s.site_id, r.sensor_id
HAVING max(r.temp_c) > 8;
-- run every minute by a scheduler

Cassandra · CQL

The partition is per sensor and day, so a store-wide query has no partition key. Do not run it as a query.

new.cqlruns offline
-- ❌ TRAP: no partition key, no way to
--    find 'all sensors of a store' here
SELECT sensor_id, max(temp_c)
FROM readings_by_sensor_day
WHERE ts > ? ALLOW FILTERING;
-- would scan every partition on every
-- node, each minute

The shift: relational answers any new question with a scan or an index; in Cassandra a question across partitions is moved out of the database and into the data stream.

Notice how the question is really two things at once: "look at the last 10 minutes" and "for every sensor of a store". A window over a moving stream is what stream processors do, so the Cassandra team does not touch the readings table at all.

  1. Read the same events: the gateway already publishes each reading to a Kafka topic (Chapter E17). A Flink or Kafka Streams job consumes it, keyed by site_id.
  2. Hold a 10-minute window: the job keeps the highest value seen per sensor in the last 10 minutes, in its own state.
  3. Write only alerts: when a window peak is above 8 °C, the job writes one row to a small table and raises the alarm.
  4. Show them: the dashboard reads the alert table, one partition per site.
alerts.cqlruns offline
CREATE TABLE alerts_by_site (
  site_id   uuid,
  raised_at timestamp,
  sensor_id uuid,
  peak_c    float,
  PRIMARY KEY ((site_id), raised_at, sensor_id)
) WITH CLUSTERING ORDER BY (raised_at DESC, sensor_id ASC)
  AND default_time_to_live = 2592000;   -- keep 30 days
Options for the new requirement
OptionPick it whenCost or catch
Stream job on the Kafka topicalerts must fire within seconds, rules change oftena job to run and monitor; state to recover after restart
Column on latest_by_site updated by the write pathonly 'is it above 8 right now' is neededanswers 'now', not 'any time in the last 10 minutes'; a brief spike between readings can be missed
Periodic query job over a rollup tablea one-minute delay is finereads hourly or per-minute rollups, not raw readings; adds a rollup table
PostgreSQL with a time-series extensionone region, moderate volume, ad hoc rulesthe primary does all the work; scale limit comes sooner

This is the same lesson as aggregates: the work that spans many partitions is done once, outside, and the result is stored where a single-partition read can find it. A new rule that needs a schema change is a new table or a new consumer, never a scan.

Case d · Social activity feed: fan-out on write, the celebrity problem

Step 1 · The requirement and what each side asks first

QuickBite adds "Dish Diary": people post photos and notes about what they ate, and follow other people and restaurants. The home feed shows the latest 50 posts from everyone you follow, newest first. A profile page shows one person's posts.

Planning numbers (illustrative): 10 million users, 5 million posts a day, an average account has 200 followers and follows 200 accounts. A few accounts are celebrity chefs with 20 million followers. Feed opens: 50 million a day, about 580 per second on average, 6,000 per second at peak.

Relational · PostgreSQL

Entities first: users, a follows relationship, posts.

erd.txtruns offline
users *--* users   (follows)
users 1--* posts
-- feed = posts of everyone I follow,
-- computed by a join when I open it

Cassandra · CQL

Screens first. Six questions, with the write path in mind.

questions.txtruns offline
Q1 home feed: latest 50, newest first
Q2 profile: one person's posts
Q3 open one post by id
Q4 who follows author X (for delivery)
Q5 who do I follow (follow button)
Q6 celebrities I follow

The shift: relational answers Q1 at read time by joining follows to posts; Cassandra answers Q1 by having already put the post into every follower's feed.

Access patterns for the feed
QueryAsks forRate (illustrative)
Q1latest 50 feed entries of one user6,000 per second at peak
Q2posts of one author, newest first1,500 per second
Q3one post, full body300,000 per second (50 per feed open)
Q4all followers of an authoronce per post: 60 per second
Q5, Q6who I follow, and which of those are celebritiesper feed open, cached in the app
Feed: pay at read time, or pay at write time Fan-out on READ (relational join) @ana posts @ben posts 300 authors Maya opensfeed: JOIN +merge + sort cost per feed open = 300 index probes grows with how many people you follow cheap to post, costly to read Fan-out on WRITE (Cassandra) @anapostsonce feed_by_user(Maya) feed_by_user(Raj) feed_by_user(+198 more) Maya's read = one partition, LIMIT 50 cost per post = 200 small writes cheap to read, costly to post
Fig. 18.24 — Two places to pay the cost of a feed. Cassandra writes are cheap and spread out, so it pays at write time.

Step 1b · Trace one real request, both ways

Follow one action: Maya, who follows 300 accounts (3 of them celebrity chefs), opens the Dish Diary app at 08:40 and pulls to refresh. She expects the 50 newest posts within a blink.

Relational · PostgreSQL

Fan-out on read: merge the posts of every account Maya follows.

plan.txtruns offline
# illustrative EXPLAIN (ANALYZE)
Limit (rows=50)
 -> Merge Append / Sort
    -> Nested Loop (x300 authors)
       -> Index Scan follows_pkey
          Cond: follower_id = 77
       -> Index Scan posts_author_idx
          Cond: author_id = f.followee_id
 Execution Time: 46 ms

Cassandra · CQL

Fan-out on write: read one ready-made partition, then fetch 50 posts.

trace.txtruns offline
# illustrative: three kinds of read
1 feed_by_user (user 77), LIMIT 50
    -> 1 partition, 50 rows, 1.2 ms
2 posts_by_id x50, in parallel
    -> 50 single-row reads, 2 ms each
3 posts_by_author x3 celebrities
    -> 3 cached partitions
merge in the app: 54 entries -> top 50

The shift: relational does its work per followed account at read time; Cassandra did that work at post time, so reading costs the same for 20 follows or 2,000.

The relational trace, step by step:

  1. Find the follows: an index lookup returns the 300 account ids Maya follows.
  2. Probe each author: for every id the database probes the index on (author_id, created_at DESC) for the newest posts. That is 300 index probes, and each may touch a different page.
  3. Merge and cut: the planner merges 300 sorted streams, keeps the 50 newest, and discards the rest. The work done is proportional to how many accounts Maya follows.
  4. At scale: 6,000 feed opens per second times 300 probes is 1.8 million index probes per second, all inside one database that also takes the post writes.

The Cassandra trace uses three kinds of read, all single-partition. The first is the feed itself at LOCAL_ONE (a feed that is a second stale is fine):

  1. Read the feed partition: feed_by_user for Maya, newest first, 50 rows of (post_id, author_id). About 2 KB comes back.
  2. Fetch bodies: the app sends 50 parallel reads to posts_by_id, one per post. Each goes to the replicas of that post, so the work spreads over many nodes instead of queueing on one.
  3. Celebrities: Maya's follow list says three authors are celebrities. Their latest posts come from posts_by_author (usually answered by a cache), and are merged by post_id.
  4. Return: the app sorts the 53 entries by time and sends 50 to the phone. Most of the cost is the parallel body reads, which can be removed by caching hot posts.
What grows with data size, per request
What growsRelationalCassandra
Maya follows 10x more accounts10x more probes and merge worksame single feed read; slightly more rows written per post by others
Total users 10x moreone big database must keep upadd nodes; the partition per user is unchanged
Posts per day 10x moreindex on posts grows, cold pagesfan-out writes grow 10x, which the ring absorbs
An author gets 10x more followersno change to read costpost cost grows 10x until the celebrity rule applies

Count the work, not the milliseconds. The relational feed does 300 units of work per open and the Cassandra feed does about 55, and only 3 of those depend on whom you follow. That is why the same app can serve a user who follows 20 people and one who follows 2,000 at nearly the same speed.

Step 2 · The schema

Relational · PostgreSQL

Posts, follows, and a feed query that joins them.

feed.sqlruns offline
CREATE TABLE posts (
  post_id    bigserial PRIMARY KEY,
  author_id  bigint REFERENCES users,
  body       text NOT NULL,
  created_at timestamptz DEFAULT now()
);
CREATE INDEX ON posts (author_id, created_at DESC);
CREATE TABLE follows (
  follower_id bigint REFERENCES users,
  followee_id bigint REFERENCES users,
  PRIMARY KEY (follower_id, followee_id)
);
CREATE INDEX ON follows (followee_id);

Cassandra · CQL

The feed is a table too: one partition per user, holding post ids.

feed.cqlruns offline
CREATE TABLE feed_by_user (
  user_id   uuid,
  post_id   timeuuid,
  author_id uuid,
  PRIMARY KEY ((user_id), post_id)
) WITH CLUSTERING ORDER BY (post_id DESC)
  AND default_time_to_live = 1209600;
-- 14 days: the feed never needs older

The shift: relational stores facts and joins them when you open the page; Cassandra stores the result of the join, per reader, and ages it out with TTL.

feed.cql (continued)runs offline
-- Q3: the full post, fetched by id after reading the feed
CREATE TABLE posts_by_id (
  post_id timeuuid PRIMARY KEY,
  author_id uuid, body text, photo_url text);

-- Q2: profile page, one partition per author per month
CREATE TABLE posts_by_author (
  author_id uuid, month int, post_id timeuuid,
  body text, photo_url text,
  PRIMARY KEY ((author_id, month), post_id)
) WITH CLUSTERING ORDER BY (post_id DESC);

-- Q4 and Q5: the relationship, stored once per direction
CREATE TABLE followers_by_author (
  author_id uuid, follower_id uuid,
  PRIMARY KEY ((author_id), follower_id));
CREATE TABLE following_by_user (
  user_id uuid, author_id uuid, is_celebrity boolean,
  PRIMARY KEY ((user_id), author_id));

A follow is a many-to-many link. Relational stores it once and indexes it both ways. Cassandra stores it twice, once per question ("who follows X" and "whom do I follow"), and writes both together.

Relational · PostgreSQL

Follow: one row.

follow.sqlruns offline
INSERT INTO follows (follower_id, followee_id)
VALUES (:me, :them);

Cassandra · CQL

Follow: two rows in a logged batch.

follow.cqlruns offline
BEGIN BATCH
  INSERT INTO following_by_user
   (user_id, author_id, is_celebrity)
  VALUES (:me, :them, :is_celeb);
  INSERT INTO followers_by_author
   (author_id, follower_id)
  VALUES (:them, :me);
APPLY BATCH;

The shift: relational has one fact and two indexes; Cassandra has two tables, and the batch keeps them agreeing.

Step 3 · The writes

Relational · PostgreSQL

Posting is one insert. Nobody else is touched.

post.sqlruns offline
INSERT INTO posts (author_id, body)
VALUES (:me, 'best dosa in town');

Cassandra · CQL

Posting writes the post, then one feed entry per follower.

post.cqlruns offline
INSERT INTO posts_by_id
 (post_id, author_id, body) VALUES (?,?,?);
INSERT INTO posts_by_author
 (author_id, month, post_id, body)
VALUES (?, 202611, ?, ?);
-- then, one write per follower:
INSERT INTO feed_by_user
 (user_id, post_id, author_id)
VALUES (?, ?, ?);

The shift: relational pays almost nothing at write time and everything at read time; Cassandra reverses that.

The per-follower writes are the fan-out. They are not a batch: each goes to a different partition on a different machine, and a batch of 200 such writes would make one coordinator do all the forwarding. They are sent as 200 concurrent asynchronous writes by a worker that reads followers_by_author, so the posting request returns immediately.

FanOutWorker.javaruns offline
// Consumes "post-created" events from Kafka; one event = one post.
void onPost(PostCreated e) {
  Statement followers = SimpleStatement.newInstance(
      "SELECT follower_id FROM followers_by_author WHERE author_id = ?", e.authorId());
  for (Row r : session.execute(followers)) {          // paged automatically
    session.executeAsync(insertFeed.bind(r.getUuid(0), e.postId(), e.authorId()));
  }                                                    // 200 concurrent writes
}

Because the worker reads from a Kafka topic (Chapter E17), a crash halfway simply restarts from the last committed offset. Writing the same feed entry twice is harmless, because it is an upsert on the same key.

Cost of fan-out on write (illustrative)
QuantityArithmeticResult
Feed inserts per day5 million posts x 200 followers1 billion
Feed inserts per second1 billion / 86,400about 11,600 on average
Storage for feed rows1 billion x ~40 B x 14 daysabout 560 GB, 1.7 TB with RF 3

Step 4 · The reads

Relational · PostgreSQL

One query joins follows to posts.

feed-read.sqlruns offline
SELECT p.* FROM posts p
JOIN follows f
  ON f.followee_id = p.author_id
WHERE f.follower_id = :me
ORDER BY p.created_at DESC
LIMIT 50;
-- 300 follows = 300 index range scans

Cassandra · CQL

Read the user's partition, then fetch the 50 posts.

feed-read.cqlruns offline
SELECT post_id, author_id
FROM feed_by_user
WHERE user_id = ? LIMIT 50;
-- then 50 parallel single-row reads:
SELECT body, photo_url FROM posts_by_id
WHERE post_id = ?;

The shift: relational finds the posts by scanning each followed author; Cassandra finds a ready list and then does 50 point lookups, a cost that does not depend on follow count (join replacement).

profile.cqlruns offline
-- Q2: profile page, current month; repeat with month - 1 for more
SELECT post_id, body, photo_url FROM posts_by_author
WHERE author_id = ? AND month = 202611 LIMIT 20;

Paging the feed uses the driver's paging state, or the last post_id seen: WHERE user_id = ? AND post_id < ?. Both avoid OFFSET (pagination).

Step 5 · Partition-size math

Relational · PostgreSQL

Feed by join: nothing is copied, so no per-reader size.

size.txtruns offline
posts: 5M/day = 1.8B rows/year
follows: 10M x 200 = 2 billion rows
  + a second index on followee_id
read: 6,000 feed opens/s x 300 probes
  = 1.8M index probes per second

Cassandra · CQL

One feed partition per user, bounded by TTL.

size.txtruns offline
avg user: follows 200 x 0.5 posts/day
  = 100 entries/day x 14 days = 1,400 rows
  1,400 x 40 B = 56 KB            OK
heavy user: follows 2,000 accounts
  14,000 rows = 560 KB            OK
author with 100k followers
  followers_by_author: 100,000 x 32 B
  = 3.2 MB, at the 100,000-row limit

The shift: relational cost scales with how many accounts a reader follows; Cassandra cost scales with how many followers a writer has.

That last line is the warning. The limit that fails is not the reader's feed. It is the author's follower list and the number of writes one post causes.

The celebrity problem

A celebrity chef with 20 million followers posts a photo. Fan-out on write now means 20 million inserts for one post.

celebrity-math.txtruns offline
# illustrative arithmetic
one post       = 20,000,000 feed inserts
at 20,000/s    = 1,000 seconds  (17 minutes) until the last follower has it
10 posts/day   = 200,000,000 inserts/day for ONE account
followers_by_author partition: 20M x 32 B = 640 MB in one partition   ✗

Two things break. The follower list is a single 640 MB partition, far over the guideline, and the delivery takes 17 minutes while the cluster is busy with nothing else. The fix has two parts.

  1. Do not fan out celebrities: above a threshold (for example 100,000 followers) the author is marked a celebrity. Their posts go to posts_by_author only.
  2. Mark the follow: when someone follows a celebrity, following_by_user.is_celebrity is true, and the worker skips the feed write for that author.
  3. Merge at read time: the reader's feed is the partition of ready entries plus the latest posts of the few celebrities they follow, merged by post_id (a timeuuid is time-ordered).
celebrity-read.cqlruns offline
-- 1. ready entries (all normal authors)
SELECT post_id, author_id FROM feed_by_user WHERE user_id = ? LIMIT 50;
-- 2. which celebrities do I follow? (cached in the app)
SELECT author_id FROM following_by_user WHERE user_id = ?;  -- filter is_celebrity in app
-- 3. for each celebrity (parallel, usually under 20)
SELECT post_id FROM posts_by_author
WHERE author_id = ? AND month = 202611 LIMIT 20;
-- 4. merge in the app by post_id, keep the newest 50

A celebrity's own posts_by_author partition is read by millions of people. That is a hot partition: the same three replicas serve every read. The usual remedy is a cache in front (the latest 20 posts of each celebrity are the same for everyone), refreshed when the celebrity posts.

Hybrid feed: push for normal authors, pull for celebrities normal author celebrity (20M) fan-out worker (200) feed_by_user posts_by_author no fan-out: 1 write, not 20M app mergesby post_idtop 50 1 partition ~20 celebrities read in parallel, via cache Normal reader: 1 read + 0 to 20 cached reads. Celebrity post: 1 write. Threshold and cache are tuning knobs; check your own follower distribution.
Fig. 18.25 — The hybrid design. Push (fan-out on write) for the 99.9% of authors, pull (merge on read) for the few with enormous audiences.

Step 6 · What breaks

Fan-out on write is not a Cassandra trick. You can keep a feed table in PostgreSQL too. At 11,600 inserts per second sustained plus index maintenance, you end up sharding that table by user, which is the same design on a harder base.

Relational · PostgreSQL

What strains in the join design.

breaks.txtruns offline
1.8M index probes/s at peak
sort + merge of 300 sorted ranges
per feed open, in the database CPU
the busiest authors' index pages
  stay hot in cache, others miss

Cassandra · CQL

The port that keeps follows as a join table.

breaks.cqlruns offline
SELECT * FROM posts
WHERE author_id IN (SELECT followee_id
  FROM follows WHERE follower_id = ?);
-- ❌ TRAP: no subqueries, no joins in CQL
SELECT * FROM posts
WHERE author_id IN (?, ?, ... 300 ids)
ORDER BY created_at DESC LIMIT 50;
-- ❌ TRAP: 300 partitions merged by one
--    coordinator on every feed open

The shift: relational makes the database do the merge; Cassandra refuses the join, and if you rebuild it with IN lists the coordinator becomes the bottleneck.

Step 7 · A new requirement arrives

Product adds a safety feature: "Let me mute an account. Muted accounts must disappear from my feed, including posts they already made." This changes what a feed row means, because feed rows are copies that were made earlier.

Relational · PostgreSQL

A mutes table and a NOT EXISTS in the feed query.

new.sqlruns offline
CREATE TABLE mutes (
  user_id  bigint REFERENCES users,
  muted_id bigint REFERENCES users,
  PRIMARY KEY (user_id, muted_id)
);
-- the feed query gains one line:
  AND NOT EXISTS (SELECT 1 FROM mutes m
    WHERE m.user_id = :me
      AND m.muted_id = p.author_id)

Cassandra · CQL

A small mutes table per user. The feed is read first, then filtered.

new.cqlruns offline
CREATE TABLE mutes_by_user (
  user_id  uuid,
  muted_id uuid,
  PRIMARY KEY ((user_id), muted_id)
);
-- read the feed as before, then:
SELECT muted_id FROM mutes_by_user
WHERE user_id = ?;
-- drop matching authors in the app

The shift: relational folds the rule into the query; Cassandra keeps the stored copies untouched and applies the rule when reading.

There is a tempting alternative: remove the muted account's posts from Maya's feed partition when she mutes them. In Cassandra that means finding those rows, which are not indexed by author, then deleting each one. Every delete writes a tombstone, and the next feed read must step over them.

Filtering on read has a cost of its own. If Maya has muted 10% of her follows, about one in ten rows is dropped, so the app asks for 60 rows to be sure of 50. A heavy muter may need a second page. That is a small, predictable cost, and it never touches the stored data.

  1. Create mutes_by_user: online, empty, tiny: a user mutes a few dozen accounts.
  2. Apply on read: fetch the mute list once per session (cache it), request the feed with a limit of about 1.2 times what you need, filter, page again if short.
  3. Handle unmute: just delete the mute row. No feed row was removed, so older posts reappear for free, which is usually what users expect.
  4. Keep the fan-out worker the same: the worker may also skip the write when the follower muted the author, to save storage. That is an optimisation, not required for correctness.
Options for the new requirement
OptionPick it whenCost or catch
Filter on read from mutes_by_userthe mute list is small and checked per sessionover-fetch of a few percent; extra page for heavy muters
Skip the fan-out for muted pairsyou want less storage and fewer wasted writesneeds the mute lookup in the worker; old posts still need the read filter
Delete matching rows from feed_by_useralmost neverneeds a scan of the feed, one tombstone per row, and unmute can no longer restore history
Rebuild the feed with a backfillthe rule changes for everyone at once (for example a policy ban)a job over all feed partitions; slow and expensive, but safe for a rare event

This case shows why the schema-change rule (schema change) is not only "new table". Some changes are best answered at read time, because the stored copies are an expensive thing to rewrite.

Case e · Leaderboards and counters, and where Cassandra is the wrong tool

Step 1 · The requirement and what each side asks first

QuickBite wants three small features. "Rider of the Week" shows the top 10 riders by deliveries this week. The rider app shows "You: 37 this week". Each dish on a menu shows "ordered 412 times today". About 30,000 riders, 5 million dish-orders a day.

These look easy, and they hide the one thing Cassandra cannot do: keep rows sorted by a value that keeps changing. This case shows what works, what does not, and then the larger question of what should never be put in Cassandra at all.

Relational · PostgreSQL

Count the delivery rows, or keep a counter row and index it.

questions.txtruns offline
deliveries(rider_id, order_id, at)
-- top 10 this week:
GROUP BY rider_id ORDER BY count DESC
-- or a stats row + index on count

Cassandra · CQL

Three different questions, three different tables.

questions.txtruns offline
Q1 my deliveries this week (one number)
Q2 top 10 riders this week (a ranking)
Q3 dish X ordered today (one number)
-- Q2 cannot be a plain query on a
-- counter: you cannot sort by it

The shift: relational can sort by any column at read time; Cassandra sorts only by clustering columns, which are fixed when the row is written.

Leaderboard: a counter cannot be sorted, so rank lives elsewhere A. Counter tablerider_week_counts+1 per delivery exact count per rider, cheap no top-10: cannot sort by a counter B. Snapshot tabletop_riders_by_weekrewritten every 60 s reads: one partition, 10 rows rank is up to 60 s old C. Redis sorted setZINCRBY +1 per deliveryZREVRANGE 0 9 live rank, ordered by score memory store; rebuild from events job Source of truth: delivery events (Kafka topic or Postgres rows). Every box above can be rebuilt from it. Pick B when a minute-old ranking is fine; pick C when ranks must move in seconds.
Fig. 18.26 — Where the ranking lives. Cassandra holds the counts; a snapshot or an in-memory sorted set holds the order.

Step 1b · Trace one real request, both ways

Follow one action: rider 5 finishes a delivery at 12:41 and her app refreshes "You: 37 this week". At the same moment the QuickBite home page loads the top 10 riders. Two reads and one write happen within a second.

Relational · PostgreSQL

The write is an UPSERT on the stats row; both reads use the index.

plan.txtruns offline
# illustrative EXPLAIN (ANALYZE)
-- write: row lock, WAL, index update
Insert on rider_week_stats
  Conflict: DO UPDATE  Time: 0.4 ms
-- my count
Index Scan rider_week_stats_pkey   0.05 ms
-- top 10
Index Scan Backward
  rider_week_stats_wk_cnt_idx
  Cond: week_id = 202647  LIMIT 10
  Time: 0.2 ms

Cassandra · CQL

The write is a counter update; the reads are a counter read and a snapshot read.

trace.txtruns offline
# illustrative
write: UPDATE rider_week_counts +1
  leader replica reads its own counter,
  adds 1, sends the NEW total to the
  other replicas              ~2-4 ms
read:  SELECT deliveries ... rider 5
  1 partition, 1 cell         ~1 ms
read:  top_riders_by_week LIMIT 10
  1 partition, 10 rows        ~1 ms

The shift: relational is hard to beat for a small leaderboard on one node; Cassandra's counter write does an internal read first, and its ranking is read from a table another process wrote.

The relational trace is short, which is the honest point of this case:

  1. Write: the transaction locks rider 5's row for the week, updates the count, writes the log, and updates two indexes, one of which is (week_id, deliveries DESC). At 58 events per second that is nothing.
  2. My count: a primary-key lookup, about 3 page reads.
  3. Top 10: walk the count index backward from the highest value in the week. 10 entries, 10 heap rows.

The Cassandra trace, with the three differences from a plain write:

  1. Counter write: the coordinator sends the increment to one replica, the counter leader for that update. It reads its stored value, adds one, and replicates the resulting total. That internal read is why counter writes cost more than normal ones, and why a retried timeout can count twice (counter).
  2. My count: an ordinary partition read of one cell, at LOCAL_QUORUM so it reflects the write just made.
  3. Top 10: a read of top_riders_by_week, partition 202647, 10 rows ordered by rank. It is a normal single-partition read, but the data in it was written by the snapshot job up to a minute ago.
  4. Staleness: after Rider 5's 37th delivery, her own count is exact, while the ranking may still show 36 until the next snapshot. The app should say "updated a minute ago" instead of hiding it.
What grows with data size, per request
What growsRelationalCassandra
Riders 10x more (300,000)index still 3 to 4 levels deep; top-10 cost unchangedcounter partitions per rider, same cost; snapshot job scans 10x more counters
Events per second 10x morerow lock contention appears on busy rowsspread over many partitions, unless one counter is hot (shard it)
Ranking needs seconds-fresh dataalready trueneeds a Redis sorted set or a faster job
History of past weeksmore rows, same indexmore clustering rows per rider, tiny

This is the one case where the relational trace is simply good. A small leaderboard on one machine is a solved problem, and saying so is a mark of a senior answer. The reason to leave PostgreSQL for it is write volume, geography or hot rows, not the shape of the query.

Step 2 · The schema

Relational · PostgreSQL

Stats row per rider and week, indexed by count for the top 10.

lb.sqlruns offline
CREATE TABLE rider_week_stats (
  week_id    int,
  rider_id   bigint,
  deliveries int NOT NULL DEFAULT 0,
  PRIMARY KEY (week_id, rider_id)
);
CREATE INDEX ON rider_week_stats
  (week_id, deliveries DESC);

Cassandra · CQL

A counter table. In a counter table every non-key column must be a counter.

lb.cqlruns offline
CREATE TABLE rider_week_counts (
  rider_id   uuid,
  week_id    int,
  deliveries counter,
  PRIMARY KEY ((rider_id), week_id)
);
CREATE TABLE dish_orders_by_day (
  item_id uuid, day date,
  orders counter,
  PRIMARY KEY ((item_id), day)
);

The shift: relational stores a number you can index; Cassandra stores a counter you can only add to and read (counter).

The ranking itself is a plain table, written by a job, with the rank as the clustering key. This is the "snapshot" from Fig. 18.26.

top-riders.cqlruns offline
CREATE TABLE top_riders_by_week (
  week_id    int,
  rank       int,
  rider_id   uuid,
  name       text,
  deliveries int,
  PRIMARY KEY ((week_id), rank)
) WITH CLUSTERING ORDER BY (rank ASC);

Step 3 · The writes

Relational · PostgreSQL

An atomic increment on a row. Transactions make retries safe.

inc.sqlruns offline
INSERT INTO rider_week_stats
  (week_id, rider_id, deliveries)
VALUES (202647, 5, 1)
ON CONFLICT (week_id, rider_id)
DO UPDATE SET deliveries =
  rider_week_stats.deliveries + 1;

Cassandra · CQL

A counter update. No read, no lock, but no safe retry either.

inc.cqlruns offline
UPDATE rider_week_counts
SET deliveries = deliveries + 1
WHERE rider_id = ? AND week_id = 202647;

UPDATE dish_orders_by_day
SET orders = orders + 1
WHERE item_id = ? AND day = ?;

The shift: relational can undo a failed increment with its transaction; a Cassandra counter that times out may or may not have been applied, and a retry may count twice.

Counters are fine when an error of a few counts does not matter, as with "ordered 412 times today". They are wrong when the number is money or stock. Counter columns also cannot have a TTL, cannot sit in a table with ordinary columns, and are awkward to reset.

If you need an exact, retry-safe count, store one small row per event and count inside one partition. The same delivery written twice is the same row, so a retry changes nothing.

Relational · PostgreSQL

Count rows. A plain GROUP BY.

exact.sqlruns offline
SELECT count(*) FROM deliveries
WHERE rider_id = 5 AND week_id = 202647;

Cassandra · CQL

One row per delivery; count them in one partition.

exact.cqlruns offline
CREATE TABLE deliveries_by_rider_week (
  rider_id uuid, week_id int, order_id uuid,
  PRIMARY KEY ((rider_id, week_id), order_id));
SELECT count(*) FROM deliveries_by_rider_week
WHERE rider_id = ? AND week_id = 202647;

The shift: relational counts by scanning an index; Cassandra counts one small partition, about 40 rows a week per rider, so the count is exact and idempotent (aggregate).

Step 4 · The reads

Relational · PostgreSQL

The top 10 is an index scan, or a GROUP BY over the week.

top10.sqlruns offline
SELECT rider_id, deliveries
FROM rider_week_stats
WHERE week_id = 202647
ORDER BY deliveries DESC
LIMIT 10;
-- index (week_id, deliveries DESC)

Cassandra · CQL

My count is one counter read. The top 10 is a read of the snapshot.

top10.cqlruns offline
-- Q1: my number
SELECT deliveries FROM rider_week_counts
WHERE rider_id = ? AND week_id = 202647;
-- Q2: the ranking
SELECT rank, name, deliveries
FROM top_riders_by_week
WHERE week_id = 202647 LIMIT 10;

The shift: relational sorts at read time; Cassandra reads a table that was sorted at write time by a different process.

The snapshot job reads all counters for the week (30,000 rows; a once-a-minute scan of that size is fine), sorts them in memory, and writes the top 100. If you need live ranks, the same events feed a Redis sorted set:

leaderboard.redisruns offline
# one command per delivery event
ZINCRBY leaderboard:202647 1 rider:5
# top 10, highest first
ZREVRANGE leaderboard:202647 0 9 WITHSCORES
# my rank
ZREVRANK leaderboard:202647 rider:5

Redis is the right store for ordering a value that changes every second, because the sort order is the data structure. It is also memory-bound and can be rebuilt from the event stream, which is why it is safe as a derived view.

Stack choice: where does the ranking live?
OptionPick it whenCost or catch
Counter table + snapshot table (Cassandra)a ranking up to a minute old is fine and you already run Cassandraa job to write and monitor; counts are approximate
Redis sorted setranks must move in seconds, or you need rank-of-meanother system; memory sized to the leaderboard; rebuild on loss
PostgreSQL table with an index on the countone region, under about thousands of updates per secondhot rows lock under heavy writes; fine for most teams

Step 5 · Partition-size math

Relational · PostgreSQL

Hot row math: the leader's row takes every update.

size.txtruns offline
5M dish-orders/day = 58/s average
one popular dish: 3,000 orders/hour
  = about 1 update/s on one row  OK
a flash sale on one dish: 5,000/s
  = 5,000 updates/s on ONE row  BAD
  (row lock waits, WAL on one page)

Cassandra · CQL

Counter partitions are tiny, but one counter can still be hot.

size.txtruns offline
rider counter: 1 row/week x 52 = 52 rows
dish counter: 1 row/day x 365 = 365 rows
  both under 20 KB per partition  OK
a flash sale on one dish: 5,000 +1 to
  ONE partition's 3 replicas   BAD
  fix: split the counter, shard 0..15,
  PK ((item_id, shard), day), sum on read

The shift: relational hot-row cost is lock waits; the Cassandra equivalent is a hot partition, and the same trick, splitting one counter into shards, fixes both.

Where Cassandra is the wrong tool

The chapter so far showed what Cassandra does well. A senior answer also names what it does badly. Here are three requests from the same company that should stay in PostgreSQL.

Inventory: the last portion of biryani

A restaurant has 12 portions left. Two customers click "order" at the same moment on the last one. Exactly one must win, and nobody may be charged for a portion that does not exist.

Relational · PostgreSQL

One atomic statement; the database locks the row.

stock.sqlruns offline
UPDATE inventory
SET qty = qty - 1
WHERE item_id = :item AND qty > 0;
-- rows updated = 1: you got it
-- rows updated = 0: sold out

Cassandra · CQL

A compare-and-set with a lightweight transaction (LWT).

stock.cqlruns offline
-- read, then conditional write
SELECT qty FROM inventory WHERE item_id = ?;
UPDATE inventory SET qty = 11
WHERE item_id = ? IF qty = 12;
-- [applied] = False -> someone won;
-- re-read and retry the loop

The shift: relational makes the check and the change one statement; Cassandra needs a read plus a conditional write, uses Paxos (about four round trips), and loops under contention.

An LWT is linearizable for one partition and is fine for rare things like claiming a username (INSERT ... IF NOT EXISTS, see unique). On one hot row with thousands of concurrent buyers it is slow, because every attempt competes in the same Paxos round.

Payments: moving money between two accounts

Relational · PostgreSQL

One transaction, a constraint, full isolation.

pay.sqlruns offline
BEGIN;
UPDATE accounts SET balance = balance - 1840
 WHERE id = :cust;       -- CHECK (balance >= 0)
UPDATE accounts SET balance = balance + 1840
 WHERE id = :rest;
INSERT INTO ledger (debit, credit, cents)
VALUES (:cust, :rest, 1840);
COMMIT;

Cassandra · CQL

No multi-partition transaction in Cassandra 5.0. A logged batch is atomic eventually, not isolated.

pay.cqlruns offline
BEGIN BATCH
  UPDATE ... SET balance = ? WHERE id = :cust;
  UPDATE ... SET balance = ? WHERE id = :rest;
APPLY BATCH;
-- ❌ TRAP: a reader can see the debit
--    without the credit; no CHECK; and
--    balance = ? needs a read first

The shift: relational protects money with isolation and constraints; Cassandra 5.0 has neither across rows, so money stays in the relational database. Accord in Cassandra 6.0 (alpha, a preview) aims to change this.

Reporting is the third no. "Revenue by city by week, joined with restaurant categories" is a join and a GROUP BY across all data. Cassandra answers it only if you precompute it. Ad hoc analytics belongs in a warehouse or in PostgreSQL.

Is Cassandra the right tool?
WorkloadFitBetter home and why
Chat messages, order timelines, sensor readings, feedsGoodCassandra: huge writes, one partition per question, multi-region
Counters for badges (approximate)GoodCassandra counters; shard the hot ones
Live rankingPoorRedis sorted set, or a snapshot table
Stock levels, seat or slot bookingPoorPostgreSQL: atomic conditional update on one row
Payments, ledgers, refundsPoorPostgreSQL: multi-row transactions and constraints
Unique keys at scale (usernames)LimitedLWT is allowed for rare use; otherwise a relational unique index
Ad hoc reports and joinsPoorWarehouse or PostgreSQL with indexes
Small data, one region, under 100 GBOverkillPostgreSQL: simpler to run and query
Polyglot persistence: each store does what it is good at PostgreSQLorders, payments,inventory, ledger(source of truth) outbox table+ relay Kafkatopicorder-events Cassandraorders, feed,timelines Redisleaderboardrank, cache Warehousereports,ad hoc SQL ACID, constraints, joins money never leaves here consumers rebuild read models by replaying the topic Write once to the source of truth. Everything else is a copy that can be dropped and rebuilt.
Fig. 18.27 — Polyglot persistence. The transactional outbox pattern (see Chapter E7) writes the event in the same transaction as the order, so nothing is lost between PostgreSQL and Kafka (Chapter E17).

Step 6 · What breaks

Relational · PostgreSQL

What breaks with the relational habit on counts: nothing at small scale, then hot rows.

breaks.txtruns offline
GROUP BY over a week of deliveries:
  14M rows scanned per leaderboard load
fix: a stats row + index (as above)
flash sale: row lock queue on one row
fix: sharded counter rows (as Cassandra)

Cassandra · CQL

What breaks with the relational habit when porting to Cassandra.

breaks.cqlruns offline
SELECT rider_id, deliveries
FROM rider_week_counts
WHERE week_id = 202647
ORDER BY deliveries DESC LIMIT 10;
-- ❌ TRAP: ORDER BY works only on clustering
--    columns; a counter cannot be one, and
--    week_id alone is not a partition key

The shift: relational can always sort by any column; in Cassandra 'top N by a changing value' needs a second structure.

Across all five cases the lesson repeats. Cassandra rewards a workload of known questions, enormous write volume, and data that is written once and read in time order. It punishes anything that needs a changing sort, a transaction across rows, or a question nobody planned for.

Partition sizes: designed versus unbucketed (scale: 1 px = 2 MB) chat week, busiest group 7 MB orders by restaurant day 0.07 MB sensor day (10 s readings) 0.43 MB feed per heavy user (14 d) 0.56 MB followers, 100k-limit author 3.2 MB chat, no bucket, 1 year 365 MB sensor, no bucket, 90 days 39 MB celebrity followers, 1 partition 640 MB 100 MB guideline
Fig. 18.28 — Partition-size summary across the cases. Green bars are the designs in this chapter. Red bars are what you get without the bucket, TTL or shard.

Step 7 · A new requirement arrives

Regional managers ask: "Give me the weekly leaderboard per city, so Mumbai riders compete with Mumbai riders." The counters are still per rider and week. What is new is a grouping by city that neither the counter table nor the snapshot has.

Relational · PostgreSQL

Add a city to the grouping and the index.

new.sqlruns offline
ALTER TABLE rider_week_stats
  ADD COLUMN city text;
CREATE INDEX CONCURRENTLY stats_city_idx
  ON rider_week_stats
  (week_id, city, deliveries DESC);

SELECT rider_id, deliveries
FROM rider_week_stats
WHERE week_id = 202647 AND city = 'Pune'
ORDER BY deliveries DESC LIMIT 10;

Cassandra · CQL

A new snapshot table. The counters do not change at all.

new.cqlruns offline
CREATE TABLE top_riders_by_city_week (
  city       text,
  week_id    int,
  rank       int,
  rider_id   uuid,
  deliveries int,
  PRIMARY KEY ((city, week_id), rank)
);
SELECT rank, rider_id, deliveries
FROM top_riders_by_city_week
WHERE city = 'Pune' AND week_id = 202647
LIMIT 10;

The shift: relational adds a column and an index and the database re-sorts; Cassandra adds a table and lets the snapshot job do a per-city sort.

This change is cheap in Cassandra for a reason that is easy to miss. The new table is derived data. It holds nothing that cannot be rebuilt from the counters, so there is no dual write on the hot path and no backfill risk.

The only new requirement is knowing each rider's city, which belongs in a small profile table. The snapshot job joins the two in memory, because it is a batch job, not a query.

riders_by_id.cqlruns offline
CREATE TABLE riders_by_id (
  rider_id uuid PRIMARY KEY,
  name text, city text);
  1. Create the two tables: riders_by_id and top_riders_by_city_week. Both are online and empty.
  2. Fill the profile table once: a copy from the PostgreSQL riders table, then keep it in step through the same event stream that feeds everything else.
  3. Extend the snapshot job: read all counters for the week, look up each rider's city in memory, sort per city, write the top 100 per city.
  4. Switch the new screen: it reads one partition per city. Existing screens never changed.
Options for the new requirement
OptionPick it whenCost or catch
New snapshot table per groupingeach grouping is a known screenone more derived table and one more output of the job
Counters per (city, rider, week)the number itself must be per citya second counter increment on every delivery; city changes cannot be fixed afterwards
Redis sorted set per cityranks must move in secondsone more key family; the app routes by city
Query in PostgreSQL from delivery eventsan ad hoc or occasional reportscans a week of events each time; fine for reports, not for a live page

Use the schema-change rule to say it in an interview: when the new question is a regrouping of data you already hold, add a derived table and rebuild it; when it needs data you never stored, add a column or table, dual write, and backfill. SAI on a counter table is not possible, and a secondary index on top of the counter would not give you a ranking (secondary index).

The five cases on one page Case Partition key Clustering Bucket / expiry Replaces a. Chat (conversation, week) message_id DESC weekly bucket index + join b. Orders customer; order(restaurant, day) placed_at DESC,line_no day bucket 3-way join c. IoT (sensor, day) ts DESC TTL 90 d + TWCS DELETE + vacuum d. Feed user (+ author, month) post_id DESC TTL 14 d follow JOIN e. Counters rider; (item, day) week / rank snapshot job GROUP BY + sort Read it right to left: each relational habit on the right became the key choices on the left.
Fig. 18.29 — All five cases in one grid. Every Cassandra table is a partition key plus a clustering order, and every one replaces something the relational planner used to do at read time.

09 · DrillModelling and keys — Q1–Q50

The first fifty questions cover how to think when you move from a relational design to Cassandra: queries before tables, keys as placement and order, and the translations of joins, relationships and constraints. Each answer has a side-by-side picture of the relational way and the Cassandra way. Say your answer first, then reveal.

Drill · The mindset: query first

These questions test whether you describe Cassandra as query-first.

Q1. "What is the core difference between modelling data in PostgreSQL and in Cassandra?"

Reveal answer

Strong answer In PostgreSQL I model the data first and ask questions later. I draw entities, normalise them so each fact is stored once, and rely on the planner, joins and indexes to answer whatever query shows up next month.

In Cassandra I list the questions first and build one table per question. Each table is shaped so a read goes to one partition (one bucket of rows on a few nodes) and reads rows that are already sorted.

The reason is physical. Cassandra spreads rows over many machines by hashing the partition key. A join or a scan would have to visit many machines, so the design avoids them by storing the answer ready-made.

So the design input changes. Relational input is the shape of the data. Cassandra input is the list of queries, with their expected rates and result sizes.

Picture it One question, "show a customer's recent orders", answered by each design.

The setup: QuickBite has 2 million customers and 40 million orders. The app screen needs the last 20 orders of one customer, newest first.

Relational · PostgreSQL

Orders live in one table. An index on customer makes the lookup fast.

orders.sqlruns offline
CREATE TABLE orders (
  order_id bigint PRIMARY KEY,
  customer_id bigint,
  placed_at timestamptz,
  total numeric(10,2));
CREATE INDEX ON orders (customer_id, placed_at);

Cassandra · CQL

The table itself is built for this one question. Key = customer, order inside = newest first.

orders_by_customer.cqlruns offline
CREATE TABLE orders_by_customer (
  customer_id bigint,
  placed_at timestamp,
  order_id bigint,
  total decimal,
  PRIMARY KEY ((customer_id),
    placed_at, order_id)
) WITH CLUSTERING ORDER BY
    (placed_at DESC, order_id ASC);

The shift: Relational makes the data general, then the index serves the query. Cassandra makes the table the query.

Make the invisible visible: Run the same screen query on both and see how many places each one visits.

the read, both waysruns offline
-- PostgreSQL: index range scan, one machine
SELECT * FROM orders WHERE customer_id = 7
ORDER BY placed_at DESC LIMIT 20;

-- Cassandra: one partition, rows already sorted
SELECT * FROM orders_by_customer
WHERE customer_id = 7 LIMIT 20;

Why: On PostgreSQL the same table can answer 50 other questions with other indexes. In Cassandra this table answers exactly one, and the second question gets its own table.

Land it I say relational designs start from the data and Cassandra designs start from the queries, because the Cassandra read must hit one partition.

Likely follow-ups
"So does Cassandra have no schema?"

It has a strict schema, which surprises people who hear "NoSQL". You declare every table, every column type and the primary key, and CQL (Cassandra's query language) looks very close to SQL. What is missing is the relational promise that any query on that schema will work.

PostgreSQL accepts any WHERE you write, and its planner (the part that picks how to run a query) uses an index or scans the table. The answer is always correct, sometimes slow. Cassandra accepts only queries that follow the primary key, because the key decides which machine holds the row and how rows are sorted.

same question, two databasesruns offline
-- illustrative
-- PostgreSQL: runs; the planner scans, or uses an index if one exists
SELECT * FROM orders WHERE restaurant_id = 12 AND status = 'NEW';
-- Cassandra: the table is keyed by customer_id, so this is refused
SELECT * FROM orders_by_customer WHERE restaurant_id = 12 AND status = 'NEW';
-- InvalidRequest: ... might involve data filtering

So I read a Cassandra schema as a contract about reads: if the key matches the query it is fast, and if not it is refused.

"Is it just denormalisation?"

Denormalisation (storing the same fact in more than one place) is part of it, but it is the last step, not the first. The order is queries, then keys, then copies.

  1. Queries: list each screen and what it asks. QuickBite has "my orders", "one order with its items" and "live orders of a restaurant today".
  2. Keys: for each query, choose the partition key it always knows and the clustering order it wants.
  3. Copies: only now copy into each table the fields that screen shows.

PostgreSQL people denormalise too, but as a measured fix for one slow query, while the normalised tables stay the truth. In Cassandra the copies are the design from day one. With three screens I expect about three tables, and one order is written three times.

Denormalising without the query list gives tables that nobody can read cheaply. That is the trap I would name in an interview.

"What do you lose by working query first?"

Flexibility. In PostgreSQL a new question is usually a new SELECT, maybe with an index. In Cassandra it usually means a new table plus a backfill (copying the old data into the new shape).

The backfill has a real cost. Suppose 40 million old orders and a job throttled to 5,000 rows a second so live traffic is not hurt.

backfill timeruns offline
# illustrative
40,000,000 rows / 5,000 rows per second = 8,000 seconds
8,000 s / 3,600 = about 2.2 hours, for one table and one pass

You also lose joins, ad-hoc reporting and constraints that span rows. Those jobs move elsewhere: reports go to a warehouse, or to PostgreSQL fed from the same events.

The trade is good when the screens are known and the volume is large. It is bad when the questions change weekly, so I ask for the query list before I agree to the model.

"When would you refuse Cassandra for a project?"

I would refuse it when the data fits comfortably on one PostgreSQL primary, when the questions change often, or when I need multi-row transactions and constraints (unique, foreign key) across tables. Those are PostgreSQL's strengths, and Cassandra gives them up on purpose.

Cassandra earns its place when write volume or data size outgrows one primary, or when the app must keep serving through the loss of a whole data centre. Those are the problems its design solves.

Count the cost honestly. A sensible cluster is at least three nodes with replication factor 3 (three copies of every row), plus repair, compaction monitoring, and one table per query. A single PostgreSQL primary with a replica is often cheaper and simpler, well into the terabytes, though you should measure your own workload.

My rule is to choose Cassandra for the problem it solves, never for the word "scalable".

Q2 · Scenario. "We ported our normalised PostgreSQL schema to Cassandra table for table. It worked in test and times out in production. What went wrong?"

Reveal answer

Strong answer The team copied the shape of the data and kept the habit of asking any question later. In Cassandra a table answers only questions that begin with its partition key.

So every query that does not start with the partition key falls back on ALLOW FILTERING or a secondary index. Both make the coordinator ask many nodes and scan. With 1,000 test rows that is invisible. With 4 billion rows on 30 nodes it times out.

The fix is not tuning. The fix is to go back to the screen list, write each query down, and build one table per query.

Picture it A one-to-one port and the two queries that break it.

The setup: Ported tables: orders keyed by order id, customers keyed by customer id. The app needs orders by customer, and customers by email.

Relational · PostgreSQL

Foreign key and an index do the work.

pg.sqlruns offline
SELECT o.*
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE c.email = 'a@b.com';

Cassandra · CQL

A straight port has no join and no way in.

port.cqlruns offline
SELECT * FROM orders
WHERE customer_email = 'a@b.com'
ALLOW FILTERING;
-- ❌ TRAP: scans every node's data

The shift: The port keeps the data model and drops the query model.

What you see: What the coordinator actually does for the ported query.

cluster-wide scanruns offline
# illustrative output
coordinator -> node1  scan orders ... 90M rows
            -> node2  scan orders ... 88M rows
            -> ... 30 nodes
ReadTimeout: Operation timed out - received only 12 of 30 responses

The fix: Two query-shaped tables, written together.

orders_by_customer + customer_by_emailruns offline
CREATE TABLE customer_by_email (
  email text PRIMARY KEY, customer_id bigint);
CREATE TABLE orders_by_customer (
  customer_id bigint, placed_at timestamp,
  order_id bigint, total decimal,
  PRIMARY KEY (customer_id, placed_at, order_id));
-- step 1: email -> id. step 2: id -> orders.

Why: Each step is a single-partition read. Two cheap reads replace one join that cannot exist.

Land it I would say we ported the tables but not the questions, so I list the queries and rebuild one table per query.

Likely follow-ups
"Could a secondary index on customer_email have saved them?"

It would run, and on a small cluster it would look fine, but it hurts at scale. A classic secondary index in Cassandra is stored locally on each node, next to that node's own data. With no partition key in the query, the coordinator (the node handling the request) cannot tell who holds the email, so it asks nodes across the whole ring.

PostgreSQL is different: one B-tree index on one primary finds the row directly. The statement CREATE INDEX looks the same, but the cost is very different.

index versus lookup tableruns offline
-- illustrative
-- PostgreSQL: one index, one lookup
CREATE INDEX ON customers (email);
-- Cassandra: the index exists, but this still fans out to many nodes
SELECT * FROM customers_by_id WHERE email = 'a@b.com';
-- Cassandra, fast: a small table keyed by email
SELECT customer_id FROM customers_by_email WHERE email = 'a@b.com';

The lookup table costs one extra write at sign-up, and then every login is one read on one replica set, however big the cluster grows. A fan-out query gets slower as nodes are added, so scale works against it. For a lookup on every login I build the lookup table. The index is acceptable for a rare admin query.

"Why did it pass testing?"

Because a test hides the one thing that makes a scan expensive, which is size. With 1,000 rows on one node, reading the whole table takes about a millisecond, so a filtering query looks the same as one that seeks.

PostgreSQL has the same trap, but there you can usually add an index later. In Cassandra the cost is baked into the table design. Three things were missing from the test:

  1. Volume: realistic row counts spread over many partitions, not thousands of rows in a few.
  2. Topology: several nodes with replication factor 3, since the fan-out only shows when data is spread.
  3. Concurrency: many clients at once. One slow scan is invisible, 200 at once are not.

The production numbers show why it matters. 4 billion rows on 30 nodes is about 133 million rows per node (4,000,000,000 / 30), and a filtering query may read most of them to return 3.

I also add a review rule: any ALLOW FILTERING in a pull request needs a written reason.

"How do you find offending queries in production?"

I look in three places, because each one shows a different symptom. PostgreSQL gives me EXPLAIN ANALYZE and pg_stat_statements. Cassandra has no EXPLAIN, so I rely on the code, the logs and the metrics.

  1. Code: search for ALLOW FILTERING and for CREATE INDEX statements. Each hit is a query that does not follow its table's key.
  2. Logs: the server reports queries slower than a threshold, and warns about tombstones read. Check the docs for your version for the exact setting names.
  3. Metrics: read latency percentiles per table from the driver or from nodetool tablestats. A table with a flat 3 ms p99 is healthy. One with 800 ms p99 and spikes on the whole cluster is probably scanning.

For a suspect query I turn on tracing in cqlsh and count the replicas and rows it touches.

Every offender becomes one line in the access-pattern list: which table should answer it?

"Do you migrate data in place?"

No. In PostgreSQL I would run an UPDATE or ALTER TABLE in place and wait. In Cassandra you cannot change a primary key in place, and a big in-place rewrite has no safe equivalent. I migrate beside the old tables.

  1. Create: the new tables, shaped by the access-pattern list, next to the old ones.
  2. Dual write: the application writes to old and new on every change.
  3. Backfill: a throttled job copies old rows into the new tables. Writes are upserts, so running it twice is harmless.
  4. Switch and drop: move reads to the new tables, watch them for a week, then drop the old ones.

Each step is safe to stop at, and each can be rolled back by pointing reads at the old table again. The cost is extra storage and extra writes while both exist. I never do a big-bang cutover, because the one thing that cannot be undone is dropping the old table too early.

Q3. "Why does Cassandra have no joins?"

Reveal answer

Strong answer A join needs rows from two tables that match on a value. In Cassandra the two sets of rows usually sit on different machines, picked by hashing different partition keys.

A join would be a network shuffle across the cluster, at read time, with no promise on how long it takes. Cassandra's promise is a predictable read: one partition, few nodes.

So the join is done at write time instead. When an order is placed, I write the customer name and restaurant name into the order row. The read then needs no second table.

Picture it Order list with restaurant name, with and without a join.

The setup: The screen shows each order with the restaurant's name. Restaurant 12 is called Spice Hut.

Relational · PostgreSQL

The order stores restaurant_id. A join finds the name.

join.sqlruns offline
SELECT o.order_id, r.name
FROM orders o
JOIN restaurants r
  ON r.id = o.restaurant_id
WHERE o.customer_id = 7;

Cassandra · CQL

The order row carries the name itself.

embed.cqlruns offline
SELECT order_id, restaurant_name
FROM orders_by_customer
WHERE customer_id = 7;

The shift: The join moves from read time to write time.

Make the invisible visible: What is stored in each design for the same order.

stored rowsruns offline
# illustrative output
PostgreSQL  orders:      (42, customer 7, restaurant 12)
            restaurants: (12, 'Spice Hut')      -- join at read

Cassandra   orders_by_customer:
            (7, 2026-11-23 19:02, 42, 'Spice Hut')  -- copy

Why: Reading one partition returns everything. The cost is that the name now exists in many rows.

Land it I explain that Cassandra moves the join from read time to write time by storing the needed fields in the row.

Likely follow-ups
"What if the restaurant renames itself?"

Old orders keep the old name, and that is usually correct. An order is a historical fact: it records what the customer saw when they paid.

The two databases differ in what they do by default. A PostgreSQL join shows the current name on every old order, unless you also copied the name into the orders table. Cassandra copied the name at write time, so it freezes it.

after a renameruns offline
-- illustrative
-- PostgreSQL join: old orders now show the NEW name
SELECT o.order_id, r.name FROM orders o
JOIN restaurants r ON r.id = o.restaurant_id WHERE o.customer_id = 7;
-- Cassandra: the name was copied when the order was placed
SELECT order_id, restaurant_name FROM orders_by_customer WHERE customer_id = 7;

If a screen must show the current name, I store the restaurant id as well and look the name up in the application from a cache. A page of 20 orders with 5 restaurants then costs 5 small reads, which run in parallel. Which behaviour is right is a business decision, so I ask for it per screen. A receipt should never change after the fact.

"Can the application do the join instead?"

Yes, for small lookups. This is the only join I do at read time, and I count the reads before agreeing to it.

  1. List: one query returns 20 orders from orders_by_customer.
  2. Collect: the app picks out the distinct restaurant ids, say 5.
  3. Fetch: it reads those 5 rows by primary key from a small restaurant table, in parallel.
  4. Merge: it joins the two results in memory.

That is 6 queries and about the time of the slowest one, because the 5 run together. At 1,000 page views a second it is 6,000 reads a second, which a healthy cluster handles.

PostgreSQL does the same work inside one query on one machine. Here the network hops are yours to count. If one request needs hundreds of lookups, I stop and copy the field into the row instead.

"Does Spark or a warehouse do joins on Cassandra data?"

Yes, but as a batch job, never in a user request. Spark (a distributed data-processing engine) can read a Cassandra table in token ranges, many ranges in parallel, join it with another dataset, and write the result somewhere else.

In PostgreSQL I would run the same report as a join on a replica. In Cassandra the join happens outside the database, because Cassandra itself has no join.

The arithmetic shows why the request path is different. A request-time join with 100 lookups, at 1,000 requests a second, is 100,000 reads a second against the cluster, all day. A nightly Spark job reads each table once.

For fresher results I stream the changes through Kafka (see E17) into a warehouse and join there. The user-facing screen still reads one prepared table.

"Is there a CQL feature that approximates joins?"

No. CQL has no JOIN, no subquery and no GROUP BY across partitions. PostgreSQL has all three, plus CTEs.

The closest tools embed a small child inside the parent row. A set, a map or a user-defined type (UDT, a named group of fields) puts related values in the same row, so one read returns both.

join versus embedruns offline
-- illustrative
-- PostgreSQL: address in its own table, joined at read time
SELECT o.order_id, a.city FROM orders o JOIN addresses a ON a.id = o.address_id;
-- Cassandra: address embedded as a frozen UDT
CREATE TYPE address (street text, city text, pin text);
CREATE TABLE order_snapshots (order_id bigint PRIMARY KEY, deliver_to frozen<address>);

This works for a few values read with the parent, such as tags or an address. A large or shared child stays its own table. Cassandra 6.0 (alpha) previews transactions across partitions, but it does not add joins. Anything wider than an embedded group is solved in the write path, by copying the field into the row, and not in the query. That is the habit change in one line.

Q4. "Explain partition key, clustering column and primary key."

Reveal answer

Strong answer The primary key has two parts. The first part, the partition key, decides which nodes store the row: Cassandra hashes it. All rows with the same partition key sit together as one partition.

The rest are clustering columns. They decide the order of rows inside the partition and make each row unique.

Written as PRIMARY KEY ((a), b, c): a is the partition key, b and c are clustering columns. A query must give a exactly, and may then narrow by b, then c, in that order.

Picture it One partition as a sorted list.

The setup: Messages for conversation 9 in a chat app. Partition key: conversation_id. Clustering: sent_at.

Relational · PostgreSQL

The primary key is only a uniqueness rule.

msg.sqlruns offline
CREATE TABLE messages (
  msg_id bigint PRIMARY KEY,
  conv_id bigint,
  sent_at timestamptz,
  body text);
CREATE INDEX ON messages (conv_id, sent_at);

Cassandra · CQL

The primary key is placement plus order.

msg.cqlruns offline
CREATE TABLE messages (
  conv_id bigint,
  sent_at timeuuid,
  body text,
  PRIMARY KEY ((conv_id), sent_at)
) WITH CLUSTERING ORDER BY
    (sent_at DESC);

The shift: A relational key says which row. A Cassandra key says which machine and which position.

What you see: Rows of conversation 9 inside its partition.

partition conv_id = 9runs offline
# illustrative output
partition key = 9   (hash decides the nodes)
  sent_at 19:05  'on my way'      <- newest first
  sent_at 19:02  'where are you'
  sent_at 18:50  'hi'

Why: Reading the latest 20 messages is reading the top of one sorted list.

Land it I say the partition key picks the machine, the clustering columns pick the order, and together they make the row unique.

Likely follow-ups
"Can I update a primary key column?"

No. In PostgreSQL UPDATE customers SET phone = ... just works, because the row's location does not depend on the key. In Cassandra the key is the row's identity and its address, since the partition key is hashed to pick the machine. A new key means a new place.

So I delete the old row and insert a new one. If two tables carry that key, a logged batch (all statements eventually apply) keeps them together.

changing a keyruns offline
-- illustrative
-- PostgreSQL
UPDATE customers SET phone = '+919811' WHERE customer_id = 1042;
-- Cassandra: phone is the key of customers_by_phone
BEGIN BATCH
  DELETE FROM customers_by_phone WHERE phone = '+919800';
  INSERT INTO customers_by_phone (phone, customer_id) VALUES ('+919811', 1042);
APPLY BATCH;

If the new phone must be unique, I claim it first with IF NOT EXISTS, which costs about four round trips but runs only on a rare event. The profile table, where phone is a normal column, is updated by its own key. The batch makes both halves apply eventually, so no half-done change stays forever, though readers may briefly see one side first.

"Can there be no clustering column?"

Yes. With only a partition key, every partition holds exactly one row. That fits lookups where each key has one answer, such as customers_by_id.

The CQL statement looks the same as PostgreSQL, but it means more. In PostgreSQL the primary key is a unique index. In Cassandra it also decides which machine stores the row.

key-value style tableruns offline
-- illustrative
CREATE TABLE customers_by_id (
  customer_id bigint PRIMARY KEY,   -- partition key only
  name text, phone text);
SELECT * FROM customers_by_id WHERE customer_id = 1042;  -- one partition, one row

It does not fit lists. A list needs several rows under one key, and that needs a clustering column. Static columns are also not allowed here, since a partition with one row has nothing to share.

I use this shape for small entity tables and for lookup tables such as email to customer id. Reading one is the cheapest query Cassandra has, because the key names exactly one partition and that partition holds exactly one row. The price is that nothing else can be asked of this table without another table.

"What does double parentheses mean?"

The inner parentheses mark which columns together form the partition key. PRIMARY KEY ((a, b), c) hashes a and b together as the partition key, with c as the clustering column. Without them, PRIMARY KEY (a, b, c) uses only a as the partition key. PostgreSQL has no such idea, because its composite key is just a multi-column unique index.

The difference decides partition size. Take QuickBite's restaurant orders at 3,000 a day.

one pair versus tworuns offline
-- illustrative
PRIMARY KEY (restaurant_id, day, placed_at)     -- one partition per restaurant
-- 3,000 rows x 365 days = 1,095,000 rows in one partition: too big
PRIMARY KEY ((restaurant_id, day), placed_at)   -- one partition per restaurant per day
-- 3,000 rows each: fine, but a query must give both restaurant_id and day

The cost of the second form is a read rule: every query must now give both restaurant_id and day by equality. A week is then seven parallel queries. When a query is rejected, I check the parentheses first, because a missing pair is the commonest cause. In PostgreSQL the same line would simply create a two-column unique index and place nothing anywhere.

"Why is clustering order fixed at table creation?"

Because the order is part of the physical layout, not a setting that is applied at read time. Cassandra keeps rows sorted by the clustering columns in the memtable (the in-memory buffer), and every flush writes a sorted SSTable file. Changing the order would mean rewriting every file on every node.

PostgreSQL works differently. The table is an unsorted heap, and sorting comes from indexes. So ORDER BY on any column works, and a new index in the other direction is a single statement.

changing the orderruns offline
-- illustrative
-- PostgreSQL: add another sort path later
CREATE INDEX ON orders (customer_id, placed_at ASC);
-- Cassandra: create a new table with the order you want, then backfill
CREATE TABLE orders_oldest_first (...) WITH CLUSTERING ORDER BY (placed_at ASC);

A new table plus backfill is exactly that rewrite, done safely while the old table keeps serving. Cassandra can read a partition backward, so the exact reverse of the declared order is allowed in ORDER BY. Any other order, such as by total, needs its own table. I pick the stored order from the main screen, usually newest first, and treat everything else as another table.

Q5. "What does a partition physically look like, and why does it matter for modelling?"

Reveal answer

Strong answer A partition is all rows sharing one partition key, stored together. On each replica it is written to memtables and SSTable files as one sorted run of rows, so reading it is mostly a sequential read.

It matters because everything that is fast in Cassandra is "read one partition". And everything that is slow is "read many partitions" or "one partition that has grown huge".

So I design for partitions that are neither too many per query nor too large. A rule of thumb: under about 100,000 rows and roughly 100 MB, as a guideline rather than a limit.

Picture it Two partitions with their rows, laid out like an ordered file.

The setup: Two customers in orders_by_customer. Customer 7 has 3 orders, customer 8 has 2.

Relational · PostgreSQL

Rows of one customer are scattered across heap pages.

heap.sqlruns offline
CREATE TABLE orders (
  order_id bigint PRIMARY KEY,
  customer_id bigint,
  total numeric(10,2));
CREATE INDEX ON orders (customer_id);
-- heap pages hold rows in arrival order
-- the index points from customer to pages

Cassandra · CQL

Rows of one customer sit side by side, sorted.

part.cqlruns offline
-- partition 7: o5, o3, o1
-- partition 8: o4, o2
-- one seek, then read forward

The shift: Relational places rows by arrival and finds them by index. Cassandra places rows by key and reads them in order.

Make the invisible visible: Count the work to fetch customer 7's three orders.

read costruns offline
# illustrative output
PostgreSQL: index lookup + up to 3 heap pages (random)
Cassandra : find partition 7, read 3 adjacent rows

Why: That adjacency is why one-partition queries stay fast as data grows.

Land it I say a partition is a sorted bucket of rows, and I keep each bucket small enough to read in one go.

Likely follow-ups
"Where is the partition stored?"

On the replica nodes chosen by hashing the partition key. In PostgreSQL a row sits in one heap page of one primary, and a replica is a copy of the whole database. In Cassandra, each partition has its own set of replicas.

With replication factor 3 on 6 nodes, a partition lives on 3 of the 6, found by the key's position on the hash ring. Every one of the three holds the full partition. The coordinator for a read can be any node. It forwards the read and merges the answers.

where does customer 7 liveruns offline
# illustrative
nodetool getendpoints quickbite orders_by_customer 7
10.0.0.2
10.0.0.4
10.0.0.5          # three replicas, RF 3
# a LOCAL_QUORUM read waits for 2 of these 3

The command getendpoints is a handy way to check where a key lives when debugging. It also explains a surprise: two keys in the same table can sit on completely different nodes, so one query for both is really two reads on two replica sets, not one.

"Can a partition span nodes?"

No. A partition is never split across nodes, and that is a deliberate trade. A read stays on one replica set, but a very large partition cannot be shared out.

PostgreSQL has a related idea, declarative partitioning, but it splits a table into child tables on the same server, or across servers only with extensions such as Citus. Cassandra's partition is the unit of placement itself.

The effect shows in a simple case. If one conversation has 5 million rows at about 90 bytes each, that is roughly 450 MB, and all of it sits on the same three replicas. Adding 20 nodes does not move one byte of it.

Every read, repair and compaction of that partition lands on those three machines, which then become a hot spot.

So growth must be bounded inside the key, before the data exists. A bucket in the partition key is the usual tool.

"How big is too big?"

Common guidance is under about 100 MB and about 100,000 rows per partition. Past that, reads slow down, compaction and repair get heavier, and memory pressure rises. It is a guideline, not a hard limit. The hard limit is about 2 billion cells per partition, which no sane design reaches.

Some teams run fine at 200 MB and others struggle at 50 MB, depending on row shape and workload. So I treat the number as a budget and size the worst partition, not the average one.

budget checkruns offline
# illustrative: assumptions are 90 bytes per row, growth 2x a year
600,000 rows x 90 B = 54 MB     -> ok today, but over 100,000 rows
doubling next year  = 108 MB    -> add a bucket now

Notice that this example fails on rows before it fails on megabytes. Either limit is a reason to add a bucket. I then confirm with nodetool tablehistograms on real data, looking at the maximum and the 99th percentile together, since one giant partition hides behind a healthy average.

"How do I limit growth?"

Add a bucket to the partition key, so each partition covers a bounded slice such as a day. PostgreSQL never needs this, because one table can grow and indexes grow with it. In Cassandra it must be in the key from the start, since adding it later means a new table and a backfill.

I choose the bucket from the write rate. Take QuickBite's rider pings, one every 5 seconds, about 50 bytes each.

pick the bucketruns offline
# illustrative arithmetic
86,400 s per day / 5 s = 17,280 pings per rider per day
17,280 x 50 B = about 0.86 MB per partition
PRIMARY KEY ((rider_id, day), at)   # fine; a month would be about 26 MB

I pair the bucket with a read plan: newest bucket first, then step back one bucket at a time. For a hot key, a shard number (0 to 15) in the key is the other tool, at the price of 16 reads. Either way, the rule is to decide the bound while designing, and to check it against the busiest key, not the typical one. A table with a seven-day TTL, like the rider track, also stays small by expiry.

Drill · Keys as address and order

These questions test whether you can read a key as placement plus order.

Q6 · Scenario. "Why can't I just add an index on the column I want to query?"

Reveal answer

Strong answer You can, but you must know what it buys. A classic secondary index stores, on each node, a map from value to the local rows. When the query has no partition key, the coordinator must ask every node.

That is fine for a rare admin query. It is not fine for a hot path. Cost grows with the number of nodes, and low- or high-cardinality columns make it worse.

Cassandra 5.0 adds Storage-Attached Indexes (SAI), which are far better, but they are still an extra lookup path rather than a table built for the question. For hot reads I build a table.

Picture it Find customers by city: an index versus a table.

The setup: One million customers across 50 cities, on a 12-node cluster.

Relational · PostgreSQL

An index. The planner chooses it.

idx.sqlruns offline
CREATE INDEX ON customers (city);
SELECT * FROM customers
WHERE city = 'Pune';

Cassandra · CQL

A query-shaped table. One partition per city.

bycity.cqlruns offline
CREATE TABLE customers_by_city (
  city text, customer_id bigint,
  name text,
  PRIMARY KEY ((city), customer_id));
SELECT * FROM customers_by_city
WHERE city = 'Pune' LIMIT 100;

The shift: The index finds rows after the fact. The table puts them in the right place at write time.

What you see: How many nodes each read touches.

fan-outruns offline
# illustrative output
secondary index, no partition key: 12 of 12 nodes asked
table by city (RF 3, LOCAL_ONE)  : 1 node asked
-- a city with 400k customers needs paging or a bucket

Why: The index spreads each query over the cluster. The table sends it to one spot.

Land it I say an index is fine for cold queries, but for hot queries I build a table so the read hits one partition.

Likely follow-ups
"When are secondary indexes acceptable?"

When the query also names the partition key, so the index only searches inside one partition, or when the query is rare and the table is small. Otherwise the cost grows with the cluster.

In PostgreSQL an index is one structure on one machine, so adding a column index is almost always a good idea. In Cassandra a classic index is stored per node, so a query without a partition key must visit nodes covering the whole ring. Roughly that is the cluster size divided by the replication factor.

fan-out per secondruns offline
# illustrative: 12 nodes, RF 3, so about 4 replica groups cover the ring
index, no partition key: 100 req/s x 4 groups = 400 node-queries/s
lookup table by key    : 100 req/s x 1 group  = 100 reads/s

Double the cluster and the first line grows while the second stays flat. So I use an index for admin screens and one-off checks, and a table for anything users wait on.

"Is SAI different?"

Yes, it is a better design, but it is not a different kind of tool. SAI (Storage-Attached Indexing, new in Cassandra 5.0) keeps its index files with the data on each node and follows the SSTable life cycle, so it is cheaper to write and to keep than the old index. It supports equality, ranges and combined conditions, which the old index could not do well. It also lets one query combine two indexed columns, where the old index handled one at a time.

SAI with and without the keyruns offline
-- illustrative
CREATE INDEX ON orders_by_customer (total) USING 'sai';
-- searches inside one partition: good
SELECT * FROM orders_by_customer WHERE customer_id = 7 AND total > 20;
-- no partition key: still visits the nodes that may hold matches
SELECT * FROM orders_by_customer WHERE total > 500;

PostgreSQL's B-tree is one local index, so the second query is cheap there. In Cassandra the second query is still a scatter across nodes. I use SAI for light or internal use, and I measure it on a realistic cluster first.

"What about low-cardinality columns like status?"

A low-cardinality column (few distinct values, like a status with 3 values) is a poor index in Cassandra. Each value points to a huge share of the table, so a query returns far too much.

The arithmetic makes it concrete. With 40 million orders and 3 statuses, each status covers about 13.3 million rows (40,000,000 / 3). Asking for one status means paging through millions of rows from every node.

The opposite extreme, a unique column like email, makes each entry tiny, but the query still asks many nodes. Both ends cost something.

PostgreSQL treats this more gently. Its planner may skip an index on a low-selectivity column and scan instead, or you can build a partial index on just the rare value, such as WHERE status = 'NEW'.

In Cassandra the good case for an index is a mid-range column queried together with the partition key.

"What about materialized views?"

They are marked experimental, disabled by default and not recommended for production in 5.0, so I keep the second table myself.

The word "view" means different things in the two databases. In PostgreSQL a materialized view is a stored snapshot that you refresh on demand. In Cassandra it was meant to be a second table that the database keeps in step on every write, which is a much harder promise.

view versus hand-built tableruns offline
-- illustrative
-- PostgreSQL: snapshot, refreshed when you say so
REFRESH MATERIALIZED VIEW orders_by_day;
-- Cassandra: I write the second table myself, in the same batch
BEGIN BATCH
  INSERT INTO orders_by_customer (...) VALUES (...);
  INSERT INTO orders_by_restaurant_day (...) VALUES (...);
APPLY BATCH;

The project has hit consistency and repair problems with views. A hand-built table costs more code, but I know exactly when it is written and what a failure leaves stale. It also uses the same batch and repair tools as every other copy, so there is one mechanism to learn and monitor, and not two.

Q7. "What does ALLOW FILTERING do, and when is it acceptable?"

Reveal answer

Strong answer ALLOW FILTERING tells Cassandra: run this query even though it cannot use the primary key, and discard rows that do not match. It does not make the query efficient. It removes the safety check.

Cassandra refuses such queries by default because the cost depends on the data size, not on the result size. A query returning 3 rows might read 3 million.

It is acceptable when the partition key is fixed and the filter runs inside one small partition, or in a one-off script on a small table. It is not acceptable on a request path.

Picture it The same query, rejected and then allowed.

The setup: Orders table keyed by customer. Someone wants orders above 500.

Relational · PostgreSQL

A WHERE on any column is legal. The planner scans or uses an index.

pg.sqlruns offline
SELECT * FROM orders
WHERE total > 500;

Cassandra · CQL

Cassandra stops you unless you override.

cql.cqlruns offline
SELECT * FROM orders_by_customer
WHERE total > 500;
-- InvalidRequest: ... might involve data
-- filtering ... use ALLOW FILTERING

The shift: Relational lets any query run slowly. Cassandra makes a slow query ask for permission.

What you see: What filtering costs.

filtering at scaleruns offline
# illustrative output
rows read: 400,000,000   rows returned: 31
time: 38 s   result: ReadTimeout

Why: Work grows with table size, which breaks the promise of predictable reads.

Land it I say ALLOW FILTERING is a warning label, not a feature, and I only use it inside a single partition I know is small.

Likely follow-ups
"What does the error look like?"

It tells you the query "might involve data filtering and thus may have unpredictable performance" and suggests adding ALLOW FILTERING. The exact wording differs between versions, so I look for the error code and the phrase "data filtering". The same message covers a missing partition key, a skipped clustering column and a filter on a normal column.

The error is a protection. PostgreSQL would just run the same statement and scan. Cassandra refuses, because the time it takes depends on the table size and not on the result size, and it cannot know that before it starts.

what you see in cqlshruns offline
# illustrative output
InvalidRequest: Error from server: code=2200
 Cannot execute this query as it might involve data filtering and thus may have
 unpredictable performance. If you want to execute this query despite the
 performance unpredictability, use ALLOW FILTERING

My habit is to treat the message as a design review comment: the table's key does not match this question. The fix is nearly always a different table, and not the flag. The flag only silences the check. A teammate who adds it to make a red query go green has moved the failure from the developer's laptop to production, where the table is large.

"How would you fix the totals query?"

First I ask which screen needs "orders with a total over X". If it is a list of big orders for a restaurant, I build a table where total is a clustering column, so a range on total is a true seek. PostgreSQL would do the same with an index on total and a WHERE total > 500.

big orders tableruns offline
-- illustrative
CREATE TABLE big_orders_by_restaurant_day (
  restaurant_id bigint, day date,
  total decimal, order_id bigint,
  PRIMARY KEY ((restaurant_id, day), total, order_id)
) WITH CLUSTERING ORDER BY (total DESC, order_id ASC);
-- top 20 of the day: reads the first 20 rows of one partition
SELECT * FROM big_orders_by_restaurant_day WHERE restaurant_id = 12 AND day = '2026-11-25' LIMIT 20;

An order's total does not change after it is placed, so total in the key is safe. Descending order means the biggest orders come first, so the top of the partition is the cheapest part to read. If it changed, every update would be a delete plus an insert. For general reporting, such as sums by week, I send the data to a warehouse.

"Can I use it with a partition key?"

Yes, and that is the safest use. Once the query gives the full partition key, the filter runs only on the rows of that one partition. The cost is bounded by the partition size, not by the table size.

PostgreSQL does the equivalent when it uses an index on customer_id and then checks the other conditions on the matching rows. In Cassandra I make that bound explicit by keeping partitions small.

bounded filteringruns offline
-- illustrative
SELECT * FROM orders_by_customer
WHERE customer_id = 7 AND total > 20 ALLOW FILTERING;
-- worst case: reads one customer's rows, say 3,000, on one replica set

Three thousand rows are fine for an occasional screen. The same line is not fine if the partition could grow to millions of rows, because the worst case grows with it. Across many partitions, the cost is the whole table.

So I allow it for small, capped partitions and ban it on request paths where the partition is unbounded. A partition capped by a day bucket or a TTL is the typical safe case, because its size has a ceiling I can write down.

"Does it work with LIMIT?"

LIMIT stops the scan once enough matches are found, so its cost depends on how common the match is. A common value is fast and a rare value reads the whole table. That unpredictability is exactly what the safety check protects against.

In PostgreSQL the planner estimates how common a value is from statistics and picks a plan. Cassandra keeps no such statistics for this, so it cannot warn you.

two filters, same LIMITruns offline
# illustrative
common value: LIMIT 20 -> first 20 matches after about 40 rows read      fast
rare value  : LIMIT 20 -> only 3 matches exist, so all 400,000,000 rows read   timeout

The second case never reaches 20, so LIMIT never gets the chance to stop it. And the test data usually contains the common value, which is why this passes testing.

My rule is that a limit does not make a filter safe. A table keyed for the question does. A rare value also means a growing table makes the same query slower every month, with no change in code, which is a hard fault to trace later.

Q8 · Design. "Here is our PostgreSQL schema for orders. Model it in Cassandra."

Reveal answer

Strong answer I do not start from the tables. I start from the screens and write the questions. For QuickBite: Q1 orders of one customer, newest first; Q2 one order with its items; Q3 live orders of a restaurant today.

Then I make one table per question. The partition key is what the query always knows. The clustering columns give the order the screen wants. Everything the screen shows is copied into the row.

Last I check partition size and the write cost: one order is written into each table, so 3 tables mean 3 writes, applied together in a logged batch.

Picture it The schema on the left, three query tables on the right.

The setup: PostgreSQL has customers, restaurants, orders and order_items with foreign keys.

Relational · PostgreSQL

Four normalised tables, joined per request.

orders.sqlruns offline
CREATE TABLE orders (
  order_id bigint PRIMARY KEY,
  customer_id bigint REFERENCES customers,
  restaurant_id bigint REFERENCES restaurants,
  placed_at timestamptz,
  total numeric(10,2));
CREATE TABLE order_items (
  order_id bigint REFERENCES orders,
  item_id bigint, qty int,
  PRIMARY KEY (order_id, item_id));

Cassandra · CQL

Three tables, one per screen.

orders.cqlruns offline
orders_by_customer
  ((customer_id), placed_at, order_id)
orders_by_id
  ((order_id), item_id)
orders_by_restaurant_day
  ((restaurant_id, day), placed_at,
   order_id)

The shift: Tables follow screens, not entities.

Make the invisible visible: Placing one order writes it once per table.

one order, three writesruns offline
BEGIN BATCH
 INSERT INTO orders_by_customer (customer_id, placed_at, order_id, restaurant_name, total) VALUES (7, toTimestamp(now()), 42, 'Spice Hut', 18.50);
 INSERT INTO orders_by_id (order_id, item_id, name, qty) VALUES (42, 1, 'Paneer', 2);
 INSERT INTO orders_by_restaurant_day (restaurant_id, day, placed_at, order_id, total) VALUES (12, '2026-11-23', toTimestamp(now()), 42, 18.50);
APPLY BATCH;

Why: The batch keeps the three copies in step. Each read afterwards is one partition.

Land it I turn the screens into a query list, build one table per query, and write each order into all of them with a logged batch.

Likely follow-ups
"Why not keep order_items as a separate table?"

I do keep an items table, but it is keyed by order and holds the items as clustering rows under the order's own partition. It is the answer to "one order with its items". The list tables, such as orders_by_customer, hold only the summary a list screen shows, such as total, status and restaurant name, but not the items. A list of 20 orders then reads 20 small rows and not 20 orders with all their items.

header and lines togetherruns offline
-- illustrative
-- PostgreSQL: two tables, joined
SELECT * FROM orders o JOIN order_items i ON i.order_id = o.id WHERE o.id = 42;
-- Cassandra: one partition; header fields are STATIC, items are rows
CREATE TABLE orders_by_id (
  order_id bigint, line_no int,
  restaurant_name text STATIC, total decimal STATIC,
  item_name text, qty int, price decimal,
  PRIMARY KEY (order_id, line_no));
SELECT * FROM orders_by_id WHERE order_id = 42;

The order id is the partition key, so all lines sit together and sorted by line number, and a single read gets them all. So the same order exists in three shapes: full detail by id, and two summaries. The join is gone because the header and the lines were stored together, and one read of one partition returns the whole order.

"What about the customers and restaurants tables?"

They stay as small entity tables keyed by id, such as customers_by_id and menu_by_restaurant. They are the source of names and prices when an order is placed. They are not joined at read time.

  1. Read: the app fetches the customer by id and the restaurant's menu entry by id. Each is a single-partition read, usually served from an application cache.
  2. Copy: it puts the display fields, such as names and prices, into the order rows.
  3. Write: it writes all the order tables in one logged batch.

There are no foreign keys in Cassandra, so the app checks that the customer exists, where PostgreSQL would reject a bad reference by itself. Later edits to the entity table do not rewrite old orders, which is the behaviour I want for history. A read by primary key is the cheapest read there is, so the extra lookup adds almost nothing to the write path.

"How do you decide what goes in each copy?"

I copy only the fields that screen displays or sorts by. A column nobody reads is wasted space on every copy, and fewer columns make cheaper writes and smaller partitions.

My method is to take one screen and underline every value on it. Each underlined value must come from the row that the screen reads, or from a cheap key lookup. In PostgreSQL I would instead write one wide SELECT with joins and let the planner gather the fields.

column budgetruns offline
# illustrative: 8 shown values plus 3 key columns, about 100 B per row
40,000,000 orders x 100 B = 4,000,000,000 B = 4 GB per table
x 3 replicas (RF 3)       = 12 GB on disk across the cluster

Drop one 20-byte field that nobody shows and the saving is 800 MB per copy before replication (40,000,000 x 20 B). That is small but free, and it repeats for every table that carries the field. Across three order tables it is 2.4 GB saved, and the same field also costs bandwidth on every read.

"What if a table is missing a query we forgot?"

Then I add a new table and backfill it from existing data. Adding a table is the normal way a Cassandra model grows. It is the equivalent of adding an index and writing a new SELECT in PostgreSQL, only with more steps.

  1. Design: write the new query in the access-pattern list and choose its key.
  2. Create and write: create the table, and make the application write to it for new orders.
  3. Backfill: copy old rows from the master table with a throttled job.
  4. Switch: point the new screen at the table, perhaps behind a feature flag.

Nothing about the old tables changes, so the risk is low. The expensive mistake is not the forgotten query. It is the forgotten query served by ALLOW FILTERING because nobody wanted to build a table, which turns up later as a timeout.

Q9. "Cassandra duplicates data across tables. Isn't that bad design?"

Reveal answer

Strong answer In a relational design duplication is a bug: two copies can disagree. In Cassandra it is the design: each copy is a different view of the same facts, built for one query.

The reasons are cost and speed. Disk is cheap, writes are fast, and a read that touches one partition is far cheaper than a join across many.

What I must do is stay disciplined. Decide which table is the source of truth, write every copy together, and accept that a failure can leave copies briefly out of step.

Picture it One order, three copies, and what keeps them honest.

The setup: Order 42 is stored in orders_by_customer and orders_by_restaurant_day.

Relational · PostgreSQL

Store the fact once. Views are queries.

view.sqlruns offline
CREATE VIEW recent AS
SELECT customer_id, order_id, total
FROM orders;
-- one copy, derived at query time

Cassandra · CQL

Store the fact in every shape needed.

copies.cqlruns offline
INSERT INTO orders_by_customer ... ;
INSERT INTO orders_by_restaurant_day ... ;
-- same facts, two layouts, written together

The shift: A relational designer protects against duplicates. A Cassandra designer plans them.

What you see: The cost of duplicating.

storage math (illustrative)runs offline
40M orders x 200 bytes      = 8 GB per table
3 tables                    = 24 GB
replication factor 3        = 72 GB across the cluster

Why: 72 GB is trivial next to the read speed gained.

Land it I say duplication is intentional in Cassandra because each copy serves one query, and I control it by writing all copies together.

Likely follow-ups
"What if one copy fails to write?"

A logged batch is the first defence. Before it touches the tables, the coordinator stores the batch in a batch log on other nodes. If the coordinator dies halfway, those nodes replay the batch, so all its statements eventually apply.

That is weaker than a PostgreSQL transaction, which is all-or-nothing and isolated. A Cassandra batch is atomic in the sense of "eventually all", but not isolated: a reader may see one table updated before another.

same job, two databasesruns offline
-- illustrative
-- PostgreSQL: one transaction, readers see all or nothing
BEGIN; INSERT INTO orders (...) VALUES (...); COMMIT;
-- Cassandra: copies written together, eventually all apply
BEGIN BATCH
  INSERT INTO orders_by_customer (...) VALUES (...);
  INSERT INTO orders_by_restaurant_day (...) VALUES (...);
APPLY BATCH;

The second defence is a repair job that scans the master table and rewrites the copies. Because writes are upserts, it is safe to repeat. Together the two leave short windows of disagreement, such as a few seconds, and never permanent ones. I design screens to tolerate that window, for example by reading the master table right after a write.

"How do updates work with copies?"

I update each copy by its full key, so I must be able to compute the key of every copy from data I hold. In PostgreSQL one UPDATE ... WHERE id = 42 changes the only copy. In Cassandra the same business change is several updates.

For orders_by_customer the key is the customer id, the placed time and the order id. If the app only has the order id, it first reads the master row to learn the rest.

find the keys, then update each copyruns offline
-- illustrative
SELECT customer_id, placed_at, restaurant_id, day FROM orders_by_id WHERE order_id = 42;
BEGIN BATCH
  UPDATE orders_by_customer SET status = 'DELIVERED'
    WHERE customer_id = 7 AND placed_at = '2026-11-25 12:00:00+0000' AND order_id = 42;
  UPDATE orders_by_restaurant_day SET status = 'DELIVERED'
    WHERE restaurant_id = 12 AND day = '2026-11-25' AND placed_at = '2026-11-25 12:00:00+0000' AND order_id = 42;
APPLY BATCH;

That is why I store every key column on the master row, even when the screen does not show it. Without them I cannot rebuild the keys of the copies, and a copy that cannot be found cannot be updated or deleted. If the keys cannot be derived, the copy becomes stale forever.

"Does it make writes slow?"

Each write is a fast append, so N copies cost about N times the write work. I count that in capacity planning. PostgreSQL also pays for extra structures, because each index on a table is another write, but there the extra writes are hidden inside one statement.

A Cassandra write goes to the commit log and the in-memory memtable. There is no read-before-write and no lock, so it is cheap and it scales with nodes.

planning arithmeticruns offline
# illustrative: assume the cluster can do 50,000 row writes per second
3 tables per order  -> 50,000 / 3 = about 16,700 orders per second
at 400 orders/s the load is 1,200 row writes/s, about 2.4% of capacity

The numbers are a planning estimate, not a promise, so I load test with real row sizes. Disk and compaction work also grow with the number of copies. For most apps the write side is the cheap side, which is the reason for moving work from reads to writes.

"When do I avoid copying?"

I avoid copying when the data changes very often and nobody reads the extra copies. The standard example is a rider's live position. It changes every few seconds, and the app reads it by key.

Many copies would mean many writes per ping with no reader for most of them. So I keep one latest-value table and a separate append-only history table.

latest value and historyruns offline
-- illustrative
CREATE TABLE rider_latest (rider_id bigint PRIMARY KEY, lat double, lon double, at timestamp);
CREATE TABLE rider_track (rider_id bigint, day date, at timestamp, lat double, lon double,
  PRIMARY KEY ((rider_id, day), at))
  WITH default_time_to_live = 604800;  -- 7 days

Each ping overwrites rider_latest and appends one row to rider_track. In PostgreSQL I might keep only one table and use an index. In Cassandra the two tables match the two questions: where is the rider now, and where was the rider.

The rule is to copy data that is read often and changes rarely. Data that changes constantly gets one home, read by key, and an append-only history if anyone needs the past. This also keeps the number of writes per ping at two, whatever the number of screens.

Q10. "Walk me through the Cassandra data modelling method."

Reveal answer

Strong answer I follow four steps, often called the Chebotko method. 1. Conceptual model: draw the entities and relationships, as an ERD. 2. Workflow and access patterns: list every screen or API call and the queries it needs. 3. Logical model: for each query, draw one table with its partition key, clustering columns and columns. 4. Physical model: choose types, estimate partition size, add buckets, tune.

The key is the second step. It has no equivalent in relational design, where the planner copes with whatever arrives. In Cassandra, missing a query means missing a table.

Picture it The four steps applied to one feature.

The setup: Feature: order tracking for a customer.

Relational · PostgreSQL

ERD, then normal forms, then indexes for queries.

steps.sqlruns offline
CREATE TABLE orders (
  order_id bigint PRIMARY KEY,
  total numeric(10,2));
CREATE TABLE order_events (
  order_id bigint REFERENCES orders,
  at timestamptz, status text);
-- later, per slow query:
CREATE INDEX ON order_events (order_id, at);

Cassandra · CQL

ERD, then queries, then one table each.

steps.cqlruns offline
1 entities: order, event
2 Q1: events of order 42, in time
3 table events_by_order
  ((order_id), at)
4 sizes, TTL, buckets

The shift: Relational closes with indexes. Cassandra opens with queries.

Make the invisible visible: The finished table for step 3.

events_by_order.cqlruns offline
CREATE TABLE events_by_order (
  order_id bigint,
  at timestamp,
  status text,
  PRIMARY KEY ((order_id), at)
) WITH CLUSTERING ORDER BY (at ASC);

Why: The query list drove the key: partition by order, sorted by time.

Land it I say entities first, then the access patterns, then one table per access pattern, then sizes and buckets.

Likely follow-ups
"Why start with a conceptual model at all?"

It makes sure I know the entities and their relations before I start copying data around. The access patterns then refer to those entities, and the table keys follow from the relation types.

In PostgreSQL the diagram also comes first, but it goes straight to tables. In Cassandra it is the stepping stone to the query list.

relations to keysruns offline
-- illustrative
customer   1 --- N  order      -> orders_by_customer: partition key customer_id
restaurant 1 --- N  order      -> orders_by_restaurant_day: partition key restaurant + day
order      1 --- N  order event -> order_events_by_order: partition key order_id
order      N --- M  menu item  -> lines stored as rows inside the order partition

Without the model I cannot see that an order has many events and exactly one customer, so I cannot see the keys, and I would only find the mistake when a screen cannot be built. It also lets me phrase the access patterns exactly, such as "given a customer, list orders", which is a sentence that maps straight to a partition key. Without it, requirements stay vague, and tables are shaped by guesses.

"What goes in an access-pattern list?"

For each query I write down six things: the screen name, what is known as input, what comes back, the sort order, the expected rate, and the expected result size. PostgreSQL design has no such list, because the planner copes with whatever arrives. In Cassandra the list is the main design input.

access-pattern listruns offline
-- illustrative
Q1 my orders       in: customer_id       out: 20 orders       sort: newest first  rate: 300/s
Q2 order detail    in: order_id          out: header + items                      rate: 400/s
Q3 restaurant day  in: restaurant + day  out: up to 3,000 orders sort: placed_at  rate: 40/s

The rate and the result size drive the later choices. A high rate says the read must hit one partition. A large result says I should bucket or page. Sort order becomes the clustering order. The input becomes the partition key.

The numbers are estimates, and I would rather write a rough number than leave the column empty. A guess of 300 a second that turns out to be 600 is still the right order of magnitude, and it changes no key.

"What is a Chebotko diagram?"

It is a diagram where each table is drawn as a box, so that anyone can check a query against a table in seconds. It is named after Artem Chebotko, who described the method.

In each box the title is the table name. Partition-key columns are marked K, clustering columns are marked C with an up or down arrow for the sort order, and the other columns are listed plain. Queries are drawn as arrows above the boxes, pointing to the table that answers them.

one Chebotko boxruns offline
-- illustrative
Q1 my orders --> orders_by_customer
  K  customer_id
  C  placed_at    (down)
  C  order_id
     restaurant_name, total, status

In PostgreSQL the nearest tool is an ER diagram, but that shows entities and links, not queries. The Chebotko diagram shows queries, and that is why a reviewer can spot a query with no table, or a table with no query, at a glance. I draw it by hand in the interview.

"How do you validate the model?"

I validate in three passes, and a diagram alone is not enough.

  1. Key shape: for each query, does the WHERE give the full partition key and only a prefix of the clustering columns, with a range on the last one only?
  2. Sizes: rows times bytes per row for the busiest partition. I aim under about 100 MB and 100,000 rows.
  3. Write cost: how many tables each business event touches. One order into 3 tables at 400 orders a second is 1,200 row writes a second.

PostgreSQL gives a shortcut here, EXPLAIN, which shows whether a query uses an index. Cassandra has none, so the check is partly by hand.

The last step is a load test using the real driver code with realistic data, because a diagram cannot show timeouts or hot partitions. I also turn on tracing for each query once, to confirm that it touches one replica set.

Drill · Keys, WHERE and partition size

These questions test whether you can read a key as an access rule and size a partition before it grows.

Q11. "What are the rules of the WHERE clause in CQL?"

Reveal answer

Strong answer Three rules. One: every partition-key column must be restricted with = (or IN). Two: clustering columns can be restricted only as a left-to-right prefix: equality on the first ones, and a range on at most the last one you restrict. Three: everything else needs an index or ALLOW FILTERING.

The reason is physical. The partition key finds the node. The clustering order lets Cassandra jump into the sorted run and read forward. A skipped column breaks the sorted run, so the engine cannot jump.

Picture it A table with three clustering columns and which queries it accepts.

The setup: Table readings keyed by ((sensor_id), day, hour, minute).

Relational · PostgreSQL

Any column combination is allowed. The planner picks.

pg.sqlruns offline
SELECT * FROM readings
WHERE hour = 14
  AND sensor_id = 5;

Cassandra · CQL

Only a key prefix is allowed.

cql.cqlruns offline
-- ✅ sensor, day
-- ✅ sensor, day, hour>=14
-- ❌ sensor, hour = 14   (skips day)
-- ❌ day only            (no sensor)

The shift: Relational asks which columns are filtered. Cassandra asks which prefix of the key you can give.

What you see: Why skipping a column fails.

sorted runruns offline
# illustrative output
sensor 5: day1 h09 | day1 h14 | day2 h03 | day2 h14
hour = 14 is not contiguous: rows are spread through
the partition, so a scan would be needed

Why: Sorted order only helps if you walk the key from the left.

Land it I say give the whole partition key, then a prefix of the clustering columns, with a range only on the last one.

Likely follow-ups
"Is IN allowed?"

On a partition key, yes, but it works differently from PostgreSQL. In PostgreSQL IN (1, 2, 3) is one index scan on one machine, and a list of thousands is fine. In Cassandra, IN on the partition key runs one read per value, and the coordinator holds all the partial answers in memory until the slowest replica replies.

A list of 3 or 4 values is fine. A list of 500 turns one request into 500 reads and makes the slowest node set the speed of the whole request.

IN versus parallel readsruns offline
-- illustrative
-- fine for a short list
SELECT * FROM orders_by_customer WHERE customer_id IN (7, 8, 9);
-- better for a long list: one query per id, sent by the driver in parallel

With one query per id the driver can send each read straight to a replica of that key, so no single coordinator is stuck holding everything. I keep IN short and use parallel queries beyond a dozen or so.

"Can I use a range on the partition key?"

Only through token(), and that is for scanning jobs, not for requests. PostgreSQL stores keys in a B-tree order, so WHERE id > 100 is natural. In Cassandra the partition key is hashed, so customer 7 and customer 8 sit on unrelated nodes and a range of ids means nothing.

token() lets a job walk the whole ring in pieces, for example to rebuild a copy or export data. It returns rows in hash order, not in any order a user would care about.

scanning by token rangeruns offline
-- illustrative
SELECT * FROM orders_by_customer
WHERE token(customer_id) > -9223372036854775808
  AND token(customer_id) <= -9000000000000000000;

Spark and export tools split the ring into many such ranges and read them in parallel, each range going to the node that owns it. I use token() for jobs, never for screens, because the result order is meaningless to a user and the scan touches every node over time.

"What about two ranges on two clustering columns?"

Not allowed. Only the last restricted clustering column can have a range, and the reason is physical. Rows in a partition are sorted by the clustering columns in order, so a restriction on the prefix names one contiguous block of rows. A range on an early column followed by a condition on a later one would need several separate blocks.

With key ((sensor), day, hour, minute) and day fixed, hour from 8 to 10 is one block. Adding minute >= 30 means the second half of hour 8, the second half of hour 9 and the second half of hour 10, which are three separate pieces.

legal and illegalruns offline
-- illustrative
-- ok: day equal, range on hour
WHERE sensor = 5 AND day = '2026-11-23' AND hour >= 8 AND hour <= 10;
-- refused: a second range on minute
WHERE sensor = 5 AND day = '2026-11-23' AND hour >= 8 AND minute >= 30;

PostgreSQL would accept the second query and filter the rest. Cassandra asks me to change the table.

"Does the error tell me which rule broke?"

It tells me the query would need data filtering, but it does not always name the exact rule that was broken, and the wording varies by version. Some cases do give a clearer hint, such as a message saying a clustering column cannot be restricted because an earlier one is not. So I go through a short checklist instead of trusting the text.

  1. Partition key: is every partition-key column given by equality (or IN)? A missing one is the commonest cause.
  2. Clustering prefix: are the restricted clustering columns a left-to-right prefix, with no gaps?
  3. One range: is there at most one range, and is it on the last restricted column?

PostgreSQL never rejects a query for its shape, so people used to it find these errors odd at first.

Nine times out of ten the fix is to change the table, not the query. The remaining case is a normal column in the filter, where the choices are a new table, SAI, or a small partition with filtering.

Q12. "How do you control sort order in Cassandra? Can I ORDER BY any column?"

Reveal answer

Strong answer No. Rows inside a partition are sorted by the clustering columns, and ORDER BY can only use those, in the declared order or its exact reverse. The order is chosen when the table is created with CLUSTERING ORDER BY.

There is no sort across partitions. Results from different partitions come in token order, which is arbitrary for the application.

If a screen needs another order, it needs another table, with a different clustering order.

Picture it Newest-first orders versus an order by price.

The setup: A customer's orders sorted by time, and the wish to sort them by total.

Relational · PostgreSQL

ORDER BY any column. A sort node does it.

sort.sqlruns offline
SELECT * FROM orders
WHERE customer_id = 7
ORDER BY total DESC;

Cassandra · CQL

ORDER BY only follows the clustering columns.

sort.cqlruns offline
CREATE TABLE orders_by_total (
  customer_id bigint, total decimal,
  order_id bigint,
  PRIMARY KEY ((customer_id), total,
               order_id))
WITH CLUSTERING ORDER BY
  (total DESC, order_id ASC);

The shift: Sorting is a query-time step in SQL and a storage-time choice in Cassandra.

What you see: What the rejected query says.

rejected ORDER BYruns offline
# illustrative output
ORDER BY total on orders_by_customer
InvalidRequest: Order by is currently only supported
on the clustered columns of the PRIMARY KEY

Why: The table stores rows by time. Sorting by total would mean reading the whole partition and sorting it, which Cassandra will not do on the server.

Land it I say sort order is decided by the clustering columns when the table is created, so a new sort order means a new table.

Likely follow-ups
"Can I reverse the order at query time?"

Yes, but only the exact reverse of the stored order. Because rows on disk are already sorted, Cassandra can walk the partition from its end instead of its start. PostgreSQL does the same with a B-tree, which can be scanned in either direction, and it also lets you sort by any other column.

both directions on one tableruns offline
-- illustrative: msgs is stored with CLUSTERING ORDER BY (sent_at DESC)
SELECT * FROM msgs WHERE conv_id = 9 ORDER BY sent_at DESC LIMIT 20;  -- stored order
SELECT * FROM msgs WHERE conv_id = 9 ORDER BY sent_at ASC  LIMIT 20;  -- exact reverse: allowed
SELECT * FROM msgs WHERE conv_id = 9 ORDER BY author;                 -- refused

A reverse read can be somewhat slower on large partitions, because the engine is optimised for forward reads. I would measure that on real data before relying on it.

So I still store the order that matches the main screen. The reverse is a convenience for the occasional other view, such as an admin looking at the oldest messages first. A list that needs an order other than the stored order or its exact reverse needs its own table, and nothing in ORDER BY can change that.

"Which order should I pick?"

The order the main screen needs. The cheapest place to read in a partition is its head, so the screen's rows should be there. Newest first is the common choice for feeds, orders and messages, because users look at the latest rows.

In PostgreSQL the order is a property of a query and its index, so there is no early commitment. In Cassandra I commit when I create the table.

stored orderruns offline
-- illustrative
CREATE TABLE orders_by_customer (
  customer_id bigint, placed_at timestamp, order_id bigint, total decimal,
  PRIMARY KEY ((customer_id), placed_at, order_id)
) WITH CLUSTERING ORDER BY (placed_at DESC, order_id ASC);
-- "my 20 latest orders" reads the first 20 rows of one partition

A log viewer used for investigations might want oldest first instead, and a leaderboard might want the highest score first. I decide by asking what the first screen shows, and I do not choose by habit. The common mistake is to copy the order of the SQL ORDER BY from the old schema without checking whether the screen still needs it.

"Can I sort in the application?"

For a few dozen rows, yes. Sorting 20 orders in Java takes microseconds. It becomes a trap when the client must fetch many rows only to sort them, because the fetch is the costly part, and not the sort.

Take a customer whose partition holds 100,000 orders. To show the latest 20 by sorting in the app, the client would read all of them.

cost of sorting in the appruns offline
# illustrative: assume 90 bytes per row and 50 requests per second
100,000 rows x 90 B = 9,000,000 B = 9 MB per request
9 MB x 50 req/s     = 450 MB/s of traffic, to show 20 rows

PostgreSQL can sort inside the database, and with an index on the sort column it reads only the 20 rows it needs. Cassandra gives the same effect only when the clustering order matches the screen.

If the list is long or paged, the table should keep it sorted. Cassandra can then hand back the first page and a paging state (a bookmark for the next page) without sorting anything. That is the case where sorting in the app is the wrong layer, and the key is the right one.

"What is the sort within equal values?"

Ties are broken by the next clustering column. Clustering columns together with the partition key make the row's unique key, so there must always be a way to tell two rows apart.

That is why a time column is almost always followed by an id. If two orders from one customer arrive in the same millisecond and the key is only placed_at, they are the same row. Cassandra writes are upserts, so the second silently overwrites the first.

tie-breaker columnruns offline
-- illustrative
PRIMARY KEY ((customer_id), placed_at, order_id)
-- same placed_at: order_id decides the order, and both rows survive
-- an alternative is a timeuuid, which carries time and uniqueness in one value

PostgreSQL treats the two ideas separately. The primary key makes a row unique, and ORDER BY has no promise about ties unless I add a second column.

In Cassandra both jobs are done by the key. So when I pick the tie-breaker I ask two questions: is it unique enough, and is its order meaningful? An order id or a timeuuid answers both, while a random number answers only the first.

Q13. "What is a composite partition key and when do you use one?"

Reveal answer

Strong answer A composite partition key has more than one column inside the inner parentheses, like PRIMARY KEY ((restaurant_id, day), placed_at). The hash covers all of them together, so each combination is its own partition.

I use it to split an otherwise large partition into bounded pieces, such as per restaurant per day. The price: a query must give all partition-key columns by equality.

Picture it One restaurant's orders split by day.

The setup: Restaurant 12 gets 3,000 orders a day. Over a year that is about 1.1 million rows.

Relational · PostgreSQL

One table. A date range scan slices it.

pg.sqlruns offline
SELECT * FROM orders
WHERE restaurant_id = 12
  AND placed_at::date = '2026-11-23';

Cassandra · CQL

Day joins the partition key.

cql.cqlruns offline
PRIMARY KEY (
  (restaurant_id, day), placed_at)
SELECT * FROM orders_by_restaurant_day
WHERE restaurant_id = 12
  AND day = '2026-11-23';

The shift: Relational slices a big table by a filter. Cassandra slices by building the bucket into the key.

What you see: Partition counts and sizes.

sizesruns offline
# illustrative output
one key ((restaurant_id)):        1 partition x 1.1M rows  (too big)
composite ((restaurant_id, day)): 365 partitions x 3,000 rows each

Why: Each day is small and cheap to read. The cost: a week means 7 reads.

Land it I use a composite partition key to bound partition size, and I accept that every read must supply the whole key.

Likely follow-ups
"What breaks if I give only restaurant_id?"

The query is rejected, because Cassandra cannot find a partition without all of its key columns. The key is hashed to pick the node, and a hash needs its full input. With only restaurant_id, there is no single hash, and no single place to look.

PostgreSQL would run the same filter without complaint, using an index on restaurant_id, and I would pay in speed only if the table were large.

the rejectionruns offline
# illustrative output
SELECT * FROM orders_by_restaurant_day WHERE restaurant_id = 12;
InvalidRequest: ... Cannot execute this query as it might involve data filtering ...

I have three honest fixes. Give the day as well. Use day IN (...) for a short list of days. Or, if the screen really starts from the restaurant alone, build a second table keyed by restaurant id with its own bounded design. I do not reach for ALLOW FILTERING.

"How do I read a week?"

Seven queries, one per day, issued at the same time and merged in the application. PostgreSQL would use one query with day BETWEEN ..., because one machine can scan an index range. In Cassandra each day is a separate partition, possibly on a separate node, so a "range of days" is a set of single-partition reads.

a week in Java (sketch)runs offline
// illustrative
List<CompletionStage<AsyncResultSet>> days = new ArrayList<>();
for (LocalDate d : week) {
    days.add(session.executeAsync(ps.bind(12L, d)));
}
// wait for all seven, then merge by placed_at

With 3,000 orders a day the merge handles 21,000 rows at most (7 x 3,000). Seven small reads running in parallel usually finish about as fast as the slowest one, and are faster than one huge read. day IN (...) also works but puts the waiting on one coordinator, so I prefer separate async queries. If one day fails, I retry only that day, and the other six results are kept, which a single big query cannot offer.

"Is the order of columns inside the key important?"

Not for placement, but it matters for readability. The whole tuple is hashed, so the order of the columns inside the inner parentheses has no effect on how well the data spreads. The query can name them in any order in the WHERE clause as long as all of them are given by equality.

The order does matter for people reading the schema, and it cannot be changed later without a new table. I put the entity first and the bucket second, so the key reads as who, then when.

who, then whenruns offline
-- illustrative
PRIMARY KEY ((restaurant_id, day), placed_at, order_id)   -- reads naturally
PRIMARY KEY ((day, restaurant_id), placed_at, order_id)   -- same behaviour, harder to read

PostgreSQL differs here. The column order in a multi-column index does matter there, because a query that skips the first column cannot use the index well. In Cassandra, skipping any partition-key column is an error.

"Can I add more columns for spread?"

Yes. A shard number is the same idea as a bucket, but it splits a hot key by hash instead of by time. For a restaurant that gets thousands of orders a minute at lunch, one (restaurant, day) partition becomes a hot spot, because every write lands on the same three replicas.

I add a shard column to the partition key and write to one shard chosen from the order id.

sharded keyruns offline
-- illustrative
PRIMARY KEY ((restaurant_id, day, shard), placed_at, order_id)
-- write: shard = order_id % 16
-- read : 16 parallel queries (shard 0..15), merged by placed_at

If the key took 2,000 writes a second, each of the 16 shards now takes about 125 (2,000 / 16). The price is 16 reads to see the whole day, so I use shards only when one partition cannot carry the load.

PostgreSQL has no direct equivalent, since a single primary absorbs the writes.

Q14 · Scenario. "We store chat messages with PRIMARY KEY (conversation_id, sent_at). A group with 5 million messages is slow. Why?"

Reveal answer

Strong answer The partition is one conversation. A busy group chat keeps growing, so its partition becomes huge: millions of rows, hundreds of MB. Reads of the latest page may still be fast, but compaction, repair and caches suffer, and the owning nodes become hot.

The fix is a time bucket in the partition key, for example per month: ((conversation_id, month), sent_at). Each bucket is bounded. The app reads the newest bucket first and goes back one bucket when the user scrolls far enough.

Picture it A conversation's partition before and after bucketing.

The setup: Group chat 77: 5 million messages over 3 years, about 140 bytes each.

Relational · PostgreSQL

One table, index on (conv, time). Size does not matter to the layout.

pg.sqlruns offline
SELECT * FROM messages
WHERE conv_id = 77
ORDER BY sent_at DESC LIMIT 50;

Cassandra · CQL

One partition per month.

cql.cqlruns offline
PRIMARY KEY ((conv_id, month),
              sent_at)
SELECT * FROM msgs
WHERE conv_id = 77
  AND month = '2026-11' LIMIT 50;

The shift: Relational lets the index hide growth. Cassandra needs growth bounded in the key.

What you see: Size before and after.

size math (illustrative)runs offline
5,000,000 rows x 140 B = 700 MB in ONE partition
bucketed per month (36 months): about 19 MB each

The fix: Read the newest bucket first. If it has fewer than 50 rows, read the previous month.

Why: Each read touches one small partition, usually the newest.

Land it I put a time bucket in the partition key so no conversation grows without bound, and read the latest bucket first.

Likely follow-ups
"How do I know the current bucket?"

The app computes the bucket from the clock. For a new message the bucket is the current month, in UTC, so every server agrees. For older pages it steps back one bucket at a time.

compute the bucketruns offline
// illustrative
String month = YearMonth.now(ZoneOffset.UTC).toString();   // "2026-11"
session.execute(insert.bind(77L, month, Uuids.timeBased(), "hi"));

I derive the bucket from the message's own time, not from the time of the read, so a message always belongs to the same bucket, even if it is written late.

In PostgreSQL none of this exists, since the table is one table and an index on (conversation_id, sent_at) is enough.

The edge case is the month boundary. A message sent at 23:59:59 UTC on 30 November goes to the November bucket, and one a second later goes to December. A reader that wants the latest 50 messages checks the newest bucket first and steps back if it returns fewer than 50.

"What if a quiet chat has 3 messages in 3 buckets?"

Then reading 50 messages takes up to 3 queries, which is acceptable. Each is a small, single-partition read, and the app can stop as soon as it has 50.

The loop is simple: read the newest bucket, count rows, and if fewer than 50 came back, read the previous bucket. For a chat with 3 messages over 3 months, that is 3 reads of 1 row each.

If this becomes common, there are two cheap remedies:

  1. Widen the bucket: a quarter or a year, if the chats are quiet in general.
  2. Track active buckets: a tiny table of conversation to latest bucket, which tells the app where to start without walking back through empty months.

I would not build per-chat bucket sizes unless the data forces it. PostgreSQL has no such problem, because one index covers the chat in one go. In Cassandra the price of bounding every partition is a few extra small reads for quiet chats.

"Can bucket size differ per chat?"

Not without extra metadata. A fixed bucket for every chat is simpler, because every part of the code can compute it from the message time. A per-chat size needs a lookup first and adds a failure path.

I choose the fixed size from the busiest chats, because they are the ones that hurt. Quiet chats just use more buckets than they need, which costs a few extra small reads.

size the busiest chatruns offline
# illustrative: 5,000,000 messages over 48 months, about 200 bytes each
5,000,000 / 48 = about 104,000 messages per month
104,000 x 200 B = about 21 MB   (size fine, rows right at the 100,000 guideline)

That says a month is borderline for the busiest chat, so I would pick a week for safety, or accept the guideline and watch the max partition size. A week would give about 24,000 rows (104,000 / 4.3) per bucket for that chat. PostgreSQL has no equivalent decision, since a table needs no bucket.

"How do I find a partition that is already too big?"

nodetool tablehistograms and tablestats show the partition sizes, per node. I compare the maximum to the 99th percentile. If the maximum is hundreds of times the percentile, a few giant partitions are hiding behind a healthy average.

partition statsruns offline
# illustrative
nodetool tablehistograms ks messages
99%   Partition Size  2.1 MB
Max   Partition Size  740 MB      <- a few chats are huge

The server log also warns when compaction writes a very large partition. The threshold is a setting, so check its name for your version.

To find which chats are big, I scan the table with a job and count rows per partition, since Cassandra has no GROUP BY across partitions the way PostgreSQL does.

The fix for a partition that is already huge is a new bucketed table plus a backfill, and then the old one is dropped. Until then, reads of the latest page may still be fast, so the problem shows up first in repair, compaction and hot nodes, and not in the application logs. That is why I watch the maximum, not the average.

Q15 · Scenario. "How do you estimate partition size, and what numbers do you aim for?"

Reveal answer

Strong answer Multiply rows per partition by bytes per row, and add some overhead. I aim under about 100 MB and about 100,000 rows as a guideline, since bigger partitions slow compaction, repair and reads.

I do the arithmetic for the busiest key, not the average, because the busiest partition is the one that hurts.

Picture it Orders per customer, average and heaviest.

The setup: Row = order_id 8 B, placed_at 8 B, total 8 B, restaurant_name 20 B, plus about 40 B overhead = about 90 B.

Relational · PostgreSQL

Row count per customer is irrelevant to the table design.

pg.sqlruns offline
SELECT max(c) FROM (
  SELECT count(*) c FROM orders
  GROUP BY customer_id) t;

Cassandra · CQL

Row count per partition is a design number.

cql.cqlruns offline
-- rows x bytes per partition
-- 5,000 x 90 B   = 0.45 MB   ✅
-- 600,000 x 90 B = 54 MB     ⚠ close

The shift: Relational size is the whole table. Cassandra size is one partition at a time.

What you see: Average customer versus a power user.

sizes (illustrative)runs offline
average customer : 40 orders  x 90 B = 3.6 KB
heavy customer   : 5,000 x 90 B = 450 KB
a business account: 600,000 x 90 B = 54 MB  (watch it)
safe if each partition stays below ~100 MB

Why: The model is fine for people. A bulk-order business needs a bucket.

Land it I compute rows times bytes for the busiest partition and aim below about 100 MB and 100,000 rows.

Likely follow-ups
"What counts as part of a row?"

A row is the sum of its cells, and each cell has a value, a timestamp and a small header. Column names are stored once in the schema and not repeated in each row, which is different from some document stores.

My recipe is to add the value bytes, add the clustering key bytes, add per-cell overhead, then add a margin. The overhead is roughly a few to a few dozen bytes per cell, depending on the version, so I use 20 as a planning number and verify it later.

one row, roughruns offline
# illustrative planning numbers
values: order_id 8 + placed_at 8 + total 8 + name 20 = 44 bytes
overhead: 4 cells x 20 bytes = 80
(44 + 80) x 1.3 margin       = about 161 bytes per row

PostgreSQL has its own per-row header of about 23 bytes plus padding. The principle is the same: count the overhead, not just the data. Then I check with tablehistograms on real data.

"Does TTL or delete change the size?"

Deleted data stays on disk as tombstones (markers that say "this was deleted") until compaction removes it after gc_grace_seconds, which defaults to 10 days. So a partition with many deletes is bigger than its live row count suggests.

Imagine a partition that received 100,000 rows, and 50,000 of them were deleted today. A query sees 50,000 live rows. The disk holds the 100,000 originals and 50,000 tombstones until compaction runs after the grace period.

Reads also pay for them. A single read warns at 1,000 tombstones and fails at 100,000 by default. So a table with heavy deletes can be unreadable while it looks small.

For a table with TTL, expired rows leave tombstones for a while too. I add a margin of 20 to 50 percent to the estimate for churny tables. In PostgreSQL deleted rows also linger until vacuum, so the same principle applies, with different machinery.

"Is 100 MB a hard limit?"

No, it is a guideline. The number to remember is about 100 MB and about 100,000 rows as a healthy ceiling. The real hard limit is about 2 billion cells in one partition, far above anything sensible.

Cells are rows times columns, so the hard limit and the guideline are far apart.

guideline versus hard limitruns offline
# illustrative
100,000 rows x 8 columns = 800,000 cells   (the guideline)
2,000,000,000 cells / 8  = 250,000,000 rows (the hard limit)

A partition at the hard limit would be unusable long before it hit the limit, because reads, repair and compaction all slow down. That is why I quote both figures in an interview and say clearly which is which.

PostgreSQL has no per-key limit to speak of, since one table holds everything on one machine. The limit of Cassandra's design is the price paid for placing each partition on specific nodes.

"How do I check real sizes?"

Two nodetool commands answer it. tablehistograms shows percentiles of partition size and cell count for a table on that node. tablestats shows the mean and maximum compacted partition size, among many other numbers.

nodetoolruns offline
# illustrative
nodetool tablehistograms ks orders_by_customer
nodetool tablestats ks.orders_by_customer | grep -i 'partition'
# look for: Compacted partition maximum bytes / mean bytes

The numbers are local to one node, so a heavy key can look small on a node that does not hold it. I run them on a node that is a replica for the heavy key, and then on a few others.

PostgreSQL measures at the table or index level with functions such as pg_total_relation_size, and Cassandra measures per partition, since the partition is its unit of design. I check after each big load and again after a week of normal traffic, and I put the maximum on a dashboard with an alert at the guideline.

Drill · Buckets, uniqueness and lookups

These questions test bucketing, uniqueness and lookup tables.

Q16. "What is time bucketing and why do time-series models need it?"

Reveal answer

Strong answer Bucketing means adding a time slice to the partition key (hour, day, month) so each partition covers a bounded span. Without it, a key like sensor_id would collect one row per reading forever.

The bucket size comes from the rate. Pick the span so that one partition ends up at tens of MB at most.

Picture it A sensor that reports every second.

The setup: Sensor 5 sends 1 reading per second. That is 86,400 rows per day.

Relational · PostgreSQL

One table, a time index. Nothing needs bucketing.

pg.sqlruns offline
CREATE INDEX ON readings
  (sensor_id, ts);
-- or partition by month

Cassandra · CQL

The bucket is a partition-key column.

cql.cqlruns offline
PRIMARY KEY ((sensor_id, day), ts)
SELECT * FROM readings
WHERE sensor_id = 5
  AND day = '2026-11-23'

The shift: Relational tables grow and the planner copes. Cassandra partitions must stay bounded.

What you see: Sizes with and without the bucket.

math (illustrative)runs offline
no bucket : 86,400 x 365 = 31.5M rows per sensor per year
day bucket: 86,400 rows per partition x 30 B = 2.6 MB

Why: A day partition is small, easy to expire with TTL, and friendly to TWCS compaction.

Land it I pick the bucket from the write rate so one partition stays small, then read buckets from newest backward.

Likely follow-ups
"Why a day and not an hour?"

The numbers decide it. The bucket size comes from the write rate times the row size, and I want one partition near a few MB up to tens of MB. At one reading per second a day is about 86,400 rows, comfortably small. At 100 readings a second a day would be 260 MB, so I would choose an hour.

pick the bucketruns offline
# illustrative: assume 30-byte rows
rate 1/s  : hour = 108 KB, day = 2.6 MB, month = 78 MB    -> day
rate 100/s: hour = 10.8 MB, day = 259 MB                   -> hour

PostgreSQL has no such question for a plain table, since one table with a (sensor_id, time) index grows without a limit on its own. Cassandra needs the bucket in the key because a partition cannot be split across nodes.

A smaller bucket means more queries per time range, so I choose the largest one that stays comfortably under the size budget.

"How do I query across days?"

One query per bucket, issued in parallel and merged in the application. PostgreSQL would use one query with a time range, because one index covers all days. In Cassandra each day is a separate partition, so a seven-day chart is seven reads.

a week of readingsruns offline
-- illustrative: run these seven in parallel, one per day
SELECT at, value FROM readings WHERE sensor_id = 5 AND day = '2026-11-19';
SELECT at, value FROM readings WHERE sensor_id = 5 AND day = '2026-11-20';
-- ... up to 2026-11-25, then merge by time in the app

Because the queries are independent, I send them together and the total time is about the slowest one. At 1 reading a second each day is about 2.6 MB, so seven days is 18 MB (7 x 2.6) in total, which is comfortable.

For a long range, such as a year, I would not read it all. I would read a pre-computed daily summary table instead, and keep the raw rows only for recent days. That summary is another table written by a small job, in line with the one-table-per-query rule.

"Does the bucket help deletion?"

Yes. Deleting old data in Cassandra is cheap when buckets, compaction windows and TTL (time to live, an expiry set on each write) line up. With TWCS (Time-Window Compaction Strategy), data written in the same window is compacted together. When every row in an old file has expired, the file can be dropped as a whole without rewriting anything.

TTL plus time windowsruns offline
-- illustrative
CREATE TABLE rider_track (
  rider_id bigint, day date, at timestamp, lat double, lon double,
  PRIMARY KEY ((rider_id, day), at))
WITH default_time_to_live = 604800            -- 7 days
 AND compaction = {'class': 'TimeWindowCompactionStrategy',
                   'compaction_window_unit': 'DAYS', 'compaction_window_size': 1};

PostgreSQL gets the same effect with partitioned tables, by dropping the old month's partition, which is also a cheap metadata operation. A row-by-row DELETE in either database is the costly way.

The one catch is that the file is dropped only after the expiry and the grace period, so the space returns a little later. I also keep the bucket, the compaction window and the TTL in the same units, such as one day, so that the data of one bucket lands in one window and expires together.

"What if the bucket boundary is crossed in mid-query?"

I read the current bucket and the previous one together and merge. For "the last 30 minutes" at 00:10 UTC, the range starts at 23:40 yesterday, so the query must cover today and yesterday.

  1. Compute: list every bucket that overlaps the time range. At most it is two for a short range with day buckets.
  2. Query: read those buckets in parallel, each with a time condition such as at >= ? on the clustering column.
  3. Merge: combine the results in time order and trim to the range.

PostgreSQL is simpler here, because one query with a time range works across any boundary. In Cassandra I do the splitting in code, and it is one small function that I write once and test around midnight and month ends.

I do this in UTC, so every server computes the same buckets. A time range that spans many buckets becomes many reads, which is why I keep ranges small and keep a summary table for long ones.

Q17. "What is a static column, and when would you use it?"

Reveal answer

Strong answer A static column holds one value per partition, shared by all its rows. It is declared with STATIC and is stored once, not repeated per row.

I use it for facts about the partition owner that are the same in every row, like the restaurant name in a table of that restaurant's orders.

Picture it A restaurant's name stored once, with many order rows.

The setup: Partition (restaurant 12, day) has 3,000 order rows, all needing the restaurant name.

Relational · PostgreSQL

The name lives in restaurants. A join adds it.

pg.sqlruns offline
SELECT o.*, r.name
FROM orders o JOIN restaurants r
  ON r.id = o.restaurant_id;

Cassandra · CQL

The name is a static column in the partition.

cql.cqlruns offline
CREATE TABLE orders_by_restaurant_day (
  restaurant_id bigint, day date,
  placed_at timestamp,
  restaurant_name text STATIC,
  PRIMARY KEY ((restaurant_id, day),
               placed_at));

The shift: Relational stores the name once in another table. Cassandra stores it once per partition.

What you see: Reading one partition returns the name with the rows.

partition viewruns offline
# illustrative output
restaurant_name | placed_at | total
Spice Hut       | 19:02     | 18.50
Spice Hut       | 19:05     | 22.00     (same static value)

Why: One write changes the name for every row of that partition. A static column only works within a partition.

Land it I use a static column for a value that belongs to the whole partition, so it is stored once and read with every row.

Likely follow-ups
"Can a table with static columns have no clustering columns?"

No. Cassandra refuses a static column in a table that has no clustering columns. A static column is shared by all rows in a partition, and if each partition holds only one row, there is nothing to share. The static column would be an ordinary column with a confusing name, so Cassandra rejects it at table creation, with a message that static columns need at least one clustering column.

PostgreSQL has no static columns at all. The same idea is usually written as a separate table, joined when needed. In Cassandra the static column keeps that value in the partition, so one read returns it together with the rows.

where static is allowedruns offline
-- illustrative
-- refused: no clustering column
CREATE TABLE restaurants_by_id (restaurant_id bigint PRIMARY KEY, name text STATIC);
-- allowed: placed_at is a clustering column
CREATE TABLE orders_by_restaurant_day (
  restaurant_id bigint, day date, placed_at timestamp, name text STATIC,
  PRIMARY KEY ((restaurant_id, day), placed_at));

I use static columns for facts about the partition owner, such as a restaurant name above its day of orders, and plain columns everywhere else.

"Does updating a static column touch every row?"

No. A static column is one cell in the partition, so updating it is one small write whatever the partition size. If the partition has 3,000 order rows, the restaurant name changes for all 3,000 with a single cell write.

Compare the two databases. In PostgreSQL, if the name was copied into every order row, a rename would be an UPDATE touching 3,000 rows. If it lives in one restaurants row, it is one row but needs a join to read. The static column gives Cassandra both: one write and no join.

one cell, whole partitionruns offline
-- illustrative
UPDATE orders_by_restaurant_day SET name = 'Spice Hub'
WHERE restaurant_id = 12 AND day = '2026-11-25';
-- 1 cell written; all 3,000 rows of that partition now return the new name

That is the main reason to prefer it over copying the name into every row. The name is also stored once per partition instead of 3,000 times, so the partition is smaller and the read carries less data.

"Does it work across partitions?"

No. A static column is shared only inside one partition, and the partition here is one restaurant on one day. Another day is another partition with its own copy of the value.

So a rename costs one update per partition that carries the name. With one partition per day, a restaurant that has been trading for a year has 365 of them, and a rename means 365 updates.

rename costruns offline
# illustrative
static name, partition per day: 365 partitions x 1 cell = 365 updates
lookup table keyed by id      :   1 row         = 1 update, one extra read per screen

If names change often, I do not embed them. I keep the name in a small lookup table keyed by restaurant id and read it separately, usually from an application cache. If names almost never change, and old orders should show the name at the time, the static copy is fine.

PostgreSQL would simply join to the restaurants table, so this decision does not arise there.

"Can it be part of the key?"

No. Static columns cannot be part of the primary key. A key column identifies a row or a partition, while a static column is plain data that belongs to the whole partition. Mixing the two roles would make no sense, since the key must be known before the partition is found.

PostgreSQL does not have the restriction in this form, since any column can be in a primary key. In Cassandra it falls out of how the storage is laid out: the partition key is hashed to find the node, and the static cell lives inside the partition it finds.

static in a tableruns offline
-- illustrative
CREATE TABLE orders_by_restaurant_day (
  restaurant_id bigint, day date, placed_at timestamp,
  restaurant_name text STATIC,
  total decimal,
  PRIMARY KEY ((restaurant_id, day), placed_at));

The saving is easy to estimate. A 20-byte name repeated in 3,000 rows is 60 KB per partition, against 20 bytes stored once.

Q18 · Scenario. "Our query WHERE customer_id = 7 AND total > 20 fails with a data filtering error. Why, and what do we do?"

Reveal answer

Strong answer total is a normal column, not part of the primary key. Cassandra can find the partition, but cannot jump to the rows with total over 20, because rows are sorted by time, not total.

The options: filter in the application (small partitions only), make total a clustering column in another table, add an SAI index on total if the usage is light, or use ALLOW FILTERING knowing it scans the partition.

Picture it Four options for the same question.

The setup: Customer 7 has 40 orders. The screen wants those over 20.

Relational · PostgreSQL

A condition on any column is fine.

pg.sqlruns offline
SELECT * FROM orders
WHERE customer_id = 7
  AND total > 20;

Cassandra · CQL

Total must be in the key to be seekable.

cql.cqlruns offline
CREATE TABLE big_orders (
  customer_id bigint, total decimal,
  order_id bigint,
  PRIMARY KEY ((customer_id), total,
               order_id));
SELECT * FROM big_orders
WHERE customer_id = 7 AND total > 20;

The shift: In SQL any column can be a filter. In CQL only key columns can seek.

What you see: The choice with a small partition.

chooseruns offline
40 rows in the partition  -> filter in the app (cheap)
5,000 rows               -> table with total in the key
rare admin screen        -> SAI or ALLOW FILTERING

Why: The cost follows how many rows must be looked at to find the matches.

Land it I say only key columns can seek, so I either filter a small partition in the app or store the data in a table keyed by that column.

Likely follow-ups
"Why is filtering inside one partition tolerable?"

Because the filtering never leaves the replica set that owns the partition. Cassandra finds the partition by the key, reads its rows in order, and drops the ones that do not match. The worst case is bounded by the partition size.

PostgreSQL does the same thing when it uses an index on customer_id and then checks the other conditions, so the shape is familiar. The difference is that Cassandra does not warn you about the size, so I enforce the bound by design.

what the worst case costsruns offline
# illustrative: assume 3,000 rows x 90 B per customer, 100 requests/s
3,000 x 90 B   = 270 KB read per request
270 KB x 100/s = 27 MB/s on that replica set, to return a handful of rows

That is acceptable. It would not be acceptable at 3 million rows, which would be 270 MB per request. So I allow filtering in a small, capped partition and forbid it across partitions, where the cost is the whole table. The cap must come from the design, for example a day bucket or a TTL, and not from hope.

"What does the table with total in the key lose?"

The cost is one more copy of the data, and the time ordering. A table keyed by total sorts by total, not by time, so the time-ordered screen still needs the original table. In PostgreSQL I would add an index on (customer_id, total) and keep one table. In Cassandra the index is a second table.

two orderingsruns offline
-- illustrative
orders_by_customer : PRIMARY KEY ((customer_id), placed_at, order_id)   -- time list
big_orders         : PRIMARY KEY ((customer_id), total, order_id)       -- value list
-- WHERE customer_id = 7 AND total > 20  is now a true seek in big_orders

Each copy costs a write for every new order, plus its storage and its repair. So I add the second table only if the screen is real, and I list it in the access-pattern list so that it is not forgotten.

The read becomes a seek that touches only the rows it returns, which is what I wanted. If a screen needs both views, I write each order into both tables in one logged batch, so that they stay in step.

"What about SAI on total?"

SAI makes the query legal and faster than a scan. With an SAI index on total, the query that gives the partition key and a range on total works, with no ALLOW FILTERING. I would accept it for an internal screen or a modest request rate.

SAI on totalruns offline
-- illustrative
CREATE INDEX ON orders_by_customer (total) USING 'sai';
SELECT * FROM orders_by_customer WHERE customer_id = 7 AND total > 20;

It is the closest Cassandra gets to a PostgreSQL index on a normal column, and it is much better than the old secondary index. It has costs, though. Every write must also update the index, and a query that runs on a screen with many users still does more work than a plain seek.

So I measure it with realistic data volumes and request rates before I rely on it. If the screen is a hot path, I build the table keyed by total, and I keep SAI for lighter use.

"What if the threshold changes per request?"

A range on a clustering column handles any threshold with one table. That is what makes the table keyed by total so useful. Total above 20, above 50 and above 100 are all seeks into the same sorted list, and each one stops where the condition stops.

Suppose one customer has six orders, sorted by total from the highest down.

QueryRows read
total > 1001 (140)
total > 503 (140, 95, 60)
total > 204 (140, 95, 60, 42)

The rest of the list (18 and 9) is never touched. This is the same behaviour as a PostgreSQL B-tree on (customer_id, total), and the cost grows with the answer, not with the table.

So one design covers a whole family of queries, with a threshold that changes per request. That is why I prefer it to filtering, where each threshold would read the full partition.

Q19 · Scenario. "Users can log in by email or by username. Both must be fast. How do you model it?"

Reveal answer

Strong answer I keep one table per lookup. users keyed by user id holds the profile. user_by_email and user_by_username are small tables mapping the lookup value to the id.

Login reads the mapping (one partition), then the profile (one partition). Registration writes all three, in a logged batch, after checking that the email and username are free.

Picture it Three tables replace two unique indexes.

The setup: 2 million users. The login screen gets an email or a username.

Relational · PostgreSQL

One table, two unique indexes.

users.sqlruns offline
CREATE TABLE users (
  id bigint PRIMARY KEY,
  email text UNIQUE,
  username text UNIQUE);

Cassandra · CQL

One table per lookup.

users.cqlruns offline
CREATE TABLE user_by_email (
  email text PRIMARY KEY,
  user_id bigint);
CREATE TABLE user_by_username (
  username text PRIMARY KEY,
  user_id bigint);

The shift: Relational indexes are private helpers. Cassandra lookup tables are public tables you maintain.

What you see: A login by email.

two readsruns offline
SELECT user_id FROM user_by_email WHERE email = 'a@b.com';
SELECT * FROM users WHERE id = 1042;

Why: Both reads are single-partition and fast. The cost is keeping three tables in sync.

Land it I give each login route its own lookup table, and I write them together with a uniqueness check.

Likely follow-ups
"How do you keep email unique?"

I use IF NOT EXISTS on the lookup table. In PostgreSQL I would add a UNIQUE constraint and let a duplicate insert fail, which is cheap. Cassandra has no constraint, so uniqueness has to be a conditional write, and that is a lightweight transaction (LWT) that costs about four round trips. Registration is rare, so I accept it.

claim an emailruns offline
-- illustrative
-- PostgreSQL
INSERT INTO users (email, ...) VALUES ('a@b.com', ...);   -- fails on duplicate
-- Cassandra
INSERT INTO user_by_email (email, user_id) VALUES ('a@b.com', 1042) IF NOT EXISTS;
-- result column [applied] is true, or false with the existing row

The lookup table is keyed by email, so the conditional check runs inside one partition, which is where LWT is safe. I claim the email, then the username, then write the profile, and if a later step fails I release the earlier claim. The cost is a few extra milliseconds at sign-up, which nobody notices. The same pattern covers usernames, phone numbers and any other value that must be unique, one lookup table per value.

"What if the user changes email?"

Three steps, and the order matters. PostgreSQL would run one UPDATE inside a transaction. In Cassandra the two lookup tables and the profile are different partitions, so I run the steps in a safe order.

changing an emailruns offline
-- illustrative
INSERT INTO user_by_email (email, user_id) VALUES ('new@b.com', 1042) IF NOT EXISTS;
UPDATE users SET email = 'new@b.com' WHERE id = 1042;
DELETE FROM user_by_email WHERE email = 'old@b.com';

Claim the new address first, because that is the step that can be refused. If it fails, nothing has changed. Then update the profile. Release the old address last, so the user never has a moment with no way to log in.

A conditional statement cannot normally share a batch with writes to other partitions, so I run these one after the other and not in a batch. If the process dies between steps, the user may hold two emails for a moment, and a cleanup job removes the old one.

"Why not an index on users.email?"

Because the index would ask many nodes on every login. A classic secondary index is stored per node, so a query without the partition key must ask nodes across the ring. At 500 logins a second that adds latency and load in a place where the user is waiting.

There is a second reason. In PostgreSQL a UNIQUE index gives both a fast lookup and a guarantee of uniqueness. A Cassandra secondary index gives neither. It does not enforce uniqueness, and it does not make the lookup a single-node read.

A lookup table keyed by email touches one replica set, whatever the cluster size, and with IF NOT EXISTS on insert it also keeps emails unique.

So the table does both jobs. The index would only half do one of them.

The price is one more table to write at registration and to keep in step with the profile. For logins that is a good price, because registration happens once and logins happen every day.

"Can the lookup tables get out of sync?"

They can, if a failure strikes between writes, and I plan for it. PostgreSQL would keep them in step with a transaction. Cassandra has no transaction across these partitions, so two things can go wrong.

  1. Orphan lookup: an email row that points to a user whose profile was never written. The email is taken but nobody owns it.
  2. Missing lookup: a profile with no email row. The user exists but cannot log in by email.

Writing in a safe order narrows the first case. Conditional claims cannot join a multi-partition batch, so the claim happens first, then the profile, then any plain copies in a logged batch.

A cleanup job removes the rest. It scans the lookup tables, checks that each profile exists and matches, and removes orphans older than a few minutes. It also rebuilds a missing lookup from the profile.

Because writes are upserts, the job is safe to repeat.

Q20. "There is no UNIQUE constraint in Cassandra. How do you make something unique?"

Reveal answer

Strong answer The primary key is the only uniqueness rule: two writes with the same key are the same row, and the later write wins. So uniqueness means making the thing I want unique the key of a table.

To reject a duplicate instead of overwriting it, I use INSERT ... IF NOT EXISTS. That is a lightweight transaction using Paxos: it costs about four round trips, and works for one partition.

Picture it Two people register the same username at once.

The setup: Alice and Bob both choose the username 'ravi' within 1 ms.

Relational · PostgreSQL

A UNIQUE index decides who loses.

pg.sqlruns offline
INSERT INTO users (username)
VALUES ('ravi');
-- second insert: ERROR
-- duplicate key value

Cassandra · CQL

A plain insert overwrites. IF NOT EXISTS rejects.

cql.cqlruns offline
INSERT INTO user_by_username
 (username, user_id)
VALUES ('ravi', 1042)
IF NOT EXISTS;
-- [applied] False for the loser

The shift: Relational stores a constraint. Cassandra negotiates one with a consensus round.

What you see: The result of IF NOT EXISTS.

cqlsh outputruns offline
# illustrative output
 [applied] | username | user_id
-----------+----------+---------
      True |     ravi |    1042
     False |     ravi |    1042   <- second attempt sees the winner

Why: Only one of the two writes wins. The other learns who did.

Land it I make the unique value the key of a table and use IF NOT EXISTS where a duplicate must be refused.

Likely follow-ups
"What does IF NOT EXISTS cost?"

It runs a Paxos round, which costs roughly four round trips between the coordinator and the replicas, against one for a normal write. Paxos is a protocol in which the replicas agree on a single value. PostgreSQL does the equivalent with a unique index check, which costs microseconds on one machine.

cost comparisonruns offline
# illustrative
normal INSERT        : 1 round trip    about 2 ms
INSERT ... IF NOT EXISTS : about 4 round trips, about 8 to 15 ms
# reply carries [applied] = true, or false plus the row that already exists

The figures are only examples. The real latency depends on the network and the cluster, and recent versions have improved Paxos, so I check the docs for the version in use.

The cost is also more than latency. Two LWTs on the same partition at the same time compete, and one of them may have to retry. So I use it on rare events such as sign-up, and never on a hot path. A counter or a feed write that needs an LWT on every request is a sign that the model should change, since 4 round trips on every write would wipe out the benefit of choosing Cassandra.

"Is it safe across partitions?"

No. It is linearizable for one partition only. Linearizable means there is one agreed order of operations on that partition. It does not extend to two partitions. PostgreSQL can enforce two unique constraints in one transaction, but Cassandra cannot.

When a rule involves two tables, I choose one as the arbiter and treat the other as dependent.

  1. Claim: insert the username into user_by_username with IF NOT EXISTS. This table decides who owns the name.
  2. Second claim: insert the email into user_by_email the same way.
  3. Write: create the profile.
  4. Undo: if step 2 or 3 fails, delete the earlier claim.

The window between steps is small, and a cleanup job covers a crash in the middle. Cassandra 6.0 (alpha) previews transactions across partitions, but I teach 5.0.

"What if I skip it?"

Without the check, the last write wins by timestamp, and no error is reported. Cassandra writes are upserts, so a second sign-up with the same key replaces the first.

PostgreSQL would stop the second insert with a unique-violation error. Cassandra stores it silently.

two sign-ups, no checkruns offline
# illustrative: both sign-ups claim the same name
t=1000 us: INSERT user_by_username ('asha', user 41)   -> success shown to user 41
t=1002 us: INSERT user_by_username ('asha', user 77)   -> success shown to user 77
read later: 'asha' -> user 77      user 41 has silently lost the name

Both users were told success, and one is later surprised. If the table holds credentials, this becomes an account-takeover risk, which is worse than a lost name.

That is silent data loss, and it is why uniqueness is an explicit decision in the model. A last-write-wins table has no memory of who came first, so there is nothing to repair afterwards. The only protection is the conditional insert, done before the claim is announced to the user.

"Does Cassandra 6 change this?"

Cassandra 6.0 is in alpha only, so I treat it as coming and design for 5.0. Its headline feature is Accord, a general transaction system that can span partitions. It is off by default and enabled per table, and it is a preview, not something I would depend on in production today.

If it arrives as described, a uniqueness check across two tables could become one transaction. That is the thing PostgreSQL does with two UNIQUE constraints, and today Cassandra needs an arbiter table and a cleanup job to approximate it.

I would be careful about three things before adopting it. The syntax and defaults may change before release. A cross-partition transaction will cost more than a plain write. And it changes the failure modes, so it needs its own load test.

Until a stable release exists, the pattern in the answer stays: make the unique value the key, and use IF NOT EXISTS for rare events.

Drill · Joins and one-to-many

These questions test whether you can translate JOIN and one-to-many.

Q21 · Scenario. "Show me how you would replace a three-table JOIN in Cassandra."

Reveal answer

Strong answer I do not replace the join with code. I replace it with a table that already contains the joined result. I find what the screen shows, then store those fields together under the key the screen uses.

For a three-table join (orders, customers, restaurants) the screen needs order id, time, customer name, restaurant name, total. That is one wide table keyed by whatever the screen starts from.

Picture it A restaurant dashboard that shows orders with customer names.

The setup: The dashboard for restaurant 12 on 2026-11-23 shows each order with the customer's name and total.

Relational · PostgreSQL

Join three tables at read time.

pg.sqlruns offline
SELECT o.order_id, c.name,
       r.name, o.total
FROM orders o
JOIN customers c ON c.id=o.customer_id
JOIN restaurants r ON r.id=o.restaurant_id
WHERE o.restaurant_id = 12;

Cassandra · CQL

One table holds the joined result.

cql.cqlruns offline
CREATE TABLE dash_by_rest_day (
  restaurant_id bigint, day date,
  placed_at timestamp, order_id bigint,
  customer_name text, total decimal,
  PRIMARY KEY ((restaurant_id, day),
               placed_at, order_id));

The shift: The join is paid once, at write time, not on every read.

Make the invisible visible: Writing an order fills that table with the names already known to the app.

write pathruns offline
INSERT INTO dash_by_rest_day
 (restaurant_id, day, placed_at, order_id, customer_name, total)
VALUES (12, '2026-11-23', toTimestamp(now()), 42, 'Asha', 18.50);

Why: The app already knew the names when placing the order, so the join costs nothing then.

Land it I answer a join by writing the joined row into a table keyed for the screen.

Likely follow-ups
"What if the name was not known at write time?"

Then the write path fetches it first. When an order is placed, the app reads the customer and the restaurant by primary key and copies the names into the order rows. In PostgreSQL the join happens on every read. In Cassandra it happens once, at write time.

That lookup is a read of one partition on a small table, usually served from an application cache. One write serves millions of later reads, so the extra read at write time is cheap in total.

read versus write countsruns offline
# illustrative
one order placed: 1 lookup (cached) + 1 write per table
dashboard polls : 40 restaurants x 12 polls/min x 60 min = 28,800 reads/hour
a join at read time would repeat the lookup 28,800 times an hour

The trade is more work and more code on the write path, in exchange for a read that is one partition. If the lookup fails at write time, I either reject the order or store the id and fill the name later, depending on the screen.

"What if a customer changes name?"

Old orders keep the old name, and that is usually the right behaviour for history. A receipt should not change after the fact. A PostgreSQL join shows the current name on every old order, unless the name was copied into the orders table too.

history or currentruns offline
-- illustrative
-- PostgreSQL: join shows the CURRENT name for every order
SELECT o.order_id, c.name FROM orders o JOIN customers c ON c.id = o.customer_id;
-- Cassandra: the name stored on the order is the name at order time
SELECT order_id, customer_name FROM orders_by_customer WHERE customer_id = 7;

If a live screen must show the current name, I store the id with the order and look the name up when rendering. I can do both: the name as it was and the id for any later lookup.

If old rows really must change, I update each copy by its full key, which means I have to keep those keys. The model should say, for each screen, which of the two behaviours it wants. If the business later wants current names everywhere, a backfill can rewrite the copies, and the model tells me which tables to touch.

"How many fields do I copy?"

Only the fields the screen shows, plus its key. The screen in question needs five values: order id, time, customer name, restaurant name and total. Those become the columns of one table keyed by whatever the screen starts from.

one wide table for the screenruns offline
-- illustrative
CREATE TABLE orders_by_customer (
  customer_id bigint, placed_at timestamp, order_id bigint,
  customer_name text, restaurant_name text, total decimal,
  PRIMARY KEY ((customer_id), placed_at, order_id)
) WITH CLUSTERING ORDER BY (placed_at DESC, order_id ASC);

Fewer copied fields make smaller rows and cheaper writes. A field that is copied but never shown is waste multiplied by the row count.

I copy fields that are small and change rarely. A large field, such as a 2 KB restaurant description, is a poor copy, because it would be repeated in every row. For that I store the id and read the description once from its own table. I also write down, next to each copied field, which table is its source, so that a later change to the source can be traced to every copy.

"Can I join in a Spark job?"

Yes, for analytics, not for requests. Spark (a distributed data engine) can read Cassandra tables through a connector, in token ranges and in parallel, and join them with any other dataset. That is how a nightly report such as "revenue per restaurant per customer area" is built.

a join outside the databaseruns offline
-- illustrative: Spark SQL, run as a batch job
SELECT r.area, SUM(o.total)
FROM orders o JOIN restaurants r ON r.restaurant_id = o.restaurant_id
GROUP BY r.area;

PostgreSQL would run this directly on a replica. Cassandra cannot, so the join happens in Spark.

It is a batch job. A user waiting on a screen should never trigger it.

For a join that must stay current, I would use a stream processor, such as Kafka Streams or Flink (see E17), that reads the order events and the restaurant changes, joins them, and writes the result to a Cassandra table. The screen then reads that table by key, so the join is done before the read.

Q22. "How do you model a one-to-many relationship such as customer to orders?"

Reveal answer

Strong answer The 'many' side becomes rows inside the partition of the 'one'. Partition key = the one (customer_id). Clustering columns = the many (placed_at, order_id).

The foreign key column becomes the partition key. The join becomes a plain read of one partition.

Picture it Customer 7 and their orders.

The setup: One customer, many orders, read together.

Relational · PostgreSQL

Two tables and a foreign key.

pg.sqlruns offline
orders.customer_id
  REFERENCES customers(id);
SELECT * FROM orders
WHERE customer_id = 7;

Cassandra · CQL

One partition per customer.

cql.cqlruns offline
PRIMARY KEY ((customer_id),
              placed_at, order_id)
SELECT * FROM orders_by_customer
WHERE customer_id = 7;

The shift: The foreign key column becomes the partition key.

What you see: Partition 7.

layoutruns offline
# illustrative output
customer 7 -> order 42 (19:02), order 41 (18:30), order 40 (12:15)

Why: The parent id is the address. The children are the sorted rows at that address.

Land it I make the parent id the partition key and the children the clustering rows.

Likely follow-ups
"What if the 'many' is unbounded?"

Then I add a bucket, so that each partition stays small. A customer with a few dozen orders needs none. A business customer with millions of orders would grow one partition without a limit.

bucketed parentruns offline
-- illustrative
PRIMARY KEY ((customer_id, month), placed_at, order_id)
-- one partition per customer per month

The arithmetic shows why. Suppose a corporate account places 50,000 orders a month at about 90 bytes a row.

with and without the bucketruns offline
# illustrative
no bucket  : 50,000 x 24 months = 1,200,000 rows = 108 MB in one partition
with bucket: 50,000 rows = 4.5 MB per monthly partition

PostgreSQL needs nothing like this, since a table and its index can grow. In Cassandra I read the newest bucket first and step back for older pages. For the reader this means the app asks for the newest month first, then steps back a month when the user scrolls far enough.

The size per bucket is known, so the cost of each read is known too. The choice of month as the bucket comes from the order rate of the busiest customer, and for a very large account I would use a week instead.

"Where does the parent's data go?"

The parent's data goes into a static column if it is small and belongs to the whole partition, or into each child row if the screen needs it per row. In PostgreSQL the child holds only a foreign key, and the parent's fields are fetched by a join.

When the partition key is the parent, as with orders_by_customer keyed by customer_id, a static column is a natural fit. The customer's name is stored once, and it comes back with the rows.

parent data in the partitionruns offline
-- illustrative
CREATE TABLE orders_by_customer (
  customer_id bigint, placed_at timestamp, order_id bigint,
  customer_name text STATIC,      -- stored once per customer
  restaurant_name text, total decimal,   -- per order
  PRIMARY KEY ((customer_id), placed_at, order_id));

A customer name on every order row is also fine. It makes each row self-contained, at the cost of repeating the name. I pick the static column when the value is the same in every row and a rename should be one write.

"What if I need the child by its own id?"

Then I build a second table keyed by the child's id. Sometimes the screen starts from the child, such as "open order 42". The list table is keyed by the customer, so it cannot answer that without a scan.

PostgreSQL answers both questions from one table, because it has the primary key on the order id and another index on customer_id. In Cassandra each entry point is its own table.

two entry pointsruns offline
# illustrative
orders_by_customer : (customer_id) -> placed_at DESC   start from customer, list orders
orders_by_id       : (order_id)                        start from order, get detail

When an order is placed, I write it into both tables in one logged batch, so that neither is forgotten. Each extra entry point costs one more write per order, so I add one only when a real screen needs it. In this case it does, since opening an order from a notification starts from the order id, with no customer id at hand.

"What about many parents per child?"

That is a many-to-many relationship, and it needs one table per direction. In PostgreSQL I would add a junction table with two foreign keys. In Cassandra I split the junction into two tables, one for each direction I read.

Take coupons. A restaurant can offer many coupons, and a coupon can apply to many restaurants.

junction versus two tablesruns offline
-- illustrative
-- PostgreSQL: one junction table, two indexes
CREATE TABLE restaurant_coupons (restaurant_id bigint, coupon_code text,
  PRIMARY KEY (restaurant_id, coupon_code));
-- Cassandra: one table per direction
CREATE TABLE coupons_by_restaurant (restaurant_id bigint, coupon_code text,
  PRIMARY KEY ((restaurant_id), coupon_code));
CREATE TABLE restaurants_by_coupon (coupon_code text, restaurant_id bigint,
  PRIMARY KEY ((coupon_code), restaurant_id));

A common mistake is to try to cover both directions with one table and to filter for the other. I build the second table, or I decide the second direction is not needed. The first step in my review of any one-to-many design is to ask whether the reverse question exists too. If it does, the relationship is many-to-many, and the second table is not optional. If it does not, the single table is enough, and I avoid the second write on every order.

Q23. "Model a many-to-many relationship: students and courses."

Reveal answer

Strong answer Many-to-many needs a junction table in SQL. In Cassandra I build one table per direction I read: courses of a student, and students of a course. Each is keyed by the side I start from.

A write to enroll adds one row to each table, in a logged batch.

Picture it Enrolling Asha in two courses.

The setup: Asha takes Maths and Art. Maths has 3 students.

Relational · PostgreSQL

Junction table, two foreign keys.

pg.sqlruns offline
CREATE TABLE enrollment (
  student_id bigint REFERENCES student,
  course_id bigint REFERENCES course,
  PRIMARY KEY (student_id, course_id));

Cassandra · CQL

Two tables, one per direction.

cql.cqlruns offline
CREATE TABLE courses_by_student (
  student_id bigint, course_id bigint,
  PRIMARY KEY ((student_id), course_id));
CREATE TABLE students_by_course (
  course_id bigint, student_id bigint,
  PRIMARY KEY ((course_id), student_id));

The shift: The junction table is split by reading direction.

Make the invisible visible: One enrollment, two rows.

enroll batchruns offline
BEGIN BATCH
 INSERT INTO courses_by_student (student_id, course_id) VALUES (1, 10);
 INSERT INTO students_by_course (course_id, student_id) VALUES (10, 1);
APPLY BATCH;

Why: Both reads are one partition. The cost is two writes.

Land it I split the junction table into one table per reading direction and write both in a batch.

Likely follow-ups
"Why can't one table serve both?"

Because a table has one partition key, and a query must give that key to find rows. Asking from the other side would need a scan of every partition to find the matches. PostgreSQL does not have this problem: its junction table has a primary key and a second index, and both directions use an index.

two directionsruns offline
-- illustrative
-- PostgreSQL: one table, two indexes
CREATE TABLE enrollments (student_id bigint, course_id bigint, PRIMARY KEY (student_id, course_id));
CREATE INDEX ON enrollments (course_id, student_id);
-- Cassandra: one table per direction
courses_by_student : PRIMARY KEY ((student_id), course_id)
students_by_course : PRIMARY KEY ((course_id), student_id)

With 200,000 students, finding the students of one course from the courses_by_student table would mean reading 200,000 partitions. The second table answers the same question with one read of one partition.

So each direction I read gets its own table, and enrolment writes both. A reviewer can check this in seconds: take each screen, find the key it starts from, and confirm that a table with that key exists.

"What if only one direction is needed?"

Then I build only that table. The method says tables follow queries, so a direction that nobody asks costs nothing, and I do not build the second one just in case.

Each extra table has a visible cost. If the system handles 1,000 enrolments a second, two tables mean 2,000 row writes a second, plus double the storage and a second table to repair. A direction that no screen reads is a pure cost.

A rarely needed opposite direction, such as a monthly report of students per course, does not need a table. It can be an offline job that scans the first table, for example with Spark, and runs overnight.

Later, if a real screen needs it, I add the second table with a backfill, as in any other schema change. PostgreSQL makes the second direction almost free with an index, and that is the habit I have to unlearn.

"What if a course has a million students?"

Then the partition for that course is unbounded, so I bucket it or paginate. A course with a million students in one partition is far above the guideline of about 100,000 rows.

bucketed course rosterruns offline
-- illustrative
CREATE TABLE students_by_course (
  course_id bigint, bucket int, student_id bigint,
  PRIMARY KEY ((course_id, bucket), student_id));
-- write: bucket = student_id % 100
-- 1,000,000 students / 100 buckets = 10,000 rows per partition, about 160 KB

Using the remainder spreads the writes evenly over 100 partitions. Reading the whole roster is 100 parallel reads, though in practice nobody reads a million names at once. A screen pages through them, a bucket at a time.

PostgreSQL would just put an index on course_id. In Cassandra the bucket is a design decision I make before the data exists, and I add it when the course size can exceed the guideline. If the roster is only ever read a page at a time, I can also page inside each bucket, and let the app keep a simple cursor of bucket number and last student id.

"How do I remove a link?"

I delete from both tables, in a logged batch, so that both changes eventually apply. In PostgreSQL I would delete one row from the junction table, and both directions would update at once.

unenrollruns offline
-- illustrative
BEGIN BATCH
  DELETE FROM courses_by_student WHERE student_id = 1 AND course_id = 10;
  DELETE FROM students_by_course WHERE course_id = 10 AND student_id = 1;
APPLY BATCH;

Each delete leaves a tombstone (a marker that says the row is gone), which stays until compaction removes it after gc_grace_seconds, 10 days by default. A read that crosses many tombstones warns at 1,000 and fails at 100,000 by default.

Ordinary unenrolling is fine. Very heavy churn in one partition, such as a roster that is emptied and refilled every day, needs thought, since the tombstones pile up. For that case I would look at a time bucket or a different model. I also avoid delete-heavy designs where a cheap alternative exists. For example, an enrolment that flips between active and dropped can be one row with a status column, and not an insert and a delete each time.

Q24. "When do you use a collection column instead of a child table?"

Reveal answer

Strong answer A collection (list, set, map) stores a small group of values inside one row. I use it when the child values are few, always read with the parent and not queried alone, like a customer's phone numbers or an order's tags.

If the group can grow large or is queried on its own, a child table is correct, because a collection is read in full with its row.

Picture it Dish tags.

The setup: A menu item has tags: spicy, vegan, gluten-free.

Relational · PostgreSQL

A child table with a foreign key.

pg.sqlruns offline
CREATE TABLE item_tags (
  item_id bigint REFERENCES items,
  tag text);
SELECT tag FROM item_tags
WHERE item_id = 5;

Cassandra · CQL

A set column inside the row.

cql.cqlruns offline
CREATE TABLE items (
  item_id bigint PRIMARY KEY,
  name text,
  tags set<text>);
UPDATE items SET tags = tags + {'vegan'}
WHERE item_id = 5;

The shift: The child table is folded into the parent row.

What you see: One read returns the tags.

resultruns offline
# illustrative output
item_id | name   | tags
5       | Paneer | {'gluten-free', 'spicy', 'vegan'}

Why: One read, no join. Keep collections small, tens of elements at most.

Land it I use a collection for a few values read with the parent, and a child table for anything large or queried alone.

Likely follow-ups
"What is the limit?"

Cassandra can store large collections, but a read of the collection column reads all of it, together with its row. So the practical limit is the cost of dragging the whole collection into every read, not a hard number.

cost of a big collectionruns offline
# illustrative: 50,000 elements x 20 bytes
50,000 x 20 B = 1,000,000 B = about 1 MB
every read of that row returns 1 MB, even if you wanted one field

PostgreSQL arrays and jsonb columns behave similarly, since a big value is fetched whole. The difference is that a Cassandra row is often read by a screen at a high rate, so the cost repeats.

So I stay with tens of elements, such as a few phone numbers or tags, and use a child table beyond that. A child table lets me read a page of children, and not all of them. A quick test is to ask whether the app ever needs one element on its own. If yes, the element wants to be a row.

"Can I query inside a set?"

Yes, with an index, but it is a secondary path. CONTAINS needs an index on the collection, and SAI in Cassandra 5.0 can provide one. I check the docs for the exact operators in the version in use.

query inside a setruns offline
-- illustrative
-- PostgreSQL: GIN index on an array
SELECT * FROM dishes WHERE 'vegan' = ANY(tags);
-- Cassandra: SAI on the collection, then CONTAINS
CREATE INDEX ON dishes (tags) USING 'sai';
SELECT * FROM dishes WHERE tags CONTAINS 'vegan';

Without a partition key this query still reaches many nodes, so it is a slower path than a lookup table. If a question such as "all vegan dishes" is a real screen, I build a table keyed by tag, with the dishes as rows.

The collection then stays what it is good at, which is carrying a few values along with the row. The index also adds work to every write of that column, so I use it for light, internal queries.

"What is a frozen collection?"

A frozen collection is stored as one value and replaced as a whole. A normal, non-frozen collection stores each element as its own cell, so elements can be added or removed one by one.

frozen versus notruns offline
-- illustrative
tags set<text>            -- non-frozen: UPDATE ... SET tags = tags + {'spicy'}
tags frozen<set<text>>   -- frozen: you must write the whole set again

A frozen collection is required when the collection sits inside another collection or inside a primary key. A non-frozen set is cheaper for adding one element to a large set, since only that cell is written.

There is also a trap with non-frozen collections. If I assign the whole collection with SET tags = {...}, Cassandra writes a tombstone first to clear the old contents, and tombstones cost on reads. A frozen collection has no such step, because it is one value that is simply overwritten. PostgreSQL has no equivalent distinction, since an array is always replaced as a value.

"Why does a list have a trap?"

A list has two traps. Some list operations, such as setting or deleting by position, need a read before the write, which Cassandra normally avoids and which is slower. And appending is not idempotent, which means a retry can add the value twice.

retry of an appendruns offline
-- illustrative
UPDATE customers SET phones = phones + ['9811'] WHERE customer_id = 7;
-- timeout, driver retries the same statement
-- phones may now be ['9811', '9811']
UPDATE customers SET phone_set = phone_set + {'9811'} WHERE customer_id = 7;
-- same statement twice: still one element

A set or a map is usually safer, because adding the same element twice is the same as adding it once. Retries are normal in a cluster that has timeouts, so I want writes that tolerate them.

PostgreSQL's array_append has the same duplicate problem on a retry, but a transaction usually protects it. For an ordered list in Cassandra, I would use a child table with a clustering column instead. I also write down in the model which collection type each column uses, so a reviewer can see the idempotence risk.

Q25. "What is a user-defined type, and where does it replace a table?"

Reveal answer

Strong answer A user-defined type (UDT) is a named group of fields stored in one column, like an address with street, city and pin code. It embeds a one-to-one child inside the parent row.

Frozen UDTs are written and read as a whole. Non-frozen UDTs can update single fields.

Picture it A delivery address on a customer.

The setup: Each order has one delivery address.

Relational · PostgreSQL

An addresses table with a foreign key.

pg.sqlruns offline
SELECT a.city
FROM orders o JOIN address a
  ON a.id = o.address_id
WHERE o.order_id = 42;

Cassandra · CQL

A UDT column inside the order.

cql.cqlruns offline
CREATE TYPE address (
  street text, city text, pin text);
CREATE TABLE orders_by_id (
  order_id bigint PRIMARY KEY,
  deliver_to frozen<address>);

The shift: A one-to-one child becomes a typed column.

What you see: Reading the order returns the address.

resultruns offline
# illustrative output
order_id | deliver_to
42       | {street: '5 MG Rd', city: 'Pune', pin: '411001'}

Why: The address is a snapshot at order time, which is what history needs.

Land it I use a UDT to embed a small structured child in a row, usually frozen.

Likely follow-ups
"Why snapshot the address?"

A copy of the address at order time is a historical fact. If the customer moves later, the order must still say where it was delivered. So I embed the address in the order and do not point to a shared address row.

reference versus snapshotruns offline
-- illustrative
-- PostgreSQL: the order points to an address row
SELECT a.city FROM orders o JOIN addresses a ON a.id = o.address_id WHERE o.id = 42;
-- the customer edits the address row, and order 42 now shows the new city
-- Cassandra: the order carries its own copy
SELECT deliver_to FROM orders_by_id WHERE order_id = 42;

The copy also saves a read, since the order row has the address with it. The price is storage, a few hundred bytes per order, which is cheap. If the business needs the live address for something, such as a marketing list, I read it from the customer table instead. I would also add the snapshot to the order's header only once, since the order lines do not need their own copy of it. An order is a record, so a record keeps its own facts.

"Can I change one field of a frozen UDT?"

No. A frozen UDT is stored as one value, so to change one field I rewrite the whole thing. A non-frozen UDT stores each field as its own cell and allows a single-field update, with the cost of more cells.

replace a frozen UDTruns offline
-- illustrative
UPDATE orders_by_id
SET deliver_to = {street: '5 MG Rd', city: 'Pune', pin: '411001'}
WHERE order_id = 42;
-- non-frozen UDT only: UPDATE ... SET deliver_to.city = 'Pune'

The whole-value rule matters under concurrency. Cassandra resolves conflicts by the timestamp of each write, and with a frozen value the later write wins as a whole. If two services each change a different field at the same time, one change is lost.

So for a snapshot that is written once, frozen is ideal. For a value that several writers edit field by field, I would use separate columns or a non-frozen type. I test this with two quick concurrent writes in staging, to see which value survives, before I trust the design in production.

"Can UDTs nest?"

Yes, as long as the inner type is frozen. I keep nesting shallow, since deep types are hard to read, to query and to change over time.

a nested typeruns offline
-- illustrative
CREATE TYPE geo (lat double, lon double);
CREATE TYPE address (street text, city text, pin text, point frozen<geo>);
CREATE TABLE order_snapshots (order_id bigint PRIMARY KEY, deliver_to frozen<address>);

Two levels is my practical limit. Adding a field to a type later is possible with ALTER TYPE ... ADD, and old values read the new field as null. Removing a field is more awkward, and I would check the docs for the version in use.

PostgreSQL has composite types as well, and a jsonb column is the more common choice there. I choose a UDT in Cassandra when the shape is stable and I want the types checked. A third level is a sign that the nested value wants to be a table of its own.

"When is a table better?"

A table is better when the child is shared by many parents, changes on its own, or needs its own queries. An address book entry that many orders refer to is an example. The customer edits it, and every screen should show the new value.

PostgreSQL would have an addresses table with a foreign key in every case. In Cassandra I choose between a table and a UDT for each use.

live child versus snapshotruns offline
-- illustrative
-- saved addresses of a customer: its own table, edited over time
CREATE TABLE addresses_by_customer (customer_id bigint, address_id uuid, street text, city text,
  PRIMARY KEY ((customer_id), address_id));
-- the delivery address on an order: a frozen UDT snapshot, never edited

A one-to-one snapshot, such as the delivery address on an order, is the ideal case for a UDT. A child with its own life is a table. I often use both for the same data, as in this example. I would not use a UDT when I need to query on one of its fields, because the field is inside a value and has no key of its own.

Drill · Collections, aggregates and indexes

These questions test collections, foreign keys, aggregates, paging and indexes.

Q26. "Cassandra has no foreign keys. How do you keep references valid?"

Reveal answer

Strong answer It does not check references. I treat the id as a plain value and keep consistency in the application and in how I write.

I place the check where it belongs: at write time (read the parent first when an order is created) or in a periodic job. Many references do not need a check, because a missing parent just shows as a gap.

Picture it An order pointing to a restaurant that no longer exists.

The setup: Order 42 points at restaurant 12. The restaurant is deleted.

Relational · PostgreSQL

The database refuses the delete.

pg.sqlruns offline
ALTER TABLE orders ADD FOREIGN KEY
  (restaurant_id) REFERENCES restaurants;
DELETE FROM restaurants WHERE id = 12;
-- ERROR: violates foreign key

Cassandra · CQL

The database accepts it. The app decides.

cql.cqlruns offline
DELETE FROM restaurants WHERE id = 12;
-- applied. Orders keep their copy of
-- restaurant_name: still readable

The shift: The constraint moves from the database into the data and the code.

What you see: Why copying the name helps.

order rowruns offline
# illustrative output
order 42 | restaurant_id 12 | restaurant_name 'Spice Hut'
the order still reads fine

Why: An order is a historical fact, so keeping the copy is the right behaviour.

Land it I say Cassandra does not enforce references, so I copy what history needs and check parents in the write path.

Likely follow-ups
"Where do orphan rows hurt?"

Where something follows an id and expects live data behind it. A stored id that points nowhere is harmless until a screen tries to use it.

In PostgreSQL the foreign key orders.restaurant_id REFERENCES restaurants(id) makes an orphan impossible: the insert fails, and deleting a restaurant that still has orders is refused. Cassandra checks nothing, so an order can name a restaurant that was deleted last week.

The place it shows is a lookup that returns no row, for example the order page asking for the restaurant's phone number. The screen then breaks or shows blank fields.

My fix is in code, not in the database. The order row keeps a copy of the restaurant name it was placed with, so history still reads correctly. For live fields, a missing parent is handled as a normal case: treat the restaurant as closed and show the stored name. I do not add a cleanup job until I have seen orphans cause a real problem.

"Can a batch check existence?"

Yes, but only inside one partition, so it is a narrow tool. A conditional batch is a batch where one statement carries an IF condition, and the whole batch applies only if that condition holds.

The rule is that every statement in a conditional batch must hit the same partition. So if the parent row and the child row share a partition key, I can write the child with a condition that the parent exists.

Different partitions are rejected. Conditions also use the Paxos protocol, so each one costs roughly four round trips and is much slower than a normal write.

For cross-partition references, I read the parent first in the write path (one primary-key read, cheap) and then write the child. A tiny race remains, since the parent could vanish a moment later, and I accept it.

"Would you ever want a constraint?"

For money and stock, yes, and I keep those in PostgreSQL. That is the split the case study makes.

Think about what a broken reference costs. If a restaurant row is missing, a screen shows a gap and carries on. If a payment points to an order that does not exist, or two orders both take the last portion in stock, someone loses money or a customer is charged for nothing. Those cases need real constraints: FOREIGN KEY, CHECK (stock >= 0) and a transaction that rolls back every step together.

Cassandra can do a limited version with conditional writes inside one partition, but it has no multi-row constraint across tables. Cassandra 6.0 has a preview of general transactions (Accord), but it is alpha, so I would not design around it today.

So I use polyglot persistence: PostgreSQL holds the rules and the system of record, and Cassandra holds the high-volume read views fed by events. The two roles do not compete.

"How do I clean up?"

A periodic job finds orphans by comparing a child table against its parent, and it must be gentle because Cassandra has no cheap way to ask which children lack a parent.

  1. Scan: read the child table in token ranges, a few thousand rows at a time, so no single query is large.
  2. Check: for each batch of parent ids, read the parent rows with single-key reads, in parallel but with a limit on how many run at once.
  3. Act: flag the orphan in a small report table first. Delete only after a person or a rule confirms, since a delete leaves a tombstone.

The scan reads whole tables, so I run it off peak and throttle it, for example 2,000 reads per second. I also remember a row may look orphaned only because the parent write is still in flight, so I skip rows younger than an hour.

Q27. "How do COUNT, SUM and GROUP BY work in Cassandra?"

Reveal answer

Strong answer They exist but only within the data a query reads. COUNT(*) over one partition is fine. Over the whole table it scans everything and times out.

For totals I maintain the answer: a counter column, or a table where the total is written as events arrive. For ad-hoc analytics I use a warehouse.

Picture it Orders per restaurant per day.

The setup: The owner wants the count and revenue for restaurant 12 today.

Relational · PostgreSQL

Aggregate over the rows.

pg.sqlruns offline
SELECT count(*), sum(total)
FROM orders
WHERE restaurant_id = 12
  AND day = '2026-11-23';

Cassandra · CQL

A table maintains the answer.

cql.cqlruns offline
CREATE TABLE daily_orders (
  restaurant_id bigint, day date,
  orders counter,
  PRIMARY KEY ((restaurant_id), day));
UPDATE daily_orders SET orders = orders + 1
WHERE restaurant_id = 12 AND day = '2026-11-23';

The shift: Compute at read time versus keep the answer up to date.

What you see: A read is a single row.

readruns offline
SELECT orders FROM daily_orders
WHERE restaurant_id = 12 AND day = '2026-11-23';

Why: The count is ready, not computed. Counters can over-count after a timeout retry, so I do not use them for money.

Land it I keep totals up to date as events arrive, and leave arbitrary aggregation to a warehouse.

Likely follow-ups
"Can I COUNT a partition?"

Yes, and it is fast as long as the partition is a reasonable size. COUNT(*) with the full partition key in the WHERE clause reads only that partition on its replicas and adds up the rows.

The cost grows with the rows read. A partition of 3,000 rows is counted in a few milliseconds. A partition of 3 million rows takes seconds and may hit a read timeout, because Cassandra must read every row to count it. There is no stored row count to look up, unlike a reltuples estimate in PostgreSQL, which is itself only approximate.

The second query below has no partition key, so every node scans everything. PostgreSQL would run the same statement as a slow but legal table scan.

If the number is shown often, I do not count at read time. I keep a counter or a total table, as in Q27's main answer.

bounded and unboundedruns offline
-- illustrative
SELECT count(*) FROM orders_by_restaurant_day WHERE restaurant_id = 12 AND day = '2026-11-23';  -- one partition: fine
SELECT count(*) FROM orders_by_restaurant_day;  -- TRAP: scans every partition on every node
"What does GROUP BY allow?"

Only a narrow form. GROUP BY in Cassandra groups rows that are already next to each other on disk, so it must follow the primary key order: the partition key columns first, then clustering columns from the left, with no gaps.

For orders_by_restaurant_day with key ((restaurant_id, day), placed_at, order_id), I can group by the whole partition key, or by partition key plus placed_at. I cannot group by status or payment_method, because rows with the same status are scattered across the partition.

PostgreSQL is far more flexible: it will hash or sort any column you name, and return the result after a full read. Cassandra refuses instead.

The practical rule: GROUP BY is a small tool for summing up one partition, for example hourly totals for one restaurant-day with GROUP BY hour if hour is a clustering column. For anything else I maintain a table that already holds the answer, or I send the data to a warehouse.

"Why not counters for money?"

Because a retry can apply the increment twice, and money needs an exact answer. A counter update is not idempotent: doing it twice does not give the same state as doing it once.

Here is how it goes wrong. The client sends cents = cents + 1850 and the connection times out. The write may have been applied, or not. If the client retries and the first one had landed, the total is 1,850 too high, and nothing in the database shows that. For a page-view count, being off by one in ten thousand does not matter.

For money I want the opposite: every cent traceable. In PostgreSQL I would have a payments table with one row per payment and a unique key, and SUM(amount) over it, inside a transaction. In Cassandra, I would write one row per payment event with a unique id (so a retry overwrites the same row) and compute totals from those rows. Better still, I keep payment truth in PostgreSQL, and use Cassandra only for read copies.

"What about SUM across partitions?"

It would touch many partitions on many nodes, so I do not run it at read time. Imagine total revenue per day across 5,000 restaurants. The partitions are spread by hash over the whole ring, so a query for the sum would visit nearly every node, read every row and ship the partial sums back. It would time out long before it finished.

PostgreSQL, on one primary, has the same shape of work but uses an index and a parallel scan, and it often finishes in a second or two for millions of rows. Cassandra is designed to avoid that kind of query.

My answer is to build the sum table and update it as each event arrives, so a read is one row. A counter table fits when small errors are tolerable, as below. When exactness matters, a stream job (Flink or Kafka Streams) writes the total from events.

maintained sumruns offline
-- illustrative
UPDATE revenue_by_day SET cents = cents + 1850
WHERE restaurant_id = 12 AND day = '2026-11-23';
-- read: one row, one partition

Q28. "How does pagination work, and why is there no OFFSET?"

Reveal answer

Strong answer Cassandra pages by position, not by count. The driver asks for a page (fetch size 20, for instance) and gets a paging state, a bookmark of where the last row was. The next page starts from the bookmark.

OFFSET would make the database read and throw away the skipped rows, and with data on many nodes it cannot know which. So it does not exist.

Picture it Page 2 of an order list.

The setup: Customer 7 has 100 orders. The app shows 20 at a time.

Relational · PostgreSQL

OFFSET skips rows.

pg.sqlruns offline
SELECT * FROM orders
WHERE customer_id = 7
ORDER BY placed_at DESC
LIMIT 20 OFFSET 20;

Cassandra · CQL

Bookmark where the last page ended.

cql.cqlruns offline
SELECT * FROM orders_by_customer
WHERE customer_id = 7
  AND placed_at < '2026-11-20 10:00'
LIMIT 20;
-- or driver paging state

The shift: A row count to skip becomes a position to continue from.

What you see: What the driver hands back.

Java driverruns offline
Statement s = SimpleStatement.newInstance(cql, 7L).setPageSize(20);
ResultSet rs = session.execute(s);
ByteBuffer next = rs.getExecutionInfo().getPagingState();
// send 'next' to the client; resume with s.setPagingState(next)

Why: Each page costs the same, however deep. OFFSET gets slower with depth.

Land it I page with a bookmark, the paging state or the last clustering value, never with OFFSET.

Likely follow-ups
"Can I jump to page 50?"

Not directly. To reach page 50 you read pages 1 to 49 first, because the start of each page is the bookmark from the end of the one before.

PostgreSQL lets you write OFFSET 980 LIMIT 20, but the database still reads and throws away the first 980 rows, so deep pages get slower on every system. Cassandra declines, since the rows sit on many nodes and no node knows how many came before.

So I change the screen, not the database. A feed with next and previous buttons works well: I keep the paging state of each page in the browser session, so Previous reuses the one I stored. For a numbered pager, I store the bookmark of each page the user has visited, and let them jump only to those.

If someone truly needs random access to row 10,000, I question the requirement. Search results beyond the first few pages are rarely used, and a search or filter box serves people better.

"Can the paging state change between releases?"

It can, so I treat it as opaque and short-lived. The paging state is a blob of bytes the server gives the driver: it records where the last row was and a few details of the query. The client hands it back unchanged to get the next page.

I never parse it, and I never store it for later. Its format can change with a server version, and the drivers say it is only valid for the same query.

In PostgreSQL the nearest idea is a cursor, or keyset pagination, where I save the last seen value myself. A cursor lives inside one connection and transaction, so it does not work across web requests either.

For a bookmark that must last, such as a link in an email, I use the last clustering key value. For orders_by_customer that is placed_at and order_id of the last row shown, and the next query asks for rows after them. That is stable across versions.

"How do I page across partitions?"

Across partitions there is no natural order, so I split the cases. A background job pages by token, which is the hash of the partition key. A user-facing screen should not page across partitions at all.

The job query below asks for the next 1,000 rows whose partition hash is above the last one seen. It walks the whole table in token order, not business order, so it is right for exports and backfills. I save the last token after each page so the job can restart.

For a screen, a list that spans partitions means the table is wrong. A PostgreSQL ORDER BY created_at LIMIT 20 works because one index orders every row. Cassandra only orders rows inside a partition. So I build a table that keeps the list in one partition, for example an orders_by_restaurant_day partition for one day, and page within it.

token paging (job)runs offline
-- illustrative
SELECT customer_id, placed_at, order_id FROM orders_by_customer
WHERE token(customer_id) > ? LIMIT 1000;
-- ? = token of the last partition seen on the previous page
"Does LIMIT page?"

No. They answer different questions. LIMIT sets the most rows the whole query may return. Paging chops the result into pieces of the fetch size, so a big result does not arrive in one huge message.

They combine. With LIMIT 1000 and a fetch size of 100, the driver asks for up to 100 rows at a time and stops after the tenth page, at 1,000 rows. Without LIMIT the query ends only when the data does, or never, if the table is large.

PostgreSQL has the same LIMIT keyword, but there paging is a separate habit: you add OFFSET, or keyset conditions, to each query. Cassandra's driver does paging for you, and the server tracks where each page stops.

A trap: a small LIMIT does not make a bad query cheap. LIMIT 20 on a query that must scan many partitions to find 20 matches still touches many nodes. I use LIMIT to match what the screen shows, and I keep the partition key in the query so it stays one read.

Q29 · Scenario. "Choose between a secondary index, SAI, a materialized view and a hand-built table."

Reveal answer

Strong answer Hand-built table: fastest and predictable reads, I own the writes. Default for hot paths. SAI (5.0): attached to the table, supports more operators, good for moderate queries; still fans out without a partition key. Legacy secondary index: works on small, low-cardinality data only. Materialized view: Cassandra maintains the copy, but it is experimental, off by default and not recommended for production.

My order: table first; SAI when a query is rare or combined with a partition key; others avoid.

Picture it One question served four ways.

The setup: Query: customers by city.

Relational · PostgreSQL

CREATE INDEX or a view.

pg.sqlruns offline
CREATE INDEX ON customers(city);
-- or
CREATE MATERIALIZED VIEW c_city AS
 SELECT * FROM customers;

Cassandra · CQL

Table, SAI, or avoid the rest.

cql.cqlruns offline
-- hot path: own table
CREATE TABLE customers_by_city (...);
-- light use: SAI
CREATE INDEX ON customers (city)
 USING 'sai';

The shift: In SQL the database maintains indexes. In Cassandra I choose who maintains the extra path.

What you see: The choice.

Which to pick
OptionPick it whenCost or catch
Hand-built tablehot, predictable readyou write every copy
SAImoderate or rare queriesstill queries many nodes
Secondary indextiny, rare lookupsfans out, weak at scale
Materialized viewexperimentation onlyexperimental, avoid in production

Why: The more automatic the option, the less control I have over cost.

Land it I build a table for hot reads, use SAI for lighter ones, and avoid legacy indexes and views.

Likely follow-ups
"Why was the view disliked?"

Because the copy was fragile when something went wrong, and the cost to fix it fell on the people running the cluster. A materialized view is a table Cassandra keeps in step with a base table, automatically, through a hidden write path.

The trouble came under failure. If a replica missed a base-table write and later got repaired, the view could end up differing from the base, and repair did not always fix it. The project marked views experimental and off by default. In recent versions, check the docs for current status.

PostgreSQL materialized views work differently: they are snapshots you refresh on demand with REFRESH MATERIALIZED VIEW, and they sit on one node. That is not the same promise, and not the same risk.

My practice is to write the second table myself, in a logged batch with the first. It costs more code, but I control the order and the retries, and I can see what happens when it fails.

"Does SAI replace tables?"

No. SAI gives extra ways to ask questions of a table, and it does not take the place of a table designed for a hot query.

Compare the two on one query: orders for a restaurant on a day. The table orders_by_restaurant_day finds the partition by hashing the key and reads rows in time order from one replica set. An SAI index on restaurant_id would instead consult an index on each node that may hold matches, then merge, which is fan-out. If the partition key is not in the query, the number of nodes asked grows with the cluster.

PostgreSQL has one tool here, the B-tree index, and it works because there is only one node to ask. In a cluster, that same easy index becomes a cost on every node.

So I look at the query's rate. Hot and user-facing: a table. Rare, internal, or one that also fixes the partition key: SAI is a good fit and saves me a whole copy of the data.

"Can SAI handle ranges?"

Yes, within limits. SAI is built to support equality and range conditions on numbers and dates, and it also does text matching. It can combine several indexed columns in one WHERE clause. The exact list of operators grows by release, so I check the 5.0 docs before promising a particular one.

The old legacy secondary index could only do equality. Cassandra 5.0 SAI is the one that adds ranges, so a query like the one below is possible.

A catch is the one I already named: the query below is fine because it also fixes the partition key, customer_id = 7, so only one replica set is asked. Drop that condition and the range total >= 20 must be answered across the ring.

In PostgreSQL I would write the same query and add a B-tree index on (customer_id, total). In Cassandra the first column is already the partition key, so the SAI index only needs to cover the range inside that partition.

SAI rangeruns offline
-- illustrative
CREATE INDEX ON orders_by_customer (total) USING 'sai';
SELECT * FROM orders_by_customer
WHERE customer_id = 7 AND total >= 20 AND total <= 50;
"How do I test SAI?"

I test it on production-sized data, because an index that is fast on 10,000 rows can behave quite differently on 4 billion.

  1. Data: load a copy of production-sized data with the real distribution of values, not random filler. A column where 80% of rows share one value indexes very differently from an even one.
  2. Queries: replay a realistic mix of queries, including the slow and rare ones, at the real rate.
  3. Measure: watch p99 latency (the slowest 1% of requests), node CPU, disk used by the index files, and the write slowdown on the table.

I compare these numbers against the same test with the hand-built table. If SAI meets the target with room to spare, I keep it. If p99 climbs as I add nodes, that is the fan-out showing, and I build a table instead.

Q30 · Design. "Model orders with line items, as PostgreSQL would have orders and order_items."

Reveal answer

Strong answer Two reads matter: the order header with items (the order page) and a customer's order list. Header and items go together in one partition keyed by order id. The list is a separate table of summaries.

In the order partition, a static column carries the header and clustering rows carry the items.

Picture it Order 42 with three items.

The setup: An order of three dishes. The order page shows header and items together.

Relational · PostgreSQL

Two tables and a join.

pg.sqlruns offline
SELECT * FROM orders o
JOIN order_items i
  ON i.order_id = o.order_id
WHERE o.order_id = 42;

Cassandra · CQL

One partition per order.

cql.cqlruns offline
CREATE TABLE orders_by_id (
  order_id bigint, item_no int,
  status text STATIC, total decimal STATIC,
  name text, qty int,
  PRIMARY KEY ((order_id), item_no));

The shift: The parent becomes static columns and the children become rows.

What you see: One read returns everything.

partition 42runs offline
# illustrative output
status  total | item_no name    qty
PLACED  18.50 | 1       Paneer  2
PLACED  18.50 | 2       Naan    4
PLACED  18.50 | 3       Lassi   1

Why: The order page needs one read of one partition.

Land it I put the header as static columns and the items as rows in one partition keyed by the order.

Likely follow-ups
"What about the customer's order list?"

A separate table, orders_by_customer, keyed by customer, with one summary row per order. The primary key is ((customer_id), placed_at DESC, order_id), so a customer's orders sit together, newest first.

The row holds only what the list screen shows: order id, time, status, total and the restaurant name copied at order time. The big detail, the lines of the order, lives in the order-detail partition and is read only when someone opens one order.

In PostgreSQL I would join orders to restaurants and sort by placed_at with an index. Cassandra has no join, so the restaurant name is copied into every summary row. That duplication is the price of reading one partition.

Small rows matter. A list of 20 orders at about 200 bytes each is 4 KB, so the whole screen is one short read. If each row carried every line item, the same screen would read 20 times more bytes to show the same thing.

"How do I change the status?"

A status change must be written to every table that stores the status: the detail table, plus each list table that has a summary row. I write them in one logged batch so they all apply eventually, even if the coordinator dies in the middle.

In PostgreSQL this is one UPDATE orders SET status = ... WHERE id = 42, because there is one copy. Cassandra has one copy per query, so the statement count grows with copies.

The summary row has a full primary key, so I must know customer_id, placed_at and order_id to address it. The service that changes status therefore receives or reads those values first. A batch of two or three small statements is far below the 5 KiB warning size.

Readers may briefly see the detail table updated and the list not, because a batch is atomic but not isolated. For a status label, that is fine, and the next refresh fixes it.

status updateruns offline
-- illustrative
BEGIN BATCH
  UPDATE orders_by_id SET status = 'PREPARING' WHERE order_id = 42;
  UPDATE orders_by_customer SET status = 'PREPARING'
    WHERE customer_id = 7 AND placed_at = '2026-11-23 19:02:00' AND order_id = 42;
APPLY BATCH;
"Is a collection of items an option?"

Yes, it is an option, and it trades update cost for simplicity. A list<frozen<item>> stores every item as one value inside the order row. A frozen user-defined type means the whole item is written and read as one unit.

Reading is simple: one row holds the whole order, with no clustering rows to page through. Writing is where it hurts. Changing one line, for example a quantity from 1 to 2, means rewriting the full list, and the old list is overwritten as one cell. Also, appending to a list is not idempotent, so a retry could add an item twice.

PostgreSQL's closest tool is a jsonb column of items. It has the same appeal and the same drawback: updating one element rewrites the whole value.

My rule: if items never change after the order is placed and the count stays small (say under 50), a frozen list is acceptable and shorter to code. If I update single items, or the count can grow large, I use one clustering row per item.

"How big is the partition?"

Small, a few kilobytes for a normal order. I estimate it before choosing, using assumptions that I state.

A normal order has about 8 items. Each item row stores a line number, name, quantity and price, about 100 bytes. The static header adds perhaps 200 bytes. That gives 8 × 100 + 200 = 1,000 bytes, so about 1 KB, plus overhead.

A large catering order with 5,000 items would be about 5,000 × 100 = 500 KB. That is still far below the guideline of roughly 100 MB or 100,000 rows per partition. So one partition per order is safe, and I do not need a bucket.

The check matters because a partition grows with its key. The key here is the order id, and an order does not keep growing after it is placed, so the size is bounded by the order itself. Contrast this with a partition keyed only by restaurant, where each new order adds rows forever. That one would need a day bucket.

size estimateruns offline
# illustrative
normal : 8 items x 100 B + 200 B header = about 1 KB
catering: 5,000 items x 100 B + 200 B = about 500 KB
guideline: stay under about 100 MB and 100,000 rows
Drill · Writes, ids and nulls

These questions test what upserts, ids and nulls do to a data model.

Q31. "What is an upsert in Cassandra, and how does it change how you write code?"

Reveal answer

Strong answer Every write in Cassandra is an upsert. INSERT and UPDATE both mean: set these columns for this primary key, creating the row if it is missing. There is no error for "row already exists" or "row not found".

That makes writes fast, because nothing is read first. It also means code must not rely on an insert failing. If two writers write the same key, the one with the later timestamp wins.

Picture it One order row written twice.

The setup: Order 42 is inserted, then a bug inserts it again with a new total.

Relational · PostgreSQL

The second insert fails.

pg.sqlruns offline
INSERT INTO orders (order_id, total)
VALUES (42, 18.50);
INSERT INTO orders (order_id, total)
VALUES (42, 99.00);
-- ERROR: duplicate key

Cassandra · CQL

The second insert silently overwrites.

cql.cqlruns offline
INSERT INTO orders_by_id (order_id, total)
VALUES (42, 18.50);
INSERT INTO orders_by_id (order_id, total)
VALUES (42, 99.00);
-- both succeed, total is now 99.00

The shift: Relational protects against overwrites. Cassandra makes overwriting the normal path.

What you see: The row afterwards.

resultruns offline
# illustrative output
order_id | total
42       | 99.00      <- last write (higher timestamp) wins

Why: Safe retries are a gift: writing the same row twice gives the same state. Surprise overwrites are the price.

Land it I say every write is an upsert, so retries are safe but duplicates are silent, and I use IF NOT EXISTS where duplicates matter.

Likely follow-ups
"How does last write wins decide?"

By comparing timestamps, cell by cell. Every column value (a cell) is stored with a write timestamp in microseconds. When two replicas hold different values for the same cell, Cassandra keeps the one with the higher timestamp. If the timestamps tie, it picks one by comparing the values, so the result is still the same on every replica.

The weak point is the clock. The timestamp comes from the client driver or the coordinator, depending on configuration, so two machines with clocks 5 ms apart can order two writes the wrong way round, as in the sketch below.

PostgreSQL does not have this problem inside one primary: its transactions and locks decide the order, and the second writer waits or fails. Cassandra has no waiting, so the clock decides.

My practice: keep servers synchronised with NTP, avoid last-write-wins for values where order is critical, and use IF conditions or separate rows (one per event) when two writers might meet.

two writesruns offline
# illustrative
server A clock +0 ms : write total=18.50 at t=1000
server B clock -5 ms : write total=99.00 at t= 998  (really later)
result               : 18.50 wins
"Is an UPDATE of a missing row an error?"

No, and that is the surprise. UPDATE and INSERT are the same operation, so updating a key that does not exist creates the row, holding only the key and the columns you set.

PostgreSQL behaves differently: UPDATE ... WHERE id = 42 on a missing id changes zero rows and reports UPDATE 0, so the application sees that nothing happened. Cassandra says nothing.

The danger is a typo or a stale id. If a service sends UPDATE orders_by_id SET status = 'READY' WHERE order_id = 4200 and order 4200 never existed, a ghost row appears with a status and no other columns. It may even show up in queries later.

Where the row must exist, I add IF EXISTS, which turns the statement into a conditional write. That uses Paxos and costs about four round trips, so it is slower than a normal write. I use it for sensitive cases, such as changing an order's state, and not for every update.

"Does it change my retry strategy?"

Yes, and the key question is whether doing the write twice leaves the same result.

  1. Full-value writes: an INSERT or UPDATE that sets every column to a fixed value is idempotent. Run it twice and the row is the same. The driver may retry it safely after a timeout.
  2. Counters: cents = cents + 1850 adds on each run, so a retry can double-count. The driver must not retry it blindly.
  3. List appends: tags = tags + ['spicy'] adds another element each time, so it is not idempotent either. A set add, however, is safe.

In the Java driver I mark such statements non-idempotent (setIdempotent(false)), and the retry policy skips them. PostgreSQL clients face the same issue with INSERT without a unique key, but the unique constraint there catches a duplicate. Cassandra does not.

"How do I stop two writers clobbering each other?"

The first rule is to avoid sharing: give each writer its own columns or its own rows. Two services that update different columns of the same row do not collide, because the timestamp is kept per cell. The orders service owns status, while the delivery service owns rider_id.

Where two writers must change the same value, I use a conditional update, so the second writer finds out about the first change. For example, UPDATE ... SET status = 'READY' WHERE ... IF status = 'PREPARING' applies only if the status is still PREPARING, and it returns [applied] = false otherwise.

PostgreSQL gives me SELECT ... FOR UPDATE or an optimistic version column. The Cassandra counterpart is the IF condition, which uses Paxos and takes about four round trips, so I keep it to the few values where a lost update is costly.

Last, I append events rather than overwrite values where the history matters, because two inserts with different keys never overwrite each other.

Q32. "There is no auto-increment in Cassandra. How do you create IDs?"

Reveal answer

Strong answer A counter that every node must agree on would be a bottleneck, so Cassandra offers none. I generate ids on the client: a uuid (random), a timeuuid (time-ordered, unique), or a time-sortable id such as a Snowflake-style 64-bit number.

I choose based on whether I want sort-by-id to mean sort-by-time. A random uuid scatters. A timeuuid orders by creation.

Picture it Messages that must sort by time.

The setup: A chat app creates 5,000 messages a second on many app servers.

Relational · PostgreSQL

A sequence hands out numbers.

pg.sqlruns offline
CREATE TABLE messages (
  msg_id bigserial PRIMARY KEY,
  body text);

Cassandra · CQL

The app generates a timeuuid.

cql.cqlruns offline
CREATE TABLE msgs (
  conv_id bigint, msg_id timeuuid,
  body text,
  PRIMARY KEY ((conv_id), msg_id));
INSERT INTO msgs (conv_id, msg_id, body)
VALUES (9, now(), 'hi');

The shift: A central counter becomes a locally generated, globally unique id.

What you see: Two messages in the same millisecond still differ.

timeuuidruns offline
# illustrative output
3f1c8a10-... (time part 19:02:11.004)
3f1c8a11-... (time part 19:02:11.004, different node bits)

Why: No coordination is needed, and the id sorts by time.

Land it I generate ids in the client, using timeuuid when order matters and uuid when it does not.

Likely follow-ups
"Which is better, uuid or Snowflake-style?"

A random uuid is the simplest choice, and a 64-bit time-based id is the compact choice. They answer different pressures.

A random uuid (version 4) is 16 bytes, needs no setup, and can be generated anywhere. It does not sort by time, so using it as a clustering column gives no useful order. For a partition key that does not matter, because the hash scatters keys anyway.

A Snowflake-style id is a 64-bit number made of a timestamp, a worker number and a sequence, so it fits Cassandra's bigint and sorts by creation time. It needs a scheme that gives every worker a distinct number, and a clock that does not run backwards.

At one billion rows, the 8-byte id saves 8 bytes per copy, which is about 8 GB per table copy, and with denormalised copies it multiplies. I take the uuid by default and switch to the compact id when row size at that scale is a real cost.

"Is timeuuid unique?"

Yes, in practice. A timeuuid is 128 bits laid out as a version-1 uuid. It carries a 60-bit timestamp counted in 100-nanosecond steps, a clock sequence, and 48 bits that identify the node that made it.

Two ids made in the same millisecond on different nodes differ in the node bits. Two made on one node in the same 100 ns tick differ through the clock sequence, and CQL's now() takes care of the details.

This is different from an auto-increment column in PostgreSQL (bigserial), where one sequence on one server hands out numbers one at a time. Cassandra has no such central place, which is why every node can create unique ids on its own.

Uniqueness is not a promise I rely on blindly. If the node identity is copied between machines, or clocks go wrong, collisions are possible, which is why the driver library, not hand-built code, should create these ids.

"Can I get the time from a timeuuid?"

Yes. A timeuuid holds its creation time, and CQL has functions to read it and to build bounds around it.

toTimestamp(msg_id) returns the time as a timestamp. minTimeuuid('...') and maxTimeuuid('...') produce the smallest and largest timeuuid for a given moment, which lets me do a range query by time on a timeuuid clustering column.

This replaces a pair of columns in PostgreSQL, such as id bigserial and created_at timestamptz, with one column. The id is both the unique key and the sort key, so a table msgs with PRIMARY KEY ((conv_id), msg_id) returns messages in time order without a separate time column.

One caution: two messages in the same millisecond have different timeuuids but compare in a fixed order that is not meaningful. So I do not read ordering finer than a millisecond as real order.

range by timeruns offline
-- illustrative
SELECT * FROM msgs WHERE conv_id = 9
  AND msg_id > minTimeuuid('2026-11-23 00:00+0000')
  AND msg_id < maxTimeuuid('2026-11-24 00:00+0000');
"Why avoid a counter column for ids?"

Because a counter is the wrong tool for identity. In Cassandra a counter column is a special type with three limits that matter here.

A counter table can hold only counter columns beside its key, so I cannot store a normal row next to it. Counter updates are not idempotent, so a retried increment can skip a number or give the same number to two callers. And reading the next value means a read of the counter across replicas, which is slower than creating an id locally.

Think of what an id needs: uniqueness. Gaps do not matter, since nobody checks that order 41 follows order 40. A locally generated uuid or timeuuid is unique with no coordination, no read, and no single hot row that every writer touches.

The hot row is the real killer. One counter row that all order creation increments would be a single partition on one replica set, receiving every write in the system. That is the bottleneck Cassandra was built to avoid, so I do not recreate it.

Q33 · Scenario. "Our table has 40 columns and the app inserts NULL for the ones it does not have. Reads got slower and we see tombstone warnings. Why?"

Reveal answer

Strong answer Writing an explicit NULL does not skip the column. It writes a tombstone (a delete marker) for that cell. 30 nulls per row across millions of rows is millions of markers to read past.

The fix is to leave the column out of the INSERT, or bind it as unset in the driver.

Picture it The same insert with and without NULLs.

The setup: An order has 10 filled columns and 30 optional ones.

Relational · PostgreSQL

NULL stores nothing special.

pg.sqlruns offline
INSERT INTO orders (id, note, coupon)
VALUES (42, NULL, NULL);
-- NULL is a flag in the row

Cassandra · CQL

NULL writes a tombstone.

cql.cqlruns offline
INSERT INTO orders (id, note, coupon)
VALUES (42, null, null);
-- ❌ TRAP: two tombstones
INSERT INTO orders (id)
VALUES (42);   -- ✅ nothing written

The shift: A missing value is free in SQL and has a price in CQL if written as null.

What you see: The warning.

logruns offline
# illustrative output
WARN Read 5200 live rows and 31000 tombstone cells for query ... (see tombstone_warn_threshold)

The fix: Use unset values in the driver.

Javaruns offline
BoundStatement b = ps.bind().setLong("id", 42L); // note and coupon stay unset

Why: Unset leaves the old value alone and writes no marker.

Land it I leave out the columns I do not have, because explicit nulls write tombstones.

Likely follow-ups
"What is the threshold?"

Warn at 1,000 and fail at 100,000 tombstones read by one query, by default. A tombstone is the delete marker Cassandra writes for a delete or an explicit NULL.

When a query reads more than 1,000 tombstones, the node writes a warning to its log. When it passes 100,000, the node aborts the query with a TombstoneOverwhelmingException and the client sees an error. Both numbers are settings in cassandra.yaml, so they can be tuned, but raising them hides the symptom without fixing the cause.

Compare with PostgreSQL, where deleted rows leave dead tuples that VACUUM cleans, and a query does slow down, but there is no hard abort. Cassandra aborts to protect the node from reading millions of markers into memory.

The numbers fit the scenario: a row with 30 explicit nulls leaves 30 tombstones, so 34 such rows read in one query pass the warning, and about 3,300 rows pass the failure limit.

thresholdsruns offline
# illustrative
tombstone_warn_threshold: 1000
tombstone_failure_threshold: 100000
"Can an unset value overwrite an old value?"

No. An unset value means this column is not part of the statement, so Cassandra does nothing to it. The old value, if there is one, stays exactly as it was, and no tombstone is written.

This differs from NULL, which means set this column to nothing: it deletes the value and writes a tombstone. In the Java driver 4.x, a bound statement leaves a parameter unset until you set it, and it is only an explicit setToNull that sends NULL. Older code that passed null for every field is the usual cause of this scenario.

PostgreSQL has no equivalent distinction in a plain INSERT: omitting a column gives its default, and NULL is a stored value that costs almost nothing. In Cassandra, NULL costs a marker, and unset costs nothing.

This also makes partial updates easy. A profile edit that changes only the phone number sets phone and leaves the 39 other columns unset, so the statement is small and cannot overwrite a value another writer changed a moment ago.

"How do we clean what already exists?"

Wait for expiry and compaction, or rewrite the data without nulls. The tombstones are already written, so I cannot remove them directly.

A tombstone may be dropped only when two things are true: it is older than gc_grace_seconds (10 days by default), and a compaction merges the SSTable files that contain it. Until both happen, reads still walk past the markers.

With 10 days of grace, even a fixed application keeps showing warnings for at least that long, so I tell the team in advance.

If I cannot wait, I take the quicker route: copy the rows into a new table without the nulls (a backfill, the same path as any other table change), switch reads, and drop the old table. Dropping a table removes its files at once. I avoid lowering gc_grace_seconds to speed things up, because repair needs that window to stop deleted data from coming back.

"Does the same happen with empty collections?"

Yes, nearly. Writing an empty collection, or overwriting a collection with a new value, can write a tombstone for the old content, so a column of empty lists or sets behaves like a column of nulls.

The detail: when I set a whole collection (tags = ['a','b']), Cassandra first writes a tombstone that covers the old collection, then the new elements. Appending (tags = tags + ['c']) writes no such marker. An insert with an empty collection writes just the marker.

A row with no tags should therefore leave the column out of the INSERT. When the app reads, a missing collection and an empty one look the same, since the driver returns an empty collection either way.

PostgreSQL has the same wish for an array column, but there an empty array '{}' is a stored value with no extra cost. In Cassandra the difference is real, so I make the rule 'absent means empty' and keep to it.

Q34. "Which data types do you choose for money, time and ids, and why?"

Reveal answer

Strong answer Money: decimal, or an integer in the smallest unit (cents), never a float. Time: timestamp for points in time, date for a calendar day, timeuuid where I need unique and ordered. Ids: uuid, timeuuid or bigint. Text: text.

Types matter more than in SQL because key columns are sorted by type and cannot be changed later.

Picture it The same row in both.

The setup: An order total of 18.50, a time and an id.

Relational · PostgreSQL

numeric and timestamptz.

pg.sqlruns offline
total numeric(10,2),
placed_at timestamptz,
order_id bigserial

Cassandra · CQL

decimal, timestamp, timeuuid.

cql.cqlruns offline
total decimal,
placed_at timestamp,
order_id timeuuid

The shift: Same ideas, different names, and key types are permanent.

What you see: Why not float.

float trapruns offline
0.1 + 0.2 = 0.30000000000000004   (float)
decimal 0.1 + 0.2 = 0.3

Why: A float cannot hold 0.1 exactly.

Land it I use decimal or integer cents for money, timestamp or date for time, and I choose key types carefully because they cannot change.

Likely follow-ups
"Can I change a column type later?"

Only a few changes, and never to the type of a key column. Cassandra lets me add a column, drop a normal column, and rename a key column. Changing the type of an existing column is almost entirely ruled out in recent versions, so I check the docs for the one I run.

The reason is how data is stored. The partition key is hashed and the clustering columns are sorted by type, so a new type would make every stored hash or sort order wrong.

PostgreSQL can do ALTER TABLE orders ALTER COLUMN total TYPE numeric(12,2). For many changes it rewrites the table under a lock, which is slow on a big table but allowed.

My answer to a type mistake is the usual path in Cassandra: create a new table with the right types, backfill from the old one, switch reads, then drop the old. That is why I pick key types with care at the start.

"Is timestamp stored in UTC?"

Yes. A timestamp is a single point in time, stored as the number of milliseconds since 1 January 1970 UTC. It carries no time zone. The zone is a question of display, which belongs to the application.

When a client sends '2026-11-23 19:02:00+0530', Cassandra converts it to UTC milliseconds. When it reads it back, the driver gives the same instant in whatever zone the client chooses. In Java 4.x it arrives as an Instant, which is always UTC.

Compare with PostgreSQL's timestamptz: it also stores UTC, and converts on input and output using the session's TimeZone. The behaviour is similar, but PostgreSQL has the extra type timestamp (without zone), which is a known source of bugs. Cassandra has no such twin.

The risk is a day bucket. 'Orders on 23 November' in Mumbai starts at 18:30 UTC on the 22nd. If the bucket is computed in UTC in one service and local time in another, an order lands in two different partitions. I fix the rule once: buckets use UTC.

"Why date for the bucket?"

Because a day bucket is a calendar day, not an instant, and date says that exactly. The type stores a day count in 4 bytes, sorts correctly as a clustering or key column, and prints as 2026-11-23, which makes the key easy to read in cqlsh.

Compare the other choices for the same bucket. A timestamp takes 8 bytes and invites questions: which time of day, which zone? A text such as '2026-11-23' sorts correctly because the format is ordered, but it takes 10 bytes and lets a typo like '2026-1-23' in. A bigint like 20261123 is compact but unreadable when you debug.

At 10,000 partitions a day, the key is not a big saving in size. The bigger win is correctness: the compiler and the driver reject a bad value.

I pick one type, document it, and use it in every table and every service. A key whose bucket is stored as date in one table and text in another turns every cross-table lookup into a conversion bug.

"What about enums?"

There is no enum type, so I choose between two options. The one I use is text with validated values; the other is a small integer code.

With text, a status is stored as 'PLACED', 'PREPARING', 'DELIVERED'. It is readable in cqlsh and in logs. The app holds an enum and rejects anything else before writing. The cost is a few bytes per row: about 9 bytes for 'PREPARING' against 2 for a smallint.

With a smallint code, rows are compact, but a person reading a table sees 3 and must look it up. Mixing meanings between services is easier too.

PostgreSQL has CREATE TYPE status AS ENUM (...) and a CHECK constraint, so the database itself refuses a bad value. Cassandra cannot, so the rule lives in the application. I keep the list of values in one shared library, and I treat a new status as a deploy that every reader must handle, since old code meets new values.

Q35. "If you duplicate data, do you ever keep a normalised source of truth?"

Reveal answer

Strong answer Yes, and I recommend it. One table is the source of truth, usually keyed by the entity id. The query tables are derived copies. If a copy is wrong, I can rebuild it from the source.

That gives a clear rule: updates go to the source first, then fan out to copies.

Picture it Orders by id as the master, lists as copies.

The setup: orders_by_id holds the full order. Three list tables hold summaries.

Relational · PostgreSQL

The normalised tables are the truth.

pg.sqlruns offline
CREATE TABLE orders (
  order_id bigint PRIMARY KEY,
  customer_id bigint,
  total numeric(10,2));
CREATE VIEW customer_orders AS
  SELECT customer_id, order_id, total
  FROM orders;
-- views derive from the tables

Cassandra · CQL

One table is the master.

cql.cqlruns offline
orders_by_id        -- master, full row
orders_by_customer -- derived summary
orders_by_restaurant_day -- derived summary

The shift: Relational has one set of tables. Cassandra has one master and several derived views you maintain.

What you see: Rebuild path.

backfillruns offline
scan orders_by_id -> rewrite orders_by_customer rows
              -> rewrite orders_by_restaurant_day rows

Why: A bug in a copy is fixed by replaying from the master.

Land it I name one table as the master and treat the others as rebuildable copies.

Likely follow-ups
"How do you scan the master?"

I read the master in pieces and write each copy from it. The loop is safe to repeat because every write is an upsert.

  1. Split: divide the token ring into ranges, for example 256 pieces, so each piece is a small, restartable unit of work.
  2. Read: for each range, read the master rows with a query on token(order_id), and page through them.
  3. Write: write each row to every copy table. Writing twice gives the same row, so a crash and a restart does no harm.
  4. Throttle: limit the rate so live traffic is not hurt, and record which ranges finished.

If the writes originally came from a log such as Kafka, I can replay the log instead of scanning the table.

backfill loop (sketch)runs offline
# illustrative
for range in token_ranges:
    rows = read(orders_by_id, range)
    write(orders_by_customer, rows)        # upserts, safe to repeat
    write(orders_by_restaurant_day, rows)
    mark_done(range)
"Why events?"

Because a log keeps every change, in order, so I can rebuild any copy from the start without reading the master at all. A table shows only the latest state. A log shows how it got there.

Say next month's screen needs a copy keyed by a different column. With tables only, I scan the master and transform each row. With Kafka, I start a new consumer at the beginning, and it builds the new table as it reads, then keeps it up to date, so there is no separate backfill to reconcile with live writes.

PostgreSQL's write-ahead log is a similar idea, but it is made for replicas, not for daily replays.

This is a strong reason to make the log the source of truth when there are many copies. One caution: topics expire data (7 days by default in Kafka), so for a full rebuild I keep the topic long enough or take snapshots. The Kafka chapter covers the outbox pattern that makes the write and the event atomic.

"Does the master need to be a Cassandra table?"

No, and often it should not be. The master can be a PostgreSQL table, with Cassandra holding read-optimised copies that are fed from it.

Here is the flow. The order service writes the order to PostgreSQL in a transaction, together with an outbox row. A relay publishes the event to Kafka, and a consumer writes orders_by_customer and orders_by_restaurant_day in Cassandra. If a copy goes wrong, I replay the events or re-read PostgreSQL.

This gives me what each system is best at. PostgreSQL has constraints, joins and transactions, so the rules and the truth stay there. Cassandra has cheap, fast reads and writes at high volume, so the screens come from there.

The cost is two systems to run and a delay between them, usually seconds. I accept that when the read volume or the availability need justifies it. If the system is small, one PostgreSQL with good indexes is simpler and I would stop there.

"What if the master and copy disagree?"

The master wins. I overwrite the copy from it. Because every write is an upsert, rewriting the copy from the master is safe to repeat.

The harder question is how I find out. Copies drift for ordinary reasons, such as a consumer that was down or a bug that skipped a field, and nothing in Cassandra checks them.

So I run a comparison job on a sample. Every night it picks, say, 10,000 random order ids, reads the master and each copy, and compares the fields the copy keeps. It reports the share that differ. A rate near zero is normal. A rate that jumps tells me a bug shipped, before customers see wrong data.

For the rows that differ, a repair job rewrites the copy from the master. PostgreSQL has no such issue with a single copy; this is the price of the duplicated reads.

drift check (sketch)runs offline
# illustrative
sample 10,000 order ids
for each id: read master row, read copy row, compare shown fields
report: drift rate (differing / sampled); alert above a threshold
Drill · Types, copies and change

These questions test types, source of truth, schema change and batches.

Q36 · Scenario. "Product asks for a new screen next month that our tables cannot serve. What do you do?"

Reveal answer

Strong answer Add a table. I write the new query into the access-pattern list, design the table, deploy it, dual-write new data, backfill old data, switch the reads on, and only then think of removing anything.

Altering a primary key is not possible, so changing a query means a new table, not an ALTER.

Picture it Adding 'orders by status' next to existing tables.

The setup: The ops team wants all orders in PREPARING for restaurant 12.

Relational · PostgreSQL

CREATE INDEX or just a WHERE.

pg.sqlruns offline
CREATE INDEX ON orders (status);
SELECT * FROM orders
WHERE status = 'PREPARING';

Cassandra · CQL

New table, dual write, backfill.

cql.cqlruns offline
CREATE TABLE open_orders_by_rest (
  restaurant_id bigint, status text,
  placed_at timestamp, order_id bigint,
  PRIMARY KEY ((restaurant_id, status),
               placed_at, order_id));

The shift: A new question is a schema change in SQL and a new table in CQL.

What you see: The steps.

  1. Create: the new table.
  2. Dual write: application writes old and new.
  3. Backfill: copy old rows from the master.
  4. Switch reads: then retire the old path.

Why: There is no downtime and every step can be rolled back.

Land it I add a new table, dual-write, backfill and switch reads.

Likely follow-ups
"How do you backfill safely?"

A backfill is a copy job, and I make it safe in three ways: gentle, restartable and repeatable.

  1. Gentle: I read the master in token ranges and cap the write rate, for example 2,000 writes per second, so live traffic is not hurt.
  2. Restartable: after each range finishes I save its number in a small progress table, so a crash resumes at the next range and not at the start.
  3. Repeatable: each write is an upsert, so writing a row twice leaves the same row. The job needs no cleanup after a failure.

I also write each row with a single-partition statement, not a large batch, since a batch of many partitions loads one coordinator. Then I check the result: count rows in a sample of ranges on both tables, and compare fields for a few thousand random keys. In PostgreSQL the same job would be one INSERT ... SELECT, which works because one server sees all the data. Cassandra has to do it in pieces.

throttle (plan)runs offline
# illustrative
range size : 1/256 of the ring
rate limit : 2,000 writes per second
progress   : saved per range in a small table
check      : sample counts and field compare
"What if backfill and live writes meet?"

Both write the same row, and the newer timestamp wins. That is what makes the overlap safe, if I order things correctly.

A given row can be written twice: once by the live path with today's value, and once by the backfill, which read an older version from the master.

The danger is the backfill writing a stale value on top of a newer one. Last-write-wins decides by timestamp. If the backfill reuses the row's original write time (USING TIMESTAMP), the older value carries an old timestamp and loses. If it writes with the current time, it can wrongly win.

So I start dual writes first, then run the backfill, and I write backfilled rows with the timestamp of the source data where I can. A live update is newer than anything history can offer, so the live value survives.

"Can ALTER TABLE ADD COLUMN help?"

Yes. Adding a column is cheap, online and does not rewrite any data. The column is added to the table's schema, and old rows read null for it.

This is similar in effect to PostgreSQL, where ALTER TABLE ADD COLUMN without a default is also quick.

So if the new screen only needs one more field per row, for example a delivery_note on orders_by_customer, I add the column, write it for new orders, and the screen shows blank for old ones. No new table.

But a change to the primary key is not possible. If the screen needs a different partition key or sort order, no ALTER helps, and the answer is a new table, with the dual write and backfill. I decide which of the two cases I have by asking: does the way I find or order the rows change?

"Does this cost storage?"

Yes, one more copy of the data, and I accept the cost in return for a fast read. The size is simple to estimate, so I do it before agreeing.

Take an assumption: the new table holds a summary of 200 bytes for each of 50 million orders. That is 10 GB of data. With replication factor 3, the cluster stores three replicas, so 30 GB, plus overhead for indexes and the commit log. I compare that with the cluster's free disk, which should stay under about 50% full so compaction has room.

PostgreSQL pays the same disk price when you add an index on a new column, only once instead of three times. The overlap of old and new paths is short, so I drop the old table once reads have moved, and the extra space comes back.

Q37 · Scenario. "A status change must update three copies of an order. How do you keep them in step?"

Reveal answer

Strong answer I write the three updates in a logged batch. The batch is written first to a batch log on other nodes, so even if the coordinator dies, the writes are replayed. All three eventually apply (atomic), but they are not isolated: a reader can briefly see one new and one old.

For keys that live in different partitions, this is the right tool. It is not for bulk loading.

Picture it A change from PLACED to PREPARING.

The setup: Order 42 exists in orders_by_customer, orders_by_id and orders_by_restaurant_day.

Relational · PostgreSQL

One transaction updates one row.

pg.sqlruns offline
UPDATE orders SET status = 'PREPARING'
WHERE order_id = 42;
COMMIT;

Cassandra · CQL

A logged batch updates every copy.

cql.cqlruns offline
BEGIN BATCH
 UPDATE orders_by_id SET status='PREPARING'
  WHERE order_id=42;
 UPDATE orders_by_customer ... ;
 UPDATE orders_by_restaurant_day ... ;
APPLY BATCH;

The shift: The transaction is replaced by a promise that all writes will happen.

What you see: What a reader may see.

timelineruns offline
t0 batch accepted (logged)
t1 orders_by_id updated
t2 reader sees new status here, old status in list
t3 all three updated

Why: For a few ms the copies differ. The screen can tolerate it.

Land it I use a logged batch to keep copies in step: all apply eventually, with no isolation.

Likely follow-ups
"What does batch size matter?"

Batch size matters because a batch is held in memory and sent as one message, so a large one burdens the coordinator. The defaults are a warning at 5 KiB and a failure at 50 KiB, set in cassandra.yaml. A batch above 50 KiB is rejected.

Three small updates of 200 bytes each are about 600 bytes, so I am far below the line. The limit is not a number to chase upward. If I find myself writing a batch of 100 statements, I am using it as a bulk loader, which it is not for.

PostgreSQL has no similar limit on a transaction's statements, because the work is on one server and it can spill to disk. In Cassandra the coordinator and the batch log both carry the batch, so I keep it small: the few statements that keep copies in step.

batch size limitsruns offline
# illustrative
batch_size_warn_threshold: 5KiB
batch_size_fail_threshold: 50KiB
"Is an unlogged batch faster?"

Only when every statement is in one partition, and across partitions it is an anti-pattern. An unlogged batch skips the batch log, which saves the log's extra writes, but it also loses the guarantee that all statements apply if the coordinator dies.

Across partitions, one coordinator must talk to many replica sets and wait for the slowest. That adds load on one node and gives no atomicity. A set of single-partition writes sent in parallel by the driver spreads the work across coordinators, finishes with the speed of the slowest single write, and is usually faster.

So my rule: a logged batch when I need atomicity across tables, a one-partition batch for rows that share a key, and plain parallel writes for bulk work. PostgreSQL's multi-row INSERT is the habit people carry over, and in Cassandra it needs this care.

"How do I deal with a reader seeing mixed states?"

I either read the master for the truth when it matters, or accept the short mismatch when it does not. A batch is atomic but not isolated, so for a few milliseconds one table can show the new status while another shows the old one.

PostgreSQL does not have this problem: a transaction is isolated, so a reader sees either the old state in all tables or the new state in all of them. Cassandra trades that away for availability and scale.

How I decide: for a customer's order list, a few milliseconds of mismatch is not noticed, so I accept it. For a decision that depends on the state, such as refunding an order, I read the master row by key at the strongest consistency I need and act on that, not on a list copy.

"Can the batch partly fail?"

Yes, it can fail in part, and what makes it safe is that it is finished by the cluster. A logged batch is written first to a batch log on two other nodes. Then the coordinator sends the statements to the replicas.

If the coordinator dies after the log is written, one of those nodes notices the batch has not been marked done, and replays it. The statements are idempotent upserts, so replaying a statement that already applied does no harm. All three updates eventually take effect.

What the log cannot do is hide the middle. While the batch runs, a reader can see two copies new and one old.

Compare PostgreSQL: a transaction either commits or rolls back, and nobody sees half of it. The Cassandra batch promises that the whole thing will happen, not that it happens at once. I write the statements so a half-applied state is a valid state that the app can show.

Q38 · Design. "Model a user profile with lookup by id, email and phone."

Reveal answer

Strong answer One master users table keyed by id, and one tiny lookup table each for email and phone. A login reads the lookup to get the id, then the profile.

I keep profile data only in the master, so an edit touches one row, unless the lookup key itself changes.

Picture it Three tables.

The setup: 2 million users. Login by email or phone.

Relational · PostgreSQL

Unique indexes on one table.

pg.sqlruns offline
CREATE TABLE users (
  id bigint PRIMARY KEY,
  email text UNIQUE,
  phone text UNIQUE);

Cassandra · CQL

Master plus one lookup per route.

cql.cqlruns offline
users (id) PRIMARY KEY
user_by_email (email) -> id
user_by_phone (phone) -> id

The shift: Each unique index becomes a table.

What you see: The write path for sign-up.

sign-upruns offline
INSERT INTO user_by_email (email, user_id) VALUES ('a@b.com', 1042) IF NOT EXISTS;
INSERT INTO user_by_phone (phone, user_id) VALUES ('+919800', 1042) IF NOT EXISTS;
INSERT INTO users (id, name) VALUES (1042, 'Asha');

Why: The IF NOT EXISTS winners hold the names. The master is written last.

Land it I use one master and one lookup table per route, claiming the unique values with IF NOT EXISTS.

Likely follow-ups
"What if the second IF NOT EXISTS fails?"

I release the first claim by deleting it, and the order of the claims decides how clean that is. The sign-up claims two unique values: the email and the phone. Each claim is a conditional insert, IF NOT EXISTS, into its own lookup table.

Suppose the email claim succeeds and the phone claim fails because that phone belongs to another user. The email row now points to a user who will never exist. I delete it, and I make the delete conditional so I remove only my own claim: IF user_id = 1042. Otherwise a late delete could remove another person's claim, if they claimed the same email in between.

PostgreSQL does this with a UNIQUE constraint on each column and one transaction: if the second insert fails, the whole transaction rolls back and no claim stays. Cassandra has no rollback, so the cleanup is mine.

I put the claim that is likelier to fail first, so most failures cost nothing to undo.

rollback of a claimruns offline
-- illustrative
DELETE FROM user_by_email WHERE email = 'a@b.com' IF user_id = 1042;
"Is it safe if the app crashes in between?"

It is safe if I order the writes carefully and have a cleanup job for the leftovers.

The order is: claim the email, claim the phone, then write the master profile last. A crash at any point leaves some claims and no profile. It never leaves a profile whose unique values another user can take, so a half-made user does not exist.

A claim without a profile is a stale row. It blocks someone from using that email, so a user who retries sign-up sees 'already taken'. The fix is a job that scans the claim tables, reads the profile for each user_id, and removes claims that are older than a safe window with no profile, for instance 10 minutes.

PostgreSQL gives all of this for free with one transaction around three inserts. The same design in Cassandra needs the order, the conditional deletes and the sweeper. If sign-up uniqueness is business-critical and volume is modest, I would keep the users table in PostgreSQL.

"Can I put the profile in the lookup table?"

Yes, but I do not, because every profile change then touches three places. If the lookup tables each hold the whole profile, then a name change means updating the master, the email table and the phone table, usually in a logged batch.

The cost multiplies. A profile of 1 KB stored three times is 3 KB, and a user who edits the name five times a year makes 15 row writes instead of 5. If the user changes their phone number, the phone table's key changes, so the row is deleted and a new one inserted, leaving a tombstone.

In PostgreSQL I would never copy a profile into two index tables, since the index is maintained for me. In Cassandra the lookup tables are the index, and I keep them tiny: key and user_id only. The master has everything else.

"What about a case-insensitive email?"

I store the email in lower case, and I apply the same rule at sign-up and at login. Cassandra compares text exactly, so A@B.com and a@b.com are two different keys. Without a rule, one person could sign up twice and the login of the second spelling would not find them.

PostgreSQL gives me choices: the citext extension, a UNIQUE INDEX ON users (lower(email)), or a nondeterministic collation. All of them let the database do the matching. Cassandra has none of these, so the normalisation moves into the application.

The practical point is a single function, normalizeEmail(), that trims spaces and lowercases, and every code path that writes or reads the lookup calls it. If sign-up and login each did their own version, a difference in one would create accounts nobody could log in to.

Lower-casing the whole address is a pragmatic choice. In theory the part before the @ can be case-sensitive, but in practice mail providers treat it as case-insensitive, and I note that choice in the design.

Q39 · Design. "Model 'live orders for a restaurant today', updated every few minutes."

Reveal answer

Strong answer Key by restaurant and day: ((restaurant_id, day), placed_at, order_id), status as a column. The query reads one partition, the day's orders in time order.

Status changes are updates by the full key, so I need placed_at and order_id on the update path.

Picture it One restaurant on one day.

The setup: Restaurant 12 receives 3,000 orders a day and shows the ones not yet delivered.

Relational · PostgreSQL

WHERE on status and date.

pg.sqlruns offline
SELECT * FROM orders
WHERE restaurant_id = 12
  AND placed_at::date = current_date
  AND status != 'DELIVERED';

Cassandra · CQL

The day is in the key. Status is filtered on screen.

cql.cqlruns offline
SELECT * FROM orders_by_restaurant_day
WHERE restaurant_id = 12
  AND day = '2026-11-23';
-- app drops DELIVERED rows

The shift: SQL filters by status in the database. Here the 3,000 rows are read and filtered by the app.

What you see: Sizes.

math (illustrative)runs offline
3,000 rows x 100 B = 300 KB per partition
read cost: one partition, 300 KB

Why: A small day-partition makes the filter cheap.

Land it I key by restaurant and day, read the day, and filter statuses in the application.

Likely follow-ups
"Why not put status in the key?"

Because status changes, and a key that changes means a delete and an insert. If status is in the key, moving an order from PLACED to PREPARING deletes the row at one address and writes a new row at another.

The cost is tombstones. Take a busy restaurant-day with 3,000 orders, each moving through 4 statuses. That is 3,000 × 4 = 12,000 deletes, and each leaves a tombstone that stays at least gc_grace_seconds (10 days by default). A read of that partition walks past 12,000 markers, well over the warning limit of 1,000.

PostgreSQL has no trouble here. UPDATE orders SET status = 'PREPARING' WHERE id = 42 changes a column, and an index on status is updated for me, and the dead row versions are cleaned by VACUUM.

So I keep status as an ordinary column in the day partition. A day partition of a few thousand rows is cheap to read whole, and the app filters on status.

"What if the day is huge?"

I split the day into smaller pieces by adding an hour to the partition key. A restaurant-day is normally small, but a very busy restaurant could push a single partition toward the guideline of about 100 MB or 100,000 rows.

With an hour bucket, the key becomes ((restaurant_id, day, hour), placed_at, order_id). The cost is that the screen asks for several partitions to show a day.

A screen that shows 'the last three hours' reads three partitions, and the driver can send those three queries in parallel. PostgreSQL would answer the same with one query on an index over (restaurant_id, placed_at), and size would not matter to it.

I do not add the bucket early. I do the size math first: orders per day × bytes per row. If the largest restaurant produces 5,000 orders a day at 300 bytes, that is 1.5 MB, and a day partition is plenty. The hour bucket is for when the numbers say otherwise.

hour bucketruns offline
-- illustrative
PRIMARY KEY ((restaurant_id, day, hour), placed_at, order_id)
"How do I handle midnight?"

I query both days and merge, because a day bucket cuts time at an arbitrary line. Around 00:10 the screen for 'live orders' needs the last hours of yesterday as well, since an order placed at 23:50 may still be open.

The app merges the two lists by time. Two single-partition reads cost little more than one.

The timezone is the usual trap. The bucket is a calendar day, so the question is whose midnight. If the day key is computed in UTC, midnight for a restaurant in Mumbai falls at 05:30 in the morning, in the middle of breakfast service. That is fine, as long as every writer and reader uses the same rule. I make the bucket arithmetic UTC everywhere and put it in one shared function.

PostgreSQL has a plain range query, WHERE placed_at >= now() - interval '6 hours', and bucket boundaries do not exist. Cassandra's buckets are the price of bounded partitions.

"Is it worth a second table for open orders only?"

Often yes, when the open set is much smaller than the day's total. I compare the two designs by their cost.

  1. The day table: holds every order for the day, 3,000 rows, and the app filters out the 150 that are open. Each refresh reads 3,000 rows.
  2. The open table: holds only open orders, with status in the key. Each refresh reads 150 rows, but each status change is a delete and an insert.
  3. The safety net: a TTL on every open row, for example 24 hours, so that a missed delete cannot leave a row forever.

The open table pays in tombstones, so it works only because the set is small and rows leave it quickly. If open orders are a small fraction and the screen refreshes every few seconds across many restaurants, the 20-times smaller read is worth it. If not, I keep one table and filter. In PostgreSQL I would add a partial index with WHERE status != 'DELIVERED' and be done.

Q40. "How do you get the newest rows first, and what is the cost of getting it wrong?"

Reveal answer

Strong answer Choose CLUSTERING ORDER BY (col DESC) at table creation when the main read is newest-first. The newest rows are then at the head of the partition.

If the table is ascending, I can still read newest first with ORDER BY ... DESC, which reads the partition backward, but with LIMIT on a large partition the cost depends on the storage layout, so I choose the order for the common read.

Picture it Latest 20 messages.

The setup: A conversation partition with 10,000 messages.

Relational · PostgreSQL

ORDER BY DESC and an index.

pg.sqlruns offline
SELECT * FROM messages
WHERE conv_id = 9
ORDER BY sent_at DESC LIMIT 20;

Cassandra · CQL

Store DESC and read the head.

cql.cqlruns offline
CREATE TABLE msgs (...,
 PRIMARY KEY ((conv_id), sent_at))
 WITH CLUSTERING ORDER BY (sent_at DESC);
SELECT * FROM msgs WHERE conv_id = 9
LIMIT 20;

The shift: Relational sorts at query time. Cassandra sorts at write time.

What you see: What is read.

readruns offline
# illustrative output
reads the first 20 rows of the partition, then stops

Why: No sort, no scan, and a cheap stop.

Land it I store in the order the main screen reads, so LIMIT 20 reads the head of the partition.

Likely follow-ups
"Can I also read oldest first?"

Yes, and the database does the work for me, but it matters which way the data is stored. ORDER BY placed_at ASC on a table stored descending reads the partition from the other end, and Cassandra allows it on any clustering column.

The two directions are not equally cheap. When the stored order matches the query, the rows I want sit at the start, so LIMIT 20 reads about 20 rows. When the query asks for the reverse, Cassandra reads the partition backwards. That works, but on a large partition the cost depends on how the data is laid out in the files, and I measure rather than assume.

Compare PostgreSQL: a B-tree index can be scanned forward or backward at about the same cost, so ORDER BY created_at DESC LIMIT 20 and the ASC form are both quick. I do not carry that confidence over, because in Cassandra the physical order is part of the table.

So I define the order for the most common read, and use the reverse for the rare one.

"Does the order change the data on disk?"

Yes, physically. Rows in a partition are stored sorted by the clustering columns, in the direction given by CLUSTERING ORDER BY. The memtable keeps them sorted, and flushes and compactions write them to disk in that order.

This is different from PostgreSQL, where the heap holds rows in the order they were inserted, roughly, and the order I see in a query comes from an index or a sort step. The B-tree index is ordered, but the table is not. In Cassandra the table itself is the ordered structure. A sort is already done at write time, which is why ORDER BY on a clustering column costs nothing extra at read time.

The consequence is that the order is a physical choice. I can choose it only when I create the table, so the choice sits next to the key. A table with placed_at DESC and a table with ASC are two different tables with different files. If I get it wrong, the fix is a new table.

"What if the old rows are deleted by TTL?"

Expired data does not disappear at once, so reading from the head matters. A TTL (time to live) marks a cell to expire after a set time. When it expires, it becomes a tombstone-like marker, and the space is freed only when compaction removes it.

For a feed stored newest first, the oldest rows are at the tail of the partition. A read with LIMIT 20 starts at the head, finds 20 live rows quickly, and stops.

Had the table been stored oldest first, a plain LIMIT 20 would begin at the front, among the expired rows, and might read thousands of expired cells before it found live ones.

PostgreSQL has no TTL, so people run a scheduled DELETE ... WHERE created_at < now() - interval '7 days' and rely on VACUUM. Cassandra's TTL is neater, but it makes the layout decision matter more. For a feed, I store newest first.

"Can I change the order later?"

No, not in place. The clustering order is part of the table definition, and I cannot alter it. If I find I need the other order, I create a new table with the new order, backfill it, and switch the reads.

The steps are the standard path. First create orders_by_customer_v2 with CLUSTERING ORDER BY (placed_at ASC). Then write new rows to both tables. Then backfill old rows in token ranges, check counts and a sample of rows, and move reads to v2. Finally drop the old table when no reader remains.

In PostgreSQL the change would be a new index (CREATE INDEX CONCURRENTLY), which builds in the background while the table stays open. It is a much lighter operation, because the table does not move.

Because the move is costly, I try to get it right early: I write down the main screen's order in the access-pattern list, and I choose the clustering order from that, not from habit.

Drill · Real designs

These questions test lookup, live and latest-value designs.

Q41 · Scenario. "The business wants ad-hoc reports on any column. Can Cassandra do that?"

Reveal answer

Strong answer Not well. Ad-hoc means the queries are unknown, and Cassandra's design needs them known. The right answer is to keep Cassandra for the live paths and send a copy of the data to a system built for questions: a warehouse, PostgreSQL, ClickHouse or Spark.

Data flows out through change events (Kafka) or batch exports.

Picture it Two jobs, two stores.

The setup: Customers browse orders live, and analysts ask 'revenue by city by week' on any day.

Relational · PostgreSQL

One database does both, within limits.

pg.sqlruns offline
SELECT city, date_trunc('week', placed_at),
       sum(total)
FROM orders JOIN customers USING (id)
GROUP BY 1, 2;

Cassandra · CQL

Cassandra serves live reads. A warehouse reports.

cql.cqlruns offline
-- live: one partition read
SELECT * FROM orders_by_customer
WHERE customer_id = 7;
-- reports: copy events to a warehouse

The shift: A single store is split by workload: serving versus analysis.

What you see: Where the data flows.

flowruns offline
app -> Cassandra (live reads)
app -> Kafka -> warehouse (reports)

Why: Each system does the job it was built for.

Land it I keep Cassandra for known live queries and feed a warehouse for ad-hoc analysis.

Likely follow-ups
"Can Spark read Cassandra directly?"

Yes, as a batch job, and never in the path of a user request. The Spark Cassandra connector splits a table into token ranges and reads them in parallel, so many Spark workers each read a slice and the load is spread across the ring.

That is the right shape for analytics: a full scan of a big table, joined with other data, grouped any way the analyst likes. Spark does the joins and grouping that CQL does not have.

The risk is the live cluster. So I schedule it at night, cap the read rate, and where possible run it against a separate analytics data centre that holds a replica, so the scan never touches the nodes that serve customers.

A common alternative is to skip the scan completely: stream changes to a warehouse and run the SQL there. In PostgreSQL the same report is a single query, which is why many teams copy Cassandra data into PostgreSQL or ClickHouse for reporting.

"Is that duplication?"

Yes, and it is a deliberate choice, not a flaw. The warehouse copy is one more derived view of the same facts, built for a different kind of question.

The live tables answer known questions fast: 'orders for customer 7'. The warehouse answers unknown questions slowly but flexibly: 'average order value by city and hour for the last quarter'. One design cannot do both well, so I keep two copies, each shaped for its job.

The rule from the rest of the chapter holds. One place is the source of truth, and the others are copies that I can rebuild. The warehouse has its own refresh schedule, for example a nightly load or a minutes-old stream. I tell the business how stale it can be.

"What if it must be real-time?"

I keep a pre-computed table that a stream job updates as events arrive, so the dashboard reads one row by key.

The counter table below holds orders per city per hour. A dashboard asking for the last 24 hours reads 24 rows from one partition, which is a few milliseconds. The totals are only as exact as counters are: a retried increment can count twice, so I use it for dashboards and not for invoices.

Where the numbers must be exact, I make the job write a row per event batch with a unique id, so a retry overwrites the same row, and I compute the sum at read time over a small range.

PostgreSQL could answer 'orders per city per hour' with a GROUP BY at read time, and it would be fine up to some volume. The point is to move the aggregation from the read to the write.

pre-computed aggregateruns offline
-- illustrative
CREATE TABLE sales_by_city_hour (
  city text, hour timestamp, orders counter,
  PRIMARY KEY ((city), hour));
"What about SAI for small reports?"

It is fine for light, internal queries, with a limit on how far I rely on it. SAI lets me filter on columns outside the primary key, so an analyst can run a small report without a new table.

The limits are the same as before. Without a partition key in the query, SAI asks every node that might hold matches, so cost grows with the cluster. It is built for filtering, not for grouping or joining, and Cassandra still has no GROUP BY over arbitrary columns or any join.

So I use it for questions asked a few times a day by a few people, where the query includes a partition key or the table is small. I do not point a dashboard that refreshes every ten seconds at it.

In PostgreSQL, the same analyst would write any query and let the planner pick an index or a scan. SAI gets part of the way there, but it does not make Cassandra a reporting engine.

Q42 · Design. "Model rider locations: the app needs the latest position of each rider and a short history."

Reveal answer

Strong answer Two tables. rider_latest keyed by rider id holds only the newest position, overwritten on every ping: a pure upsert. rider_track keyed by ((rider_id, day), ts) keeps history with a TTL.

The map reads rider_latest for many riders; each one is a single-partition read.

Picture it Riders pinging every 5 seconds.

The setup: 1,000 riders, one ping each 5 seconds: 200 writes per second.

Relational · PostgreSQL

UPDATE the one row.

pg.sqlruns offline
UPDATE riders
SET lat = 18.52, lon = 73.85,
    seen_at = now()
WHERE id = 7;

Cassandra · CQL

Upsert the latest. Append the history.

cql.cqlruns offline
INSERT INTO rider_latest
 (rider_id, lat, lon, seen_at)
VALUES (7, 18.52, 73.85, toTimestamp(now()));
INSERT INTO rider_track (...) USING TTL 86400 ...;

The shift: Relational updates in place. Cassandra overwrites the latest and appends the rest.

What you see: The sizes.

math (illustrative)runs offline
latest : 1,000 rows, always
history: 17,280 rows per rider per day x 40 B = 0.7 MB

Why: A ping is just a write. Reads of a rider are one partition.

Land it I use one overwritten row for the latest position and a bucketed, TTL'd table for history.

Likely follow-ups
"Does overwriting create garbage?"

No real garbage problem, because an overwrite is not a delete. When a rider's position is updated, the new value goes to the memtable (memory) and later to a new file. The old value stays in an older file until compaction merges them and keeps only the newest.

The difference from deletes matters. A delete writes a tombstone that reads must skip, and that is what causes slow reads and warnings. An overwrite is just a newer version of the same cell, and a read by key merges versions and picks the newest by timestamp.

PostgreSQL pays for the same pattern differently: each UPDATE writes a new row version and leaves a dead one, so a table updated this often needs aggressive VACUUM and may bloat. In Cassandra the cleanup is compaction, which runs in the background.

"How do I show all riders in one area?"

I add a table keyed by a grid cell of the map, so the screen reads a few partitions and not one per rider.

The new table is keyed by a grid cell, for example a geohash prefix: ((cell_id), rider_id). Each rider has one row in the cell they are in. A map screen computes the cell for the viewport, plus its neighbours, and reads those few partitions.

When a rider crosses into a new cell, I delete the row in the old cell and insert into the new one, ideally in one logged batch. That is a key change, so it leaves a tombstone, as in Q48.

PostgreSQL with PostGIS answers 'riders within 2 km' with a spatial index, in one query. Cassandra has no spatial index in the core, so I move the geometry into the key, and I accept some churn. If the questions get richer, I would send the positions to PostGIS or a search engine.

"Why a TTL on history?"

I use a TTL so that data deletes itself, without a delete job and without me writing tombstones one by one.

  1. Set it: a TTL is a lifetime in seconds attached to a write. The row's cells expire when it ends. I can set it per write, or as the table's default_time_to_live.
  2. Pair it: with a time-window compaction (TWCS), which puts data from the same time window in the same files, so a whole file can be dropped when all its data has expired.
  3. Size it: by what the business needs: a 24-hour TTL (86,400 seconds) means yesterday's track disappears by itself.

Without a TTL, I would run a nightly DELETE, which writes a tombstone per point and needs scanning. PostgreSQL would use partitioned tables and drop the oldest partition, which is the same idea in another form.

TTL on writeruns offline
-- illustrative
INSERT INTO rider_track (rider_id, day, at, lat, lon)
VALUES (7, '2026-11-23', toTimestamp(now()), 18.52, 73.85) USING TTL 86400;
"What compaction suits it?"

Time-window compaction, TWCS, for the TTL'd history table. It fits one pattern very well: data written once in time order, never updated, and expired after a fixed time.

TWCS groups SSTables (the data files) by the time window in which the data was written, for example one file group per day. Within a window it behaves like size-tiered compaction. Once a window closes, it is not merged with newer data again. When every cell in an old file has expired and is past the grace period, the whole file is dropped at once, with no rewriting.

For rider_track with a 7-day TTL and daily windows, that means a file leaves on the eighth day instead of being merged for ever.

Cassandra 5.0 adds UCS, the unified strategy, which can be set up to behave like STCS, LCS or TWCS, so I may see it in newer clusters. I would still choose the strategy by the workload, and check the 5.0 docs for how UCS settings map.

Q43 · Scenario. "One partition is huge and slowing the cluster. How do you find it and fix it?"

Reveal answer

Strong answer Find it with nodetool tablehistograms (partition size and cell count percentiles) and nodetool tablestats (the maximum partition size). Logs may warn about large partitions during compaction.

The fix is in the model: add a bucket to the partition key, or a shard number, then migrate data into the new table. Tuning does not cure a bad key.

Picture it Reading the histogram.

The setup: Table messages shows slow p99 on a few conversations.

Relational · PostgreSQL

A big table is fine. Bloat vacuumed.

pg.sqlruns offline
SELECT conv_id, count(*)
FROM messages
GROUP BY conv_id
ORDER BY 2 DESC LIMIT 5;

Cassandra · CQL

Check partition size on the node.

cql.cqlruns offline
nodetool tablehistograms ks messages
nodetool tablestats ks.messages
-- look at: Compacted partition maximum bytes

The shift: SQL finds heavy groups by counting rows. Cassandra reads the node's partition statistics.

What you see: The output.

histogramruns offline
# illustrative output
Percentile  Partition Size  Cell Count
50%         1.2 KB          20
99%         420 KB          900
Max         3.1 GB          41,000,000      <- the problem

The fix: Change the key to ((conv_id, month), sent_at) and backfill.

Why: A max far above the 99th percentile means a few outlier keys.

Land it I find the outlier with tablehistograms and fix it by changing the key, not by tuning.

Likely follow-ups
"Why is a huge partition bad?"

Because Cassandra stores and moves a partition as a unit. The size of the largest partition therefore sets the worst case for several operations, not only reads.

A read of a big partition streams a lot of data, so latency climbs and the coordinator holds more in memory. Compaction merges partitions across files, so one huge partition is rewritten again and again, using disk and CPU. And since all replicas of one partition sit on the same three nodes (with RF 3), that replica set takes all the traffic for that key.

PostgreSQL has a related problem in a hot table or a bloated row set, but a single node absorbs it, and an index can still find a small slice quickly.

The guideline I use is to keep partitions under roughly 100 MB and 100,000 rows. It is a guide, not a hard limit, and I check it with nodetool tablehistograms.

"Can I just split it online?"

No. There is no way to split a partition in place, because the partition key decides where data lives. Changing the key means every row has a new address.

So I do a table migration. First, create a table with the better key, for example ((customer_id, bucket), ...). Second, write new data to both tables. Third, backfill the old data in token ranges, writing each row to the new table with its bucket. Fourth, check counts, and switch the reads. Fifth, drop the old table.

Until the migration finishes, I limit the damage. If the screen only needs the newest rows, I read only the head of the partition with LIMIT (when the clustering order is newest first), which skips the bulk. I may also add a client cache for that key, and alert on its size.

PostgreSQL would let me run ALTER TABLE or re-partition, with a lock and a rewrite. Cassandra needs the new table, which is more work but leaves the old one serving until the switch.

"Do I fix all keys?"

No. I fix only the keys that can grow without bound. A key that stays under a few megabytes forever is not a problem, and splitting it would add reads for no benefit.

The test is about growth, not a snapshot. A partition keyed by order_id holds one order and never grows after it is placed. A partition keyed by restaurant_id alone gets a new row for every order for ever, so it will cross any limit in time. That is the kind of key I change.

I check each key against a worked estimate. If a restaurant does 400 orders a day at 300 bytes, that is 120 KB a day, or about 44 MB a year, so even a one-year partition is under the guideline, and a day or month bucket is plenty.

Bucketing has a cost: a read that spans buckets must query several partitions. So I add a bucket where the numbers say it is needed, and I write the arithmetic down so the next person can see why.

"How do I prevent it?"

I prevent it at design time with size arithmetic, and after launch with an alert on the largest partition. Both are cheap, and both catch the problem before it hurts.

At design time, from Q15: rows per partition × bytes per row, for the growth of one key over its whole life. If the answer is over about 100 MB or 100,000 rows, I add a bucket to the key before the first row is written.

After launch, I check the maximum partition size from nodetool tablestats on a schedule, and I alert on it. The thresholds below are an idea to start from. A rising maximum shows a key outgrowing its design, months before a user notices.

PostgreSQL gives no such warning, because a big table is not a problem in the same way. In Cassandra, one key can.

alert idearuns offline
# illustrative
max partition bytes  > 100 MB  -> warning
                     > 500 MB  -> page someone

Q44. "How does the partition key decide which node stores a row, and why does the choice of key matter for spread?"

Reveal answer

Strong answer Cassandra hashes the partition key with Murmur3 into a number (a token). The token ring is divided among nodes (with vnodes, each node owns many small ranges, 16 per node by default since 4.0). The owner and its replicas store the row.

A good key has many distinct values with even traffic, so the hashes spread evenly. A key with few values or one dominant value puts the load on a few nodes.

Picture it Two keys on a six-node cluster.

The setup: Orders keyed by customer (2 million values) versus keyed by country (3 values).

Relational · PostgreSQL

Data placement is not a design choice.

pg.sqlruns offline
CREATE TABLE orders (
  order_id bigint PRIMARY KEY,
  customer_id bigint);
CREATE INDEX ON orders (customer_id);
-- one primary holds every row
-- placement is not a design choice

Cassandra · CQL

The key is the placement.

cql.cqlruns offline
PRIMARY KEY ((customer_id), ...)
-- token(customer_id) -> node
SELECT token(customer_id)
FROM orders_by_customer LIMIT 3;

The shift: In SQL placement is hidden behind one primary. In Cassandra the key places every row.

What you see: The spread.

load (illustrative)runs offline
key customer_id: 6 nodes each ~16% of rows   ✓
key country    : 3 values -> at most 3 partition owners   ✗

Why: Few key values cannot use more nodes than values.

Land it I pick a partition key with many values and even traffic, since the hash of the key decides the node.

Likely follow-ups
"What is a vnode?"

A vnode is a small slice of the token ring that a node owns, and each node owns many slices. The ring is the range of all hash values, and a partition key's hash falls into one slice, which has a node as its owner.

Without vnodes, each node owned one big range. Adding a node took half of one neighbour's range, so only that neighbour streamed data, and the load was uneven. With vnodes, each node owns 16 slices by default since Cassandra 4.0 (num_tokens: 16), spread around the ring.

A new node picks up small slices from many existing nodes, so all of them stream a little data in parallel, and joining is faster and fairer. The same holds when a node leaves.

The number of slices evens out load, since many small ranges average out the unlucky ones.

PostgreSQL has no such idea on one primary. In Citus, shards play a similar role: many small pieces move between workers.

"Can I see the token?"

Yes, with token(column) in a SELECT. It returns the hash of the partition key, so I can see where a key lands on the ring.

This is useful for two things. One is debugging: if one node is hot, I can check the tokens of the busiest keys and see if they are close together. The other is scanning in token order, as a job does when it pages through a whole table.

A key's token is a 64-bit number, from about minus 9.2 quintillion to plus 9.2 quintillion.

PostgreSQL has no equivalent, because rows are not placed by a hash of the key. The nearest idea is hashtext(id), which people use when they shard by hand.

see tokensruns offline
-- illustrative
SELECT customer_id, token(customer_id) FROM orders_by_customer LIMIT 3;
"Does the hash keep order?"

No. Murmur3 is a hash made to scatter keys, so neighbouring keys land far apart. Customer 100 and customer 101 get unrelated tokens and probably live on different nodes.

That is what spreads the load. If keys kept their order, then newly created ids, which are usually the biggest, would all pile up on the node that owns the top of the ring. The hash prevents that hot spot.

The price is on range queries. 'All customers with id between 100 and 200' is no longer a contiguous slice on disk. It is a scan of the whole ring, and CQL will refuse it without ALLOW FILTERING. A range is only allowed inside a partition (on clustering columns) or on token() for scanning.

A PostgreSQL B-tree keeps keys in order, so range queries on the primary key are cheap. Cassandra gave that up on purpose, to get an even spread. If I need ranges, I put the range column in the clustering key, where order is kept.

"What if traffic is uneven although the keys are many?"

Then the problem is a hot key, not a hash problem. A hash spreads different keys evenly, but it sends all traffic for the same key to the same replicas, so one very popular key stays hot, however many nodes there are.

Picture a celebrity restaurant with a million views an hour. Every read of its menu goes to the same three replicas of one partition. Adding ten nodes to the cluster does nothing for that key, since the three nodes that own it are the same three.

The ways out are per-key. I cache the hot key in front of Cassandra (in the app, or a cache like Redis), so most reads never reach it. For writes, I shard the key: add a number from 0 to N-1 to the partition key, write to one of N partitions, and read all N, as in Q45.

Q45 · Scenario. "We keyed a table by status (PLACED, PREPARING, DELIVERED). One node is on fire. Why, and what is the fix?"

Reveal answer

Strong answer Three values means three partitions, and 'PLACED' might hold millions of rows being written constantly. All traffic for each status lands on its replica set. The keys cannot use the cluster.

The fix: use a high-cardinality key and put status in a clustering column or a combined key such as ((restaurant_id, status), ...). For a truly hot key, add a shard number: ((status, shard), ...) with shard 0 to 15, and read all shards.

Picture it Status as the whole key versus a spread key.

The setup: 40,000 new orders per minute, all with status PLACED.

Relational · PostgreSQL

An index on status is fine.

pg.sqlruns offline
CREATE INDEX ON orders (status);
SELECT * FROM orders
WHERE status = 'PLACED';

Cassandra · CQL

Never key by a low-cardinality value.

cql.cqlruns offline
-- ❌ TRAP: PRIMARY KEY ((status), ...)
-- ✅ PRIMARY KEY ((restaurant_id, status),
--               placed_at, order_id)

The shift: A filter column is not a partition key.

What you see: Load by node.

load (illustrative)runs offline
key (status)                    : node B 90% of writes
key (restaurant_id, status)     : 40 restaurants spread over 6 nodes

Why: Spread by an id that grows with the data.

Land it I never use a low-cardinality column as the partition key, and I shard a hot key.

Likely follow-ups
"How do I shard?"

I add a shard number to the partition key, so one logical group becomes N physical partitions, and I read all N and merge.

  1. Choose N: from sizes and rates. If one status partition would grow to 800 MB at the guideline of 100 MB per partition, I want at least 8 shards, and I round up to 16 for headroom.
  2. Write: compute shard = hash(id) mod N and write to the partition for that shard, so the rows spread evenly.
  3. Read: query all N partitions in parallel and merge the results in the app.

A plain mod of the id works if ids are well spread. In PostgreSQL I would not need any of this, since one index on status covers all rows. Cassandra pays with N reads for a stable write path.

shard on write (sketch)runs offline
// illustrative
int shard = Math.floorMod(orderId.hashCode(), 16);
session.execute(insert.bind(restaurantId, status, shard, placedAt, orderId));
"What is N?"

Enough to bring the hot partition down to a safe size, and no larger. In practice I pick 8 or 16, and the sums decide.

Take the assumption: one status partition would grow to 800 MB, and I want each shard under 50 MB. That is 800 / 50 = 16 shards. With 8 shards, each is 100 MB, at the edge of the guideline, so I choose 16.

The cost of a larger N is on the read side: every read must query N partitions. With N = 16, the screen sends 16 small queries in parallel and merges the results, which is acceptable, and it finishes at the speed of the slowest one. With N = 256, it would send 256 queries and the tail latency would grow.

So I pick the smallest N that makes the partition safe, with a little headroom.

"Is the shard stored?"

No, I compute it from the id each time, and storing it adds nothing. The shard is a pure function of the id, so any code, in any service, that knows the id and N can work it out and reach the same shard.

For a write, the order service calculates shard = hash(order_id) mod 16, and puts it into the key. For a read by a single id, the same calculation tells me which one of the 16 partitions has the row, so I do one read, not 16.

The rule has a catch: the hash function must be stable and shared. If service A uses Java's hashCode() and service B uses Python's hash(), they get different shards. Python's built-in hash() for strings changes between runs, so I would use a fixed algorithm such as murmur3 or CRC32 everywhere and write it in one shared library.

PostgreSQL's hash partitioning does the same internally, and hides the function. In Cassandra the function is mine to keep stable.

"Can I change N later?"

Not easily, so I choose N with headroom. The shard count is part of the key, and changing it changes where each row lives: with mod 16 an id may sit in shard 5, and with mod 32 it moves to shard 5 or 21.

To change N, I create a new table, write to both during the change, backfill the old data with the new shard number, switch reads to the new table, and drop the old one. It is the same path as any key change, and it costs a copy.

Because of that, I plan for growth when I pick N. If today's traffic needs 8 shards and next year's might need 16, I start with 16. The cost of a few extra, smaller partitions is low, and the cost of a migration is high.

In PostgreSQL, adding hash partitions also means a rewrite or re-split of data, so it is a similar chore.

Drill · Spread, churn and method

These questions test spread, churn and the order in which a senior engineer designs.

Q46. "How many tables is too many?"

Reveal answer

Strong answer The number of tables is driven by the number of queries, not by the number of entities. A real system often has 20 to 100 tables. Each table has fixed memory overhead (memtable, bloom filters, metadata), so thousands is a problem, and the project's guidance is to keep it modest. Check current docs for the number for your version.

If I need many more, I look for queries that could share a table, or move some workloads elsewhere.

Picture it Counting the tables for a feature.

The setup: A chat product has 12 screens.

Relational · PostgreSQL

Tables follow entities: about five.

pg.sqlruns offline
CREATE TABLE users (id bigint PRIMARY KEY);
CREATE TABLE conversations (
  id bigint PRIMARY KEY);
CREATE TABLE members (
  conv_id bigint REFERENCES conversations,
  user_id bigint REFERENCES users);
CREATE TABLE messages (
  id bigint PRIMARY KEY, conv_id bigint);
-- five tables, queries come later

Cassandra · CQL

Tables follow queries: about a dozen.

cql.cqlruns offline
msgs_by_conv, convs_by_user,
user_by_email, unread_by_user,
members_by_conv, attach_by_msg ...

The shift: Table count tracks the query count.

What you see: Cost per table.

cost (illustrative)runs offline
each table: memtable + bloom filters + compaction state
200 tables -> fine;  5,000 tables -> memory pressure

Why: A table is a unit of memory and maintenance.

Land it I say tables follow queries, so tens are normal and thousands are a smell.

Likely follow-ups
"Do I merge queries?"

Yes, where two queries can share the same partition key and the same sort order. One table can then serve both, with a few extra columns.

Take two screens: 'a customer's orders, newest first' and 'a customer's open orders'. Both start with customer_id, and both want newest first. One table, orders_by_customer, serves both: the second screen reads the same partition and drops the delivered rows in the app. The extra column is status, which was already there.

I cannot merge queries that need a different partition key, such as 'orders by restaurant', since the key decides where the data lives.

PostgreSQL never faces this, because one table plus indexes serves both. In Cassandra, I list all queries in the access-pattern list, group the ones with the same key and order, and count tables after grouping. I also ask whether a rare query should leave Cassandra and run on a warehouse.

"Is one keyspace per tenant a good idea?"

It multiplies tables by tenants, so I prefer a tenant id inside the key. A keyspace is a namespace, and each tenant's keyspace needs its own copy of every table.

The arithmetic is quick. Suppose 30 tables per application and 1,000 tenants. That is 30 × 1,000 = 30,000 tables. Each table carries its own memtable, bloom filters and metadata, so memory and startup time grow with the count, and schema changes must be applied to 30,000 tables one by one.

The usual alternative is one set of 30 tables, with the tenant id as the first column of the partition key: ((tenant_id, customer_id), ...).

PostgreSQL offers schema-per-tenant, which is workable up to some hundreds of tenants, and row-level security with a tenant_id column. Cassandra has no row-level security, so isolation is enforced in the app. If a tenant needs hard isolation, such as its own cluster or region, I treat that as a special case.

"How does cost show up?"

As heap pressure, flush pressure and slow startup. The cost is paid in memory and in file handles, long before disk runs out.

Each table keeps its own memtable (the in-memory buffer for recent writes), bloom filters (small structures to skip files that cannot hold a key) and index data. Memory grows with the table count, whether the table is busy or not. With thousands of tables, a shared memory limit forces the node to flush many small memtables early, which makes many small files and more compaction work.

Startup is slower too, as each table must be opened and its files checked. Schema changes also take longer to spread, because every node must agree on the schema.

PostgreSQL has a similar effect with very many tables, in the catalog and in per-table files, and large installs struggle with hundreds of thousands. Cassandra's limit is much lower. I look at heap use, the count of pending flushes in nodetool tpstats, and the node's start time as warnings.

"Is there a hard limit?"

There is no fixed hard limit I would quote, and I do not recite a number. The project's guidance is to keep the table count modest, and it has changed with versions, so I check the current documentation for my version.

What I do instead is measure. I create the planned number of tables on a test cluster of the real hardware, run a realistic write load, and watch heap use, flush counts and start time. If memory is tight at 200 tables, I know my own limit, and that matters more than a general number.

As a working habit, tens of tables is normal, a few hundred needs a measured plan, and thousands is a design smell that sends me back to the question of why. Usually the cause is one keyspace per tenant, or one table per tiny variation of a query.

In PostgreSQL, tens of thousands of tables also work, but get slow in tooling such as dumps and migrations. In Cassandra, the hit is at runtime.

Q47 · Design. "Model menu items by restaurant, grouped by category and sorted by name."

Reveal answer

Strong answer Partition by restaurant. Clustering by category and then item name: ((restaurant_id), category, name). The menu page is one partition read and comes sorted and grouped.

A single restaurant's menu is small, so one partition is right.

Picture it Restaurant 12's menu.

The setup: A menu has 120 items in 8 categories.

Relational · PostgreSQL

Group and sort with ORDER BY.

pg.sqlruns offline
SELECT * FROM menu_items
WHERE restaurant_id = 12
ORDER BY category, name;

Cassandra · CQL

Clustering order is the grouping.

cql.cqlruns offline
PRIMARY KEY ((restaurant_id),
              category, name)
SELECT * FROM menu_by_restaurant
WHERE restaurant_id = 12;

The shift: Grouping at query time becomes grouping in the key.

What you see: Read one category.

category sliceruns offline
SELECT * FROM menu_by_restaurant WHERE restaurant_id = 12 AND category = 'Starters';

Why: The slice needs the first clustering column, which is category.

Land it I put the grouping columns in the clustering key in the order the screen shows them.

Likely follow-ups
"What if I also need lookup by item id?"

I add a second table keyed by item id. The menu table is keyed by restaurant, so a lookup of 'item 981' alone cannot be answered, since the key is not known.

The lookup table is tiny: item_by_id with the item id as the partition key and a few columns, such as restaurant, name and current price. A line in an order that adds item 981 reads this table by key, in one fast read.

Writing is the cost: an item added or renamed is written twice, once in each table, in a logged batch. Menus change rarely, so that is cheap.

In PostgreSQL one menu_items table with a primary key on id and an index on (restaurant_id, category, name) serves both, since a table can have many access paths.

item lookupruns offline
-- illustrative
CREATE TABLE item_by_id (
  item_id bigint PRIMARY KEY, restaurant_id bigint, name text, price decimal);
"How do I list the categories?"

I read the menu partition once and collect the distinct category values in the app. That gives the list for free. A menu of 120 items is about 12 KB, so the read is tiny.

Because the clustering key is (category, name), rows come sorted by category. Reading down the list, a new category starts whenever the value changes, so the app builds the list of headings in one pass, with no extra query.

In PostgreSQL I would write SELECT DISTINCT category FROM menu_items WHERE restaurant_id = 12, and the engine would do the same work.

A separate categories table is worth it only if a category carries its own data, such as a display order, an icon or opening hours. Then it is an entity, and I add a small table keyed by restaurant, with a row per category. Otherwise it is extra copies to keep in step.

"Where does price go?"

Price is an ordinary column in the menu table, and it is copied into each order line when the order is placed. So the menu has the current price, and each order has the price it was sold at.

This is the same copy-what-history-needs rule as the restaurant name. A receipt must show what the customer paid, whatever the menu says today.

In PostgreSQL, a normalised design would have order_items.item_id pointing to menu_items, and the price would come from the join. That is a classic bug: raise the price of a burger and last month's orders change their totals, unless the schema also copies the price into the order line. A careful relational design copies it too.

So the copy is not only a Cassandra workaround. It is correct modelling for money. In Cassandra I do it from the start, as there is no join anyway: the order service reads the item row, takes the price, and writes it into the order partition in the same request. Price is of the type decimal or integer cents.

"Does a price change update old orders?"

No, and that is correct behaviour. A price change updates one menu row, and every order already placed keeps the price it copied at the time.

Let me trace one case. On Monday a burger costs 8.00, and 500 orders include it, each with 800 cents in its own line. On Tuesday the price becomes 9.00. The menu row is updated: one write. The 500 orders are not touched, so their totals and receipts stay as they were.

The new price applies to orders placed from now on, because the order service reads the current price when it builds a new order.

A relational design reaches the same result only if the price is copied.

Q48 · Scenario. "Orders move through statuses and we need a list of orders by status. Updating the key column fails. What do we do?"

Reveal answer

Strong answer A key column cannot be updated, because the key is the address. If status is in the key of a table like open_orders, a status change means deleting the old row and inserting the new one, in a batch.

Each delete leaves a tombstone, so a table with heavy churn makes reads scan old markers. I keep the churn table small and expire with TTL, or I avoid status in the key and filter in the app.

Picture it The move PLACED to PREPARING.

The setup: Order 42 changes status.

Relational · PostgreSQL

UPDATE the column.

pg.sqlruns offline
UPDATE orders
SET status = 'PREPARING'
WHERE order_id = 42;

Cassandra · CQL

Delete the old row, insert the new one.

cql.cqlruns offline
BEGIN BATCH
 DELETE FROM open_by_status
  WHERE restaurant_id=12 AND status='PLACED'
  AND placed_at=... AND order_id=42;
 INSERT INTO open_by_status (...)
  VALUES (12,'PREPARING',...);
APPLY BATCH;

The shift: A key is not editable. Moving a row is a delete plus an insert.

What you see: The tombstone cost.

logruns offline
# illustrative output
WARN 1,800 tombstones read in partition (12, PLACED)

Why: The PLACED partition is full of delete markers for orders that left.

Land it I say a key cannot change, so a move is delete plus insert, and I watch tombstones.

Likely follow-ups
"Do I need old key values?"

Yes. The old row cannot be deleted without its full key, so I must know the current status before I move it.

  1. Read: fetch the master row by order id to learn the current status and placed_at. These are the key columns of the old row.
  2. Delete: remove the row at the old address, using the old status in the key. This writes a tombstone.
  3. Insert: write the row at the new address, with the new status in the key.

I do the delete and insert in one logged batch, so both apply or neither is lost. Two concurrent changes can still race, so I make the move conditional on the old status when it matters, with IF status = 'PLACED' on a table that holds it as a normal column. PostgreSQL has none of this: UPDATE ... SET status = ... finds the row by id and changes the column, and the index on status follows by itself.

the moveruns offline
-- illustrative
SELECT status, placed_at FROM orders_by_id WHERE order_id = 42;
-- then, in one logged batch:
--   DELETE the row under the old status; INSERT the row under the new status
"How long do tombstones stay?"

At least gc_grace_seconds, which is 10 days by default, and in practice until a compaction removes them. A tombstone is dropped only when it is older than that and compaction merges the files that hold it.

The 10 days exist for repair. If a replica missed a delete while it was down, the tombstone must still be around when that replica comes back and repairs, or the deleted data would return from the dead. That is why I do not shorten the setting just to make tombstones go away.

Count the cost for a queue-like table. Say 500 status moves per second. Each move writes one tombstone, so there are 43 million tombstones a day, and about 430 million inside the 10 days. A read over that partition walks past many of them, and the warn and fail thresholds (1,000 and 100,000) are reached fast.

That is why heavy delete churn is a known anti-pattern. PostgreSQL has the same issue in another form, dead rows, but VACUUM removes them continuously. Cassandra's markers wait for compaction.

"Can I avoid moving rows?"

Often, and that is my first choice. Store status as an ordinary column in a table keyed by restaurant and day, as in Q39. A status change then updates a column in place, with no row move and no tombstone.

The price is that the app filters. A restaurant-day partition has a few thousand rows, and the screen needs the 100 that are open. Reading 3,000 small rows is a single-partition read, and it costs a few milliseconds.

A moving table makes sense only if the open set is much smaller than the whole, the screen refreshes very often, and the read volume makes the filtering visible. Even then, I keep the table small and put a TTL on the rows as a safety net.

In PostgreSQL I would add WHERE status = 'PLACED' on an indexed column and not think about it. In Cassandra the choice is between filtering in the app and paying in tombstones, and I try filtering first.

"Is TTL a better cleanup?"

For rows that live a short time and then go, yes, as a cleanup. A TTL expires a row by itself, so no explicit delete is needed, and no job.

A TTL on a row leaves an expiry marker of its own, and it is cleaned by compaction after the grace period. For a time-series table with TWCS (time-window compaction), the files of one window expire together and the whole file is dropped, with no merging. So for data with a natural lifetime, such as live rider positions or a table of open orders that disappear after a day, TTL is much cheaper than many individual deletes.

It does not help the status move itself: a move needs a delete, because the row must go at once, not after a day. TTL is for what I leave behind in case a delete was missed, as a safety net.

PostgreSQL has no row TTL, so I would run a scheduled delete, or drop old partitions.

Q49. "When is SAI an acceptable answer in an interview, and when is it a red flag?"

Reveal answer

Strong answer Acceptable: a query that also fixes the partition key, an internal or rare query, a quick prototype, or a query whose index column has useful selectivity. SAI in Cassandra 5.0 is far better than the old secondary index.

A red flag: using it as the main path of a high-rate query without a partition key, or to avoid thinking about the query. It still fans out over the ring.

Picture it The same query with SAI.

The setup: Find orders by delivery pin code.

Relational · PostgreSQL

CREATE INDEX on pin.

pg.sqlruns offline
CREATE INDEX ON orders (pin);
SELECT * FROM orders
WHERE pin = '411001';

Cassandra · CQL

SAI. Fine if rare. Better, a table.

cql.cqlruns offline
CREATE INDEX ON orders (pin)
USING 'sai';
-- or CREATE TABLE orders_by_pin (...)

The shift: SQL indexes are everyday. SAI is a deliberate exception.

What you see: The decision.

SAI or table
CaseChoose
rare internal querySAI
hot user-facing pathown table
partition key also givenSAI is fine

Why: The more often and the larger the cluster, the more a table pays back.

Land it I accept SAI for light or partition-scoped queries and build a table for hot paths.

Likely follow-ups
"What does SAI add over old indexes?"

It is a newer index design, built into the SSTable (data file) lifecycle, and it has fewer of the old index's limits. The old secondary index stored a hidden table per index, which worked only for equality, and was a poor fit for most queries.

SAI keeps index data in files that are written and compacted along with the table's own files, so the index is never out of step with the data, and the write cost is lower. It supports ranges on numbers and dates, combined conditions across several indexed columns, and more column types.

In Cassandra 5.0, SAI is the index to use. SASI, an earlier attempt, is deprecated in its favour.

A PostgreSQL B-tree is a simple, global structure on one node. SAI is distributed: each node indexes its own data, and a query without a partition key must ask many nodes. So SAI gives me more questions I can ask, not a promise they are cheap.

"Is there vector search?"

Yes. Cassandra 5.0 has a vector type and SAI can search it for approximate nearest neighbours, which is what similarity search over embeddings needs.

An embedding is a list of numbers, such as 768 floats, that a model produces for a piece of text or an image. Close vectors mean similar content. The query below asks for the 5 stored vectors nearest to the one given, using ANN OF. The answer is approximate: it is much faster than comparing with every row, and may miss a true neighbour now and then.

This is the Cassandra counterpart of PostgreSQL's pgvector extension, where an index of type HNSW or IVFFlat serves ORDER BY embedding <-> .... Both give approximate results.

I treat it as a feature for where vectors live next to data already in Cassandra. For a large, search-first workload, a dedicated vector store may still fit better, so I would test on my data.

vector indexruns offline
-- illustrative
CREATE TABLE docs (id bigint PRIMARY KEY, emb vector<float, 3>);
CREATE INDEX ON docs (emb) USING 'sai';
SELECT id FROM docs ORDER BY emb ANN OF [0.1, 0.2, 0.3] LIMIT 5;
"Cost?"

It costs extra disk and extra work on every write. Each write updates the table and then updates the index, so a write is slower than on a table without one, and the index files take space beside the data.

On a table taking 5,000 writes a second, an index on one column adds work to all 5,000. The amount depends on the column's type and how it is spread, so I measure it, and I do not quote a percentage. The disk use depends on the number of distinct values and rows too.

There is also a read-side cost. A query that does not fix the partition key still asks many nodes, and the work scales with the cluster size. So the index trades a cost on every write for the freedom to ask a question the key does not allow.

The same trade exists in PostgreSQL, where each index slows inserts and updates and takes disk. The extra Cassandra worry is the fan-out. So I index only columns that a real, listed query needs.

"How do I test it?"

With realistic data and a realistic mix of queries, on a cluster of the real size. An answer from a laptop test is not an answer for a production decision.

I ask for three things. First, data of the real size and shape, including skew: if 60% of rows share one value, the index behaves differently from an even spread. Second, the queries I expect, at the rate I expect, mixed with the normal writes. Third, a node failure during the test, since fan-out queries are the ones that suffer when a node is slow.

I then look at p99 latency (the time under which 99 of 100 requests finish), CPU on each node, the size of the index files, and the slowdown of writes.

I compare the result with the same query on a hand-built table. If SAI is close to the table's numbers and the query is rare, I keep SAI. If p99 grows when I add nodes, the fan-out is showing, and I build the table.

Q50 · Design. "Interview round: I give you a PostgreSQL schema. Walk me through converting it to Cassandra in the time you have."

Reveal answer

Strong answer I follow seven questions. 1. What are the screens and APIs? 2. Write the query for each with inputs, sort and size. 3. Pick the partition key from what the query always knows. 4. Pick clustering columns from sort and range needs. 5. Estimate partition size and add a bucket. 6. Copy the fields each query shows. 7. Plan the writes: all copies in a logged batch, uniqueness with IF NOT EXISTS, and what stays in PostgreSQL.

I say aloud that some parts should not move, such as money and stock.

Picture it The routine on one query.

The setup: PostgreSQL: customers, orders, order_items. Screens: my orders, one order, restaurant day.

Relational · PostgreSQL

Start from tables and FKs.

pg.sqlruns offline
CREATE TABLE customers (
  id bigint PRIMARY KEY);
CREATE TABLE orders (
  id bigint PRIMARY KEY,
  customer_id bigint REFERENCES customers);
CREATE TABLE order_items (
  order_id bigint REFERENCES orders,
  item_no int);
-- queries are decided later

Cassandra · CQL

Start from screens and make tables.

cql.cqlruns offline
orders_by_customer
orders_by_id
orders_by_restaurant_day
-- written together in a batch

The shift: The relational schema is the input and the Cassandra schema is a new output.

What you see: The answers for one screen.

  1. Query: orders of one customer, newest first, 20 at a time.
  2. Partition key: customer_id.
  3. Clustering: placed_at DESC, order_id.
  4. Size: about 40 rows, fine.
  5. Copy: restaurant name and total.

Why: Each answer is one line and reaches the table.

Land it I say screens, queries, keys, sizes, copies, then the write plan, and I name what stays relational.

Likely follow-ups
"What do you leave in PostgreSQL?"

Payments, stock counts and anything that needs a rule across several rows. These are where a wrong answer costs money or trust, and where PostgreSQL's strengths are the point.

A payment must move from 'pending' to 'captured' exactly once, with the order, the ledger entry and the refund rules kept in step. In PostgreSQL that is one transaction with foreign keys and a UNIQUE constraint on the payment reference. Stock needs CHECK (stock >= 0) and a lock or a conditional update so two customers cannot take the last item.

Cassandra has no foreign keys, no multi-row constraints and no isolation, and its conditional writes work inside one partition only. Cassandra 6.0 previews general transactions, but it is an alpha release, so I would not design around it.

Saying so in the interview shows judgement: the hybrid is common, with PostgreSQL as the system of record and Cassandra for read-heavy views of the same data.

"How do you sync?"

The sync goes through events, so the two databases are connected by a log and not by two writes that could disagree.

  1. Write: the order service writes the order and an outbox row in one PostgreSQL transaction, so the change and its event are atomic.
  2. Publish: a relay reads the outbox and publishes each event to Kafka, at least once.
  3. Apply: a consumer reads the events and writes the Cassandra tables. Every write is an upsert, so a repeated event does no harm.

If I tried to write to PostgreSQL and Cassandra in the same request, one could succeed and the other fail, and there would be no transaction across them. The log removes that. A delay of a second or two between the two is normal, and the screen copes with it. The Kafka chapter covers the outbox and replay in full.

"What do you show on the whiteboard?"

One box per table, drawn in a fixed style, so the interviewer can read the model at a glance. I mark each column's role, and next to each box I write the query it serves.

The box has a title, such as orders_by_customer. Partition key columns are marked K, clustering columns are marked C with an arrow up or down for the sort order, and the other columns are listed below. Above or beside it I write the query it answers, like Q2: a customer's orders, newest first.

For the relational side, I draw the original tables with arrows for the foreign keys, so the contrast is visible: many linked tables become a few independent boxes, each shaped for one read.

Then I add one line of arithmetic per box: rows per partition × bytes per row, so the partition size is visible. A model drawn this way answers the three questions an interviewer is thinking: what does each screen read, where does each row live, and will it grow too big.

"What is the biggest mistake?"

Copying the relational schema table for table and keeping the habit of asking any question later. The result is Cassandra tables that look like PostgreSQL tables, and the queries need joins, secondary indexes or ALLOW FILTERING, none of which scale.

The root cause is the order of design. Relational design starts from the data, and Cassandra design starts from the queries. If I begin by drawing entities and normalising, I end up with the wrong tables, and no tuning will rescue them.

The second mistake is forgetting partition size. A key like restaurant_id alone looks fine in testing, then grows by a row per order for ever. It shows only after months, as slow reads and compaction trouble, which is the hardest time to change a key.

I guard against both by listing the screens first, writing a query for each, and doing the size arithmetic before the first CREATE TABLE. If a part of the schema is really about rules, I leave it in PostgreSQL.

10 · DrillConsistency, Performance & Real-Time Design — Q51–Q100

The second fifty questions leave the table design and ask how it behaves under load, failure and change. They cover consistency levels and conflicts, deletes and tombstones, the read and write path, indexes and clients, and then ten real-time designs and ten operations or choice questions.

Every answer shows the relational habit and the Cassandra replacement side by side inside its "Picture it" box. Say your answer first, then reveal.

Drill · Consistency levels and conflicts

These ten questions test whether you can say, in plain words, how many replicas must agree, what a conflict looks like, and how to stand in for the relational tools you gave up: UNIQUE, transactions and counters.

Q51. "What is a consistency level in Cassandra, and who chooses it?"

Reveal answer

Strong answer A consistency level (CL) is the number of replicas that must answer before Cassandra tells the client "done". The client chooses it for each request, not the server for the whole database.

With replication factor 3, every row lives on three nodes. A write at ONE returns after one node has it. At QUORUM it returns after two. At ALL it waits for all three.

The write is always sent to all three replicas anyway. The level only decides how many acknowledgements you wait for. Reads work the same way: a read at QUORUM asks two replicas and returns the newest answer.

Picture it One row, three copies, three different waiting rules.

The setup: A table with replication factor 3. A customer changes a delivery address, and the app has to decide how long to wait.

Relational · PostgreSQL

Postgres has one primary. A commit means one place has the data (plus a standby if synchronous).

address.sqlruns offline
BEGIN;
UPDATE customers
   SET address = '12 Elm St'
 WHERE id = 7;
COMMIT;  -- done: the primary has it
-- one copy decides; no per-query choice

Cassandra · CQL

Every query names how many replicas to wait for.

address.cqlruns offline
CONSISTENCY LOCAL_QUORUM;
UPDATE customers
   SET address = '12 Elm St'
 WHERE id = 7;
-- 2 of 3 replicas must answer
-- level is set per request, in cqlsh or driver

The shift: A relational commit has one answer; a Cassandra write has a dial you set per request.

Make the invisible visible: A write at QUORUM with RF 3, one replica slow.

consistency-level.txtruns offline
# illustrative output
write at QUORUM (needs 2 acks of 3)
replica A  ack   (4 ms)
replica B  ack   (6 ms)   -> client told "done" here
replica C  slow  (still writing, 90 ms)
write at ALL would have waited for C too

Why: The slow third replica does not hold the client back at QUORUM. That is the latency you buy by lowering the level, and the freshness you give up if the next read only asks C.

Land it I pick the level per query: LOCAL_QUORUM for normal reads and writes, ONE only where a stale answer is harmless.

Likely follow-ups
"What is the default level?"

It depends on the client, not on the server, and the usual answer is a single replica. In cqlsh the default is ONE. In the Apache Java driver 4.x the default profile uses LOCAL_ONE (check the reference configuration of your driver version).

So a query you never tuned waits for one replica only. With replication factor 3 that is fast, but the read can return a copy that missed the latest write, because the other two replicas were never asked.

PostgreSQL has no such dial. A read on the primary always sees committed data, and a read on a standby is stale only if you chose to read there. Cassandra moves that choice onto every statement.

I would never rely on the default for important data. I set the level in the driver profile, for example basic.request.consistency = LOCAL_QUORUM in application.conf, and override it per query only where a stale answer is harmless.

"What does LOCAL_ONE mean?"

LOCAL_ONE means one replica answers, and that replica must sit in the datacentre the client is connected to. Plain ONE accepts the first replica from anywhere, so with two sites it may wait on a node across the ocean.

Example: RF is 3 in Frankfurt and 3 in Mumbai, and a Frankfurt app reads at ONE. If the local replicas are slow or down, the coordinator may use a Mumbai replica, and a 5 ms read becomes a 120 ms read (illustrative figures). LOCAL_ONE removes that surprise because it never leaves Frankfurt.

The price is that you get one local copy, and that copy may be stale. It suits cheap, tolerant reads such as a cache warm-up or a dashboard that refreshes every few seconds.

For data a user will notice I would use LOCAL_QUORUM instead (Q53). If the local site has no live replica, a LOCAL_ONE request fails rather than quietly going abroad, and for most systems that failure is the behaviour you want.

"Can reads and writes use different levels?"

Yes, and they should be chosen as a pair. Each statement carries its own level, so one table can be written at QUORUM and read at ONE by a different query. What matters is the sum, as Q52 shows: read replicas plus write replicas must be more than the replication factor.

With RF 3 here is how common pairs behave:

WriteReadSumFresh read?
ONEONE1 + 1 = 2No, stale reads possible
QUORUMONE2 + 1 = 3No, not above 3
QUORUMQUORUM2 + 2 = 4Yes
ALLONE3 + 1 = 4Yes, but a dead node blocks writes

In PostgreSQL there is one level in practice: after COMMIT the primary shows the row. Cassandra lets you spend consistency where it matters. I give the order-placement write and the order-status read LOCAL_QUORUM and a menu read LOCAL_ONE.

"What happens if too few replicas are alive?"

The coordinator throws an UnavailableException before it sends anything, because it already knows too few replicas are alive for the level you asked for. With RF 3 and QUORUM you need 2 live replicas, so losing two nodes that hold the same data makes that data unavailable at that level.

  1. Unavailable vs timeout: unavailable means the coordinator believed too few replicas were up and did not try; a timeout means it tried and the replicas did not answer in time.
  2. Only some data is affected: the failure covers only partitions whose replicas are down. Other keys on healthy nodes keep working, unlike a primary crash where every write fails.
  3. You choose per query: the same partition still answers at ONE, so a query that can tolerate a stale answer can keep serving.

The relational comparison is a primary crash with no standby. My rule is to size RF so LOCAL_QUORUM survives one node loss, and to decide in advance which queries may drop to LOCAL_ONE.

Q52. "Explain R + W > RF. Why does it give strong consistency?"

Reveal answer

Strong answer Let R be the replicas you read, W the replicas you write, and RF the number of copies. If R + W is greater than RF, every read set overlaps every write set by at least one replica.

That overlapping replica holds the latest write, and Cassandra returns the newest timestamp among the replies. So the read sees the write.

With RF 3, QUORUM is 2. Write 2 plus read 2 is 4, which is more than 3. Any two replicas out of three must share at least one node.

Picture it Count the overlap with real node names.

The setup: Replicas A, B, C hold one customer. A write reached A and B. C is behind.

Relational · PostgreSQL

One primary, so a read always sees the commit. No overlap maths exists.

read.sqlruns offline
-- same primary for reads and writes
SELECT address FROM customers WHERE id = 7;
-- sees every committed write
-- replicas (if any) lag; you choose to
-- read them or not

Cassandra · CQL

Read set and write set must overlap by one node.

overlap.cqlruns offline
-- RF = 3, QUORUM = floor(3/2)+1 = 2
-- write acked by {A,B}
-- read asks any 2 of {A,B,C}
--   {A,B} -> both fresh
--   {A,C} -> A fresh, C stale -> A wins
--   {B,C} -> B fresh, C stale -> B wins

The shift: Relational consistency comes from one authority; Cassandra builds it from overlapping majorities.

Make the invisible visible: All three read pairs after the write reached A and B.

overlap-table.txtruns offline
# illustrative output
write value=NEW at t=100 -> A,B have it; C has OLD at t=50
read pair   replies                   returned
A + B       NEW(100) NEW(100)         NEW
A + C       NEW(100) OLD(50)          NEW (newest ts)
B + C       NEW(100) OLD(50)          NEW (newest ts)
R + W = 2 + 2 = 4 > RF 3  -> always NEW

Why: No pair of two nodes can avoid both A and B, so at least one fresh copy is always in the read. Compare ONE + ONE: 1 + 1 = 2, not above 3, so the read can land on C alone and return OLD.

Land it I choose the pair so R plus W exceeds RF, and I write the sum next to the table in the design doc.

Likely follow-ups
"What other pairs work with RF 3?"

Several pairs work. The test is only that read replicas plus write replicas must exceed RF. With RF 3 the choices are:

rf3_pairsillustrative
# illustrative
W=QUORUM(2) R=QUORUM(2)  2+2 = 4 > 3  fresh, survives 1 dead node
W=ALL(3)    R=ONE(1)     3+1 = 4 > 3  fresh, but 1 dead node blocks writes
W=ONE(1)    R=ALL(3)     1+3 = 4 > 3  fresh, but 1 dead node blocks reads
W=QUORUM(2) R=ONE(1)     2+1 = 3, not > 3  a read can miss the write

The last row is the common mistake: it looks safe because the write used a quorum, but the single replica the read picks may be the one that did not get the write yet.

So the choice is about which side you want to be cheap. Pick it from the read-to-write ratio and from which failure hurts more. If reads are 100 times more frequent than writes, ALL on write and ONE on read is tempting, but every write then fails when any replica is down. I use QUORUM on both sides unless a measured reason says otherwise, and I write the sum in the design doc.

"Is this the same as linearizability?"

No. The overlap rule guarantees that a read sees the latest write that has already completed. Linearizability is a stronger promise: all operations behave as if they happened one at a time in one real-time order.

The gap shows in two cases. First, two writers update the same row at the same moment, each at QUORUM; neither knew about the other, and the higher timestamp silently wins (Q56). Second, a write that has reached only one replica can be seen by one read and missed by the next, so a value can appear and then vanish for a moment.

A compare-and-set needs a lightweight transaction, which runs Paxos among the replicas of one partition (Q57). Here is the same idea in both worlds:

compare_and_setillustrative
-- illustrative
-- PostgreSQL: the row lock makes check-and-change one step
UPDATE accounts SET owner = 'asha' WHERE id = 7 AND owner = 'ravi';
-- Cassandra: a lightweight transaction does it for one partition
UPDATE accounts SET owner = 'asha' WHERE id = 7 IF owner = 'ravi';

I use that for rare events, not for every write, because it costs about four round trips.

"What if RF is 5?"

With RF 5 the quorum is floor(5/2) + 1 = 3. Write 3 plus read 3 is 6, which is more than 5, so the pair is strongly consistent and you can lose two replicas of any partition and still serve both reads and writes.

The cost is real. Every write is sent to 5 nodes, repair compares 5 copies, and disk use rises with the copy count. For 2 TB of unique data, RF 3 stores 6 TB and RF 5 stores 10 TB, about two thirds more (arithmetic from stated sizes).

Other pairs also work at RF 5: write 4 with read 2 (sum 6), or write 5 with read 1. Write 2 with read 3 does not, because 5 is not more than 5.

I would pick RF 3 per datacentre as the normal case, and RF 5 only when losing two replicas at once is a real scenario, for example a region with frequent rack maintenance, and the business accepts the extra storage bill.

"Does a failed write that reached one replica count?"

A write that returned a timeout is in an unknown state, not a failed one. The coordinator sends it to every replica anyway and only counts acknowledgements, so a timeout can mean the data landed on one or two replicas.

  1. What exists now: Cassandra has no rollback. Replicas that applied the write keep it, and the others may receive it later through a hint or repair.
  2. What a reader sees: a later read can return the new value if it touches a replica that has it, because the newest timestamp wins. Another read may return the old value until the data spreads.
  3. What the client does: retry the same statement. An upsert with the same key and values is safe to repeat, and adding USING TIMESTAMP with the original value makes the retry unable to overwrite a newer write.

The trap is non-idempotent writes, such as counters or list appends, where a blind retry can apply twice (Q60).

Q53. "When do you use LOCAL_QUORUM instead of QUORUM?"

Reveal answer

Strong answer Use LOCAL_QUORUM whenever you run more than one datacentre. It counts a majority only inside the datacentre the client is connected to.

Plain QUORUM counts a majority of all replicas in all datacentres. With two datacentres of RF 3, that is 6 replicas and a quorum of 4, so every request needs an answer from the faraway site.

LOCAL_QUORUM needs 2 of the 3 local replicas. It stays fast and keeps working if the other datacentre is cut off.

Picture it Two datacentres, one slow link.

The setup: QuickBite runs Frankfurt and Mumbai, each RF 3. The link takes about 120 ms (illustrative).

Relational · PostgreSQL

A relational read replica in another region is read-only and lags. You pick the primary or the replica.

region.sqlruns offline
-- app in Mumbai
SELECT status FROM orders WHERE id = 42;
-- reads the local replica (may lag)
-- writes must travel to the primary
-- in Frankfurt: about 120 ms

Cassandra · CQL

Both sites take writes; the level stays local.

region.cqlruns offline
CONSISTENCY LOCAL_QUORUM;
INSERT INTO orders_by_id (id, status)
VALUES (42, 'ACCEPTED');
-- needs 2 of 3 Mumbai replicas: ~5 ms
-- Frankfurt gets it in the background

The shift: Relational multi-region means one writer far away; Cassandra lets each region write locally and sync later.

Make the invisible visible: Latency of QUORUM against LOCAL_QUORUM.

latency.txtruns offline
# illustrative output
level          replicas needed   typical latency
LOCAL_QUORUM   2 of 3 local       5 ms
QUORUM         4 of 6 (two sites)  125 ms  (waits for far site)
EACH_QUORUM    2 local + 2 far     125 ms  (writes only)

Why: QUORUM across sites pays the speed of light on every request. LOCAL_QUORUM does not, which is the whole point of a multi-datacentre cluster.

Land it I use LOCAL_QUORUM for both reads and writes in each datacentre, which keeps strong consistency inside a site and speed everywhere.

Likely follow-ups
"Do you still get strong consistency across sites?"

Not instantly, and LOCAL_QUORUM does not promise it. Its overlap guarantee works only inside one datacentre.

What happens is this. A Frankfurt coordinator sends the write to all six replicas, three in Frankfurt and three in Mumbai, but it acknowledges the client after two local replicas answer. The Mumbai copies arrive one network trip later, roughly 100 to 150 ms between continents (illustrative), or later through hints if the link was down.

So a Mumbai LOCAL_QUORUM read issued inside that window can return the old value. Across sites you have eventual consistency, usually converging in well under a second.

If one flow truly needs the new value everywhere, for example a user who changes a password, I would either route that user to a single home site, or write that one change at EACH_QUORUM. For everything else I accept the short lag and say so in the design doc.

"When would you use EACH_QUORUM?"

EACH_QUORUM needs a quorum in every datacentre, so it is the strongest cross-site write level. With two sites of RF 3 it waits for 2 acknowledgements in Frankfurt and 2 in Mumbai, which means the write is as slow as the slowest site.

Use it for rare changes that must be confirmed everywhere before you go on, such as publishing a global price list or a feature flag that every region must have before the rollout starts. It is mostly a write level; check the docs before relying on it for reads.

The cost is availability. If the link to Mumbai is cut, every EACH_QUORUM write fails, even though both sites are healthy on their own. A normal LOCAL_QUORUM write would still succeed.

I keep it off the hot path. Anything a customer does on every request uses LOCAL_QUORUM, and the rare global change uses EACH_QUORUM with a clear error message when it fails.

"What if the local datacentre is down?"

By default the app does not move, and that is deliberate. The driver is configured with one local datacentre name, and a LOCAL_QUORUM request needs live replicas there. In the Java driver 4.x, remote nodes are used only if you set max-nodes-per-remote-dc above 0, and even then not for local levels unless you opt in (check the reference configuration).

If the whole local site is down, requests fail with a no-node-available error. A silent fallback would turn a 5 ms call into a 120 ms one and would drop LOCAL_QUORUM strength, because Mumbai replicas may not yet have Frankfurt's last writes.

I would rather fail over at the load balancer or DNS, so the same application code runs in Mumbai with Mumbai as its local datacentre.

One thing to prepare in advance: the surviving site must have capacity for double the traffic, so I test that failover in a drill and not on the day of the outage.

"Does this need a special replication setting?"

Yes. The keyspace must name the datacentres and give a replica count for each, using NetworkTopologyStrategy. The names must match what the snitch reports, so a typo makes the keyspace place no replicas where you expected.

keyspace.cqlillustrative
-- illustrative
CREATE KEYSPACE quickbite WITH replication =
  {'class': 'NetworkTopologyStrategy', 'fra': 3, 'mum': 3};
-- PostgreSQL has no per-table replica count: streaming replication
-- copies the whole cluster from one primary to its standbys.

SimpleStrategy walks the ring and ignores datacentres and racks, so two of three replicas can land in the same rack or site. It is fine on a laptop and wrong in production, because one rack or one site failing could then take out most copies of the same data at once.

If you add a datacentre later, change the keyspace replication first, then stream data to the new site with nodetool rebuild and run repair. Do it in that order, and test it on a staging cluster.

Q54 · Scenario. "A customer changes their address, refreshes the page, and still sees the old one. Cassandra is 'strongly consistent' with QUORUM. What went wrong?"

Reveal answer

Strong answer First suspect the levels. If the write used ONE and the read used ONE, the sum is 2 and not above RF 3, so a read can hit the stale replica.

Second suspect: the write and the read ran in different places. A write at LOCAL_QUORUM in one datacentre and a read in the other site's LOCAL_QUORUM do not overlap.

Third suspect: two clients with unsynchronised clocks. If a different app server wrote with a timestamp slightly in the future, a later write with an earlier clock loses (Q56).

Picture it Walk the three suspects with a trace.

The setup: The address update used LOCAL_ONE for speed. The page read used LOCAL_ONE too.

Relational · PostgreSQL

In Postgres a read after commit on the same primary always sees the new row.

read-your-write.sqlruns offline
UPDATE customers SET address = 'NEW'
 WHERE id = 7;
COMMIT;
SELECT address FROM customers
 WHERE id = 7;  -- 'NEW', same primary

Cassandra · CQL

The read can reach a replica that has not got the write yet.

read-your-write.cqlruns offline
CONSISTENCY LOCAL_QUORUM;
UPDATE customers SET address = 'NEW'
 WHERE id = 7;
-- ✅ read with LOCAL_QUORUM as well
SELECT address FROM customers
 WHERE id = 7;  -- overlap guaranteed

The shift: On one primary you never think about it; in Cassandra you must pair the read level with the write level.

What you see: The stale read, replica by replica.

replicas.txtruns offline
# illustrative output
write LOCAL_ONE  -> acked by A only (B, C pending)
read  LOCAL_ONE  -> coordinator asks C
C replies address='OLD'   -> user sees OLD
fix: write LOCAL_QUORUM + read LOCAL_QUORUM
     (2 + 2 = 4 > 3, overlap guaranteed)

Why: The level pair was 1 + 1 = 2, not above 3. Nothing was broken; the design simply never promised read-your-writes.

Land it I check the sum first, then sites, then clocks, before I blame the database.

Likely follow-ups
"Could read repair have fixed it?"

Read repair fixes the stale replica after a read, so it can heal the data but it cannot make the first read correct.

Here is how it works. At QUORUM the coordinator asks one replica for the data and another for a digest, which is a hash. If the hashes differ, it fetches full data from both, picks the newest by timestamp, writes that value to the stale replica, and only then answers. That blocking repair is why quorum reads never go backwards.

At ONE only one replica is asked, so there is nothing to compare and read repair does not run for that read. The old background read-repair chance setting was removed in 4.0.

In the address bug above, a read at ONE returned the stale value and repaired nothing. I would fix the levels first, and treat read repair, hints and scheduled repair as the safety net that keeps replicas close over time.

"Can we pin the user to one replica?"

You cannot rely on it, and pinning would not fix the bug anyway. A token-aware driver does choose a replica for each query, but it changes the choice as nodes get busy, fail or join.

More importantly, the write at ONE went to whichever replica answered first. If you pin the reader to replica B and the write landed on replica A, the user sees the old address until A's copy reaches B by hint or repair. Pinning only works if the writer and reader use the same replica, and nothing guarantees that.

What does help is pinning to a datacentre. A user routed to the same site for a session reads from the same local replica set, so LOCAL_QUORUM reads and writes overlap.

So the answer is to use the right levels, which costs one extra replica read of about a millisecond inside the same site (illustrative), not to build stickiness that breaks on every node restart.

"What if the app must be fast and cannot use QUORUM?"

I would first ask whether LOCAL_QUORUM is really too slow, because inside one datacentre the extra replica is usually a fraction of a millisecond. If it truly is, I protect only the paths where a user sees their own change.

  1. Selective quorum: write the profile at LOCAL_QUORUM and read the user's own profile page at LOCAL_QUORUM, while other users' views of that profile read at LOCAL_ONE.
  2. Session value: after the write, keep the new address in the session or a small cache with a time stamp, and show it for the next 5 to 10 seconds (illustrative window).
  3. Expire it: after the window, read from the database again, because by then the replicas have caught up.

This pattern is called read-your-writes at the application layer. It trades a little code for latency, and it hides the lag only from the person who made the change.

"How would you test for this bug?"

I would build a small experiment, because the bug depends on timing and will not show on every run. Use a three-node test cluster with RF 3, and set both write and read to ONE.

stale_read_testillustrative
# illustrative
1. start 3 nodes, RF 3, CONSISTENCY ONE
2. loop 10,000 times: write value i from node 1, read it at once from node 2
3. count reads that return a value older than i
4. repeat with QUORUM for both sides, expect 0

To make stale reads likely, add network delay to one node, for example with tc netem, so that node acknowledges later than the others. Without delay the stale window is only a few milliseconds and the loop may show nothing.

The test proves the bug exists and then proves the fix works, which is the evidence a reviewer wants. After the fix, keep the test in CI against a small cluster, so a future change of the driver default cannot bring the bug back unseen.

Q55. "How do replicas get back in sync after a node was down for an hour?"

Reveal answer

Strong answer Three mechanisms, from fastest to slowest. Hinted handoff: while the node was down, a coordinator saved the missed writes as hints and replays them when the node returns.

Read repair: when a read at QUORUM or higher finds replicas that disagree, Cassandra writes the newest value to the stale ones.Anti-entropy repair (nodetool repair): a scheduled job that compares data between replicas using hash trees and copies what is missing. It is the safety net for everything else.

Picture it Three catch-up paths for one missed write.

The setup: Node C was down for 60 minutes while 10,000 writes arrived for its token ranges (illustrative).

Relational · PostgreSQL

A Postgres standby replays the write-ahead log in order; catching up is automatic.

standby.sqlruns offline
-- standby reconnects to the primary
-- and replays WAL in one fixed order
SELECT pg_last_wal_replay_lsn();
-- converges because there is one
-- single history to replay

Cassandra · CQL

Several mechanisms, because writes may have gone to any replica.

catchup.txtruns offline
hints:       coordinator replays missed
             writes (kept 3 h by default)
read repair: a QUORUM read fixes stale
             replicas it notices
repair:      nodetool repair compares all
             replicas, copies the gaps

The shift: A relational standby follows one log; Cassandra replicas have no single log, so three repair paths exist.

Make the invisible visible: What each mechanism covers after a 60-minute outage.

repair-paths.txtruns offline
# illustrative output
outage 60 min, hint window 3 h
hints replay on return        -> covers all 10,000 writes
outage 5 h (longer than hints)-> hints dropped after 3 h
nodetool repair               -> covers the missing 2 h
rows never read               -> only repair can fix them

Why: Hints are best-effort and expire (the default window is three hours, check your version). Read repair only touches rows that are read. Repair is the only guarantee.

Land it I rely on hints for short blips and run repair on a schedule, within gc_grace_seconds, for everything else.

Likely follow-ups
"Why must repair run within gc_grace_seconds?"

A delete in Cassandra is a marker called a tombstone, and the marker is thrown away after gc_grace_seconds, 10 days by default. Repair must reach every replica before that, or the delete can be undone.

zombie_timelineillustrative
# illustrative
day 0   delete row: replicas A and B store the marker, C was down
day 10  grace period over: A and B compact the marker away
day 11  C comes back, still holds the old row
day 12  repair finds A and B empty, C has data, copies the row back

That last step is the zombie: the deleted row is alive again, and nothing in the logs says it was a mistake.

So I repair every table, including tables that only ever receive deletes by TTL, at least once inside the window, with margin. For a 10-day window I schedule a full cycle every 7 days. PostgreSQL has no such trap because one history decides what is deleted, and VACUUM only removes rows nobody can still see. A relational standby cannot bring a deleted row back.

"Is hinted handoff a guarantee?"

No. Hinted handoff is a best-effort speed-up, not a guarantee. When a replica is down, the coordinator stores the missed write as a hint in a file on its own disk and replays it when the replica returns.

Three limits matter. First, hints are only kept for max_hint_window, by default 3 hours, and a node down longer than that gets no more hints. Second, if the coordinator's disk is lost before replay, the hints are gone. Third, hints do not count toward the consistency level, so a QUORUM write was acknowledged by live replicas anyway.

For an outage of an hour, hints will usually bring the node up to date within minutes of its return. For a node down for a day, I do not rely on hints at all: I run repair on it before it serves traffic again.

The judgement is simple. Hints make the common short blip painless, and scheduled repair is the real guarantee that all copies agree.

"Does repair block traffic?"

It competes with traffic but does not block it. Repair is background work that uses disk, CPU and network, and a careless full run can raise read latency for the whole cluster.

It works in three steps. Each replica reads its data and builds a hash tree per token range, which is disk-heavy. The coordinator compares the trees, and where they differ only those ranges are streamed between nodes, which is network-heavy.

Two settings reduce the cost. Incremental repair marks data it has already repaired, so the next run reads only new data. And nodetool repair -pr repairs only the node's primary ranges, so running it on every node covers each range once instead of three times at RF 3.

I would not run repair by hand on a big cluster. A scheduler such as Cassandra Reaper splits the work into small segments, runs them off-peak and retries failures. Check the current docs for the repair mode recommended in 5.0.

"What is the relational comparison for repair?"

PostgreSQL streaming replication does not need repair, because there is one history. A standby replays the primary's write-ahead log byte for byte, so it can only lag, never disagree. The nearest check is measuring the lag.

pg_lag.sqlillustrative
-- illustrative
-- PostgreSQL standby: one history, so only a lag number
SELECT now() - pg_last_xact_replay_timestamp() AS lag;
cass_repairillustrative
# illustrative
# Cassandra: replicas take writes independently, so reconcile them
nodetool repair -pr quickbite

In Cassandra any replica accepts writes on its own, so the copies can diverge after an outage, and repair is how they are made equal. The sizes of the two jobs differ too: the standby check is one cheap query, while repair reads and compares every replica's data for a token range.

So repair is routine maintenance, like VACUUM in PostgreSQL, but with a hard deadline of gc_grace_seconds. If I cannot meet that deadline, I lower my ambition and raise gc_grace_seconds instead of skipping repairs.

Q56 · Scenario. "Two services update the same row at nearly the same moment. Who wins in Cassandra, and what can go wrong?"

Reveal answer

Strong answer Cassandra resolves a conflict per column with last write wins: the value with the higher write timestamp stays. The timestamp is set by the client or coordinator, in microseconds.

If timestamps are equal, the larger value wins (a tie-break on the bytes). If one server's clock runs 2 seconds ahead, its older write can beat a newer write from a correct clock.

So concurrent writers are not merged. One of them silently disappears. That is acceptable for a profile photo and wrong for a bank balance.

Picture it Two updates, two clocks.

The setup: Support sets the order status to REFUNDED at 10:00:00.100. The rider app sets DELIVERED at 10:00:00.050 on a clock running 100 ms ahead (illustrative).

Relational · PostgreSQL

A transaction takes a row lock; the second waits and sees the first result.

lock.sqlruns offline
BEGIN;
SELECT status FROM orders
 WHERE id = 42 FOR UPDATE;  -- lock
UPDATE orders SET status = 'REFUNDED'
 WHERE id = 42;
COMMIT;  -- other writer waited

Cassandra · CQL

No lock. Both writes land; the timestamps decide.

lww.cqlruns offline
UPDATE orders SET status = 'REFUNDED'
 WHERE id = 42;           -- ts = 1000100
UPDATE orders SET status = 'DELIVERED'
 WHERE id = 42;           -- ts = 1000150
-- higher ts wins: DELIVERED, not REFUNDED

The shift: The relational database orders writers with locks; Cassandra orders them with clocks.

What you see: The winner is the timestamp, not the real order of events.

lww.txtruns offline
# illustrative output
SELECT status, WRITETIME(status) FROM orders
 WHERE id = 42;
 status    | writetime(status)
-----------+-------------------
 DELIVERED | 1000150           <- looks newest
-- the refund was really later, but its clock was behind

Why: Cassandra cannot know the true order. It compares two numbers. Fix by synchronising clocks (NTP or chrony), or by making each writer write different columns, or by using LWT when order matters.

Land it I assume last-write-wins, keep clocks tight, and use one writer per column or an LWT when two writers truly collide.

Likely follow-ups
"How do you avoid conflicts by design?"

Give each writer its own rows, and turn every change into a new row instead of an overwrite. Then there is nothing for last-write-wins to throw away.

Take the order status. If the kitchen service and the rider service both run UPDATE orders SET status = ... on the same column, one of them can disappear. Instead each one inserts an event:

order_events.cqlillustrative
-- illustrative
CREATE TABLE order_events_by_order (
  order_id uuid, at timeuuid, actor text, status text,
  PRIMARY KEY ((order_id), at)
) WITH CLUSTERING ORDER BY (at DESC);
-- current status = the first row:  ... WHERE order_id = ? LIMIT 1

Two services writing at the same moment create two rows with different at values, and both survive. The price is that reading the current status becomes a read of the newest row, and the history is kept for free. In PostgreSQL I would just update one column, because row locks serialise the writers; here I model the history on purpose.

"Can I set the timestamp myself?"

Yes, with USING TIMESTAMP, which takes microseconds since 1970. If you leave it out, the client or coordinator fills in the current time.

The main use is a backfill. A job that copies old data should write it with the old timestamp, so it can never overwrite a newer value that a live writer put there a minute ago.

using_timestamp.cqlillustrative
-- illustrative
INSERT INTO customers_by_id (customer_id, name) VALUES (?, ?)
USING TIMESTAMP 1700000000000000;   -- microseconds, a day in Nov 2023

There are two traps. A timestamp too small, for example milliseconds passed where microseconds are expected, loses to every existing value, so your write seems to vanish. A timestamp too large, such as one far in the future, can never be overwritten by normal writes until real time catches up. Both look like a database bug.

I use it only in backfills and retries, always with a value computed from one clearly named source, and I never mix hand-set and automatic timestamps on the same column.

"How big can clock skew be before it hurts?"

Any skew larger than the gap between two conflicting writes can flip the winner. If the two writes are 5 ms apart and one server's clock is 8 ms off, the older write can win.

In a well-run cluster with NTP or chrony the offset is a few milliseconds, so most conflicts are decided correctly. A paused virtual machine or a broken time source can drift by seconds. Example: a server 2 seconds ahead stamps a write 10:00:00 when the true time is 09:59:58, and a correct server writing at 09:59:59 loses.

The Java driver 4.x stamps writes on the client and keeps them increasing inside one process, so the danger is between different app servers.

So I monitor clock offset on every app and database host, and I alert well below the typical gap between conflicting writes; 100 ms is a reasonable first line (illustrative). For columns where order really matters, I use an event row or a lightweight transaction instead of trusting clocks.

"How does this differ from a relational last-commit-wins?"

In PostgreSQL two concurrent updates to a row queue up. The second waits for the first row lock, so both run, in a real commit order. In Cassandra there is no lock and no order, so each write is simply stamped and the higher stamp wins.

lost_update.sqlillustrative
-- illustrative
-- PostgreSQL, one statement: both apply, 700 - 100 - 100 = 500
UPDATE accounts SET balance = balance - 100 WHERE id = 7;
-- Cassandra: read-modify-write, both read 700, both write 600
UPDATE accounts SET balance = 600 WHERE id = 7;

The Cassandra pair is a lost update: one withdrawal never happened. Even in PostgreSQL a read-then-write from the application has the same trap unless you lock the row or use one statement.

That is why money moves stay in a relational system with real transactions (Q91). Cassandra gives me speed and availability, and I accept that it decides conflicts by clock. If two writers can collide and both matter, I model events, or I use a lightweight transaction for the rare case.

Q57 · Design. "Design unique usernames in Cassandra. There is no UNIQUE constraint."

Reveal answer

Strong answer Use a lightweight transaction: INSERT ... IF NOT EXISTS into a table whose partition key is the username. Exactly one of two racing inserts is applied; the other gets [applied] = false.

Inside one partition this is linearizable, because Cassandra runs Paxos among the replicas of that partition. It costs about four round trips, so use it for rare events such as sign-up, not for every write.

Then write the rest of the user profile into the main table. Keep the claim table tiny: just username and user_id.

Picture it Two people sign up as 'asha' at once.

The setup: The claim table is keyed by username. Request A and request B arrive 3 ms apart.

Relational · PostgreSQL

A UNIQUE constraint makes the second INSERT fail with an error.

unique.sqlruns offline
ALTER TABLE users
  ADD CONSTRAINT uq_name UNIQUE (username);
INSERT INTO users (id, username)
VALUES (1, 'asha');
INSERT INTO users (id, username)
VALUES (2, 'asha');  -- ERROR duplicate

Cassandra · CQL

A claim table plus IF NOT EXISTS.

claim.cqlruns offline
CREATE TABLE username_claims (
  username text PRIMARY KEY,
  user_id  uuid
);
INSERT INTO username_claims (username, user_id)
VALUES ('asha', 11111111-...-1)
IF NOT EXISTS;  -- [applied] = true

The shift: The database checked uniqueness for you; in Cassandra you build a claim row and race for it.

Make the invisible visible: What the second client gets back.

lwt.txtruns offline
# illustrative output
 [applied] | username | user_id
-----------+----------+-----------
     False |     asha | 1111...1     <- A already owns it
-- app shows "name taken"; no second row is created
-- ✅ one winner, decided by Paxos on partition 'asha'

Why: Paxos agrees on one winner among the three replicas of that single partition. It cannot do this across partitions, so uniqueness must be a partition key.

Land it I make the unique value the partition key of a claim table and claim it with IF NOT EXISTS.

Likely follow-ups
"What if the claim succeeds but the profile write fails?"

The first rule is to make the order of steps safe, because Cassandra has no transaction across the claim table and the profile table. They are different partitions, and a conditional batch must stay inside one partition.

  1. Claim: generate the user_id first, then run the IF NOT EXISTS insert so the claim row stores it.
  2. Profile: write the profile under that same user_id. It is an upsert, so retrying it is safe.
  3. Cleanup: if the profile never lands, a claim sits there with no owner. Give the claim a short TTL (for example 10 minutes), and after the profile succeeds rewrite it with USING TTL 0 so it becomes permanent.

With that, a crash in the middle frees the name by itself. A sweeper job that scans for orphans also works, but scanning a claim table is the kind of query I try to avoid.

"Why not SELECT then INSERT?"

Because the gap between the two statements is where the bug lives. Two clients ask whether asha exists, both get nothing, both insert, and the second silently overwrites the first, since every Cassandra write is an upsert.

In PostgreSQL a unique index closes that gap, because the second insert fails with a unique violation. Cassandra has no such constraint, so the check and the write must be one atomic step:

claim_usernameillustrative
-- illustrative
-- PostgreSQL: the index rejects the second insert
ALTER TABLE users ADD CONSTRAINT users_username_key UNIQUE (username);
-- Cassandra: one conditional write; the loser gets [applied] = false
INSERT INTO username_claims (username, user_id)
VALUES ('asha', ?) IF NOT EXISTS;

The result row also contains the existing user_id, so the loser can tell a real conflict from a retry of its own claim. A retry that finds its own id there should count as success. A different id means the name is taken, and the form should say so.

"Can I change the username later?"

Yes, but the order of steps decides whether it is safe. The goal is that at no moment do two users hold the same name, and no one is left with no name.

  1. Claim the new name: run IF NOT EXISTS on the new username. If it fails, stop and tell the user.
  2. Update the profile: change the username column on the profile row to the new value.
  3. Release the old name: delete the old claim with IF user_id = ?, so you can only remove your own claim.

If the process crashes after step 1, the user holds two names for a moment and a retry finishes the job. Each step is idempotent, so repeating it is harmless. Some products keep the old name reserved for 30 days to stop impersonation; that is a product choice, and it is just a TTL on the old claim.

"How slow is an LWT?"

A lightweight transaction runs Paxos among the replicas of one partition, which takes about four round trips: prepare, read, propose and commit. A normal write takes one, so an LWT is several times slower (check the current docs for 5.0 improvements).

A worked example, using illustrative timings. If replicas in one datacentre are 1 ms apart, a normal write costs about 1 ms of network and the LWT about 4 ms. If the serial phase has to cross two sites at 120 ms, the LWT costs near 480 ms, which is why I use LOCAL_SERIAL.

Contention is the second cost. Two LWTs on the same partition at the same moment compete for the Paxos ballot, and one has to retry or time out. Two people racing for one username is rare and fine, but a counter built on LWT would hit this contention on every request.

My rule is to use an LWT for rare, high-value decisions such as sign-up, and never in a loop that handles every request.

Q58 · Design. "You write the same order to three tables, one per query. How do you keep them in sync?"

Reveal answer

Strong answer Use a logged batch: one BEGIN BATCH ... APPLY BATCH with the three inserts. The coordinator first writes the batch to a batch log on other nodes, then applies the writes. If it dies halfway, another node finishes the job.

That gives atomicity in the sense that all statements eventually apply. It is not isolated: another reader may see two of three tables for a moment.

A logged batch is slower than a single write, so it is for keeping denormalised copies aligned, not for bulk loading.

Picture it One order, three copies.

The setup: Order 42 must appear in orders_by_id, orders_by_customer and orders_by_restaurant_day.

Relational · PostgreSQL

One transaction writes the single orders table; views and indexes follow automatically.

order.sqlruns offline
BEGIN;
INSERT INTO orders (id, cust, rest, total)
VALUES (42, 7, 3, 18.50);
COMMIT;
-- indexes update inside the same commit
-- one copy, so nothing to keep in sync

Cassandra · CQL

The app writes every copy; a logged batch ties them together.

batch.cqlruns offline
BEGIN BATCH
 INSERT INTO orders_by_id (...) VALUES (...);
 INSERT INTO orders_by_cust (...) VALUES (...);
 INSERT INTO orders_by_restaurant_day (...)
   VALUES (...);
APPLY BATCH;

The shift: Relationally, indexes are kept in step by the engine; in Cassandra, you keep your own copies in step.

Make the invisible visible: What happens when the coordinator dies after table 1.

batch-log.txtruns offline
# illustrative output
1 coordinator writes batch log to 2 other nodes
2 coordinator applies: table 1 done, table 2 done
3 coordinator DIES before table 3
4 a node holding the log replays: table 3 applied
result: all three tables get the order, eventually

Why: The batch log is what makes it eventually all-or-nothing. A reader in step 2 can see the order in two tables and not the third, so design screens to tolerate that.

Land it I use logged batches to keep denormalised tables aligned, keep them small, and never use them to speed things up.

Likely follow-ups
"Is a batch like a relational transaction?"

Partly. A logged batch gives you one of the four ACID properties well, and the rest only in weaker forms.

PropertyPostgreSQL transactionLogged batch
AtomicYes, all or nothing, with rollbackAll statements eventually apply; no rollback
ConsistentConstraints and foreign keys checkedNo constraints; you keep the copies aligned
IsolatedOthers never see half of itOthers can see some tables updated first
DurableYes, after COMMITYes, at the chosen consistency level

So a batch guarantees that if the coordinator dies halfway, the rest will still be applied. It does not stop a reader from seeing the order in orders_by_id before it appears in orders_by_customer.

The Cassandra 6.0 alpha adds real multi-partition transactions called Accord (Q98), but it is a preview and off by default. I design for 5.0 and keep the apps tolerant of a copy that is a few milliseconds late.

"How big can a batch be?"

Cassandra warns at 5 KiB and rejects the batch at 50 KiB by default, set by batch_size_warn_threshold and batch_size_fail_threshold in cassandra.yaml.

cassandra.yamlillustrative
# illustrative
batch_size_warn_threshold: 5KiB
batch_size_fail_threshold: 50KiB

The arithmetic is simple. If one order row is about 500 bytes, ten rows reach the warning and about a hundred reach the failure (illustrative row size). The normal case in the QuickBite design is three or four rows, one per table, which is far below both.

I would not raise the fail threshold to make a big batch pass. The limits protect the coordinator, which holds the whole batch in memory and must forward it. A developer who needs hundreds of rows in a batch is using the wrong tool, and the fix is separate asynchronous writes (Q59).

"What if the three tables are on different nodes?"

That is the normal case, and it is why a multi-partition batch costs more than separate writes. Count the work for QuickBite's three tables with RF 3.

batch_costillustrative
# illustrative
logged batch:   2 batch-log writes + 3 tables x 3 replicas = 9 data writes
                + 2 batch-log deletes, all driven by ONE coordinator
3 plain writes: 9 data writes, each sent by a token-aware driver
                to a replica of its own table

The coordinator of a batch owns at most one of the keys, so it must talk to nodes that do not hold the others. The batch log is written to two other nodes first, so if the coordinator dies, one of them replays the batch.

I pay that price on purpose. It is the cost of knowing that no copy is permanently missing, because a replay finishes the missing writes. For three or four rows per request it is acceptable; for a bulk load it is not, since the same overhead repeats for every batch.

"What about a single-partition batch?"

It is the one batch type that is good for performance. When all rows share the same partition key, Cassandra applies them as a single mutation on each replica. That makes it atomic and isolated, and it skips the batch log.

A typical use is a related group of rows in one partition, such as an order's header and its line items. A reader sees either all the lines or none of them.

order_lines.cqlillustrative
-- illustrative
BEGIN BATCH
  INSERT INTO orders_by_id (order_id, line_no, item, qty) VALUES (?, 1, 'biryani', 2);
  INSERT INTO orders_by_id (order_id, line_no, item, qty) VALUES (?, 2, 'raita', 1);
APPLY BATCH;

The relational equivalent is a transaction around two inserts into the same order. In Cassandra, putting both rows in the same partition is what turns the guarantee from eventual into immediate. I use it freely, as long as the partition stays small. For a bulk load of whole orders I still write order by order, not in one giant batch.

Q59 · Scenario. "A developer batches 500 inserts across many partitions to 'speed up' a bulk load. The cluster starts timing out. Why?"

Reveal answer

Strong answer A multi-partition batch goes through one coordinator. That node must forward all 500 rows to many other nodes and hold the whole batch in memory.

It becomes a bottleneck and a single point of pain. The batch size warning (5 KiB) is a sign, and past 50 KiB the batch is rejected.

Faster is the opposite: many small single-row writes, sent asynchronously by a token-aware driver, with a cap on how many are in flight. Each goes straight to its own replicas.

Picture it One coordinator against twenty.

The setup: A 6-node cluster. The batch of 500 rows touches all six nodes.

Relational · PostgreSQL

Bulk loading in Postgres uses COPY or one multi-row INSERT in a transaction.

bulk.sqlruns offline
COPY orders (id, cust, total)
FROM '/data/orders.csv' CSV;
-- or
INSERT INTO orders VALUES (1,..),(2,..),
 (3,..);  -- one node, one transaction

Cassandra · CQL

Separate async writes, spread over all nodes.

bulk.cqlruns offline
-- ❌ TRAP: one big batch, one coordinator
BEGIN BATCH ... 500 inserts ... APPLY BATCH;
-- ✅ 500 single INSERTs, async, in parallel
INSERT INTO orders (id, cust, total)
VALUES (?, ?, ?);   -- prepared

The shift: One big transaction suits one node; Cassandra wants many small writes fanned out to many nodes.

What you see: The coordinator's log and the symptom.

batch-warn.txtruns offline
# illustrative output
WARN Batch of prepared statements for [orders]
 is of size 62190, exceeding specified
 threshold of 5120 by 57070.
ERROR Batch too large (> 51200 bytes)
Write timeout: coordinator busy, 480 of 500 pending

Why: The load is not spread. One node does the work of six, and its memory and network fill first.

Land it I never use multi-partition batches for speed; I send prepared single writes asynchronously with a bounded number in flight.

Likely follow-ups
"How many writes in flight is right?"

There is no universal number, so I measure it with a simple rule. The right in-flight count is throughput times latency, from Little's law.

in_flight.txtillustrative
# illustrative
target 50,000 writes/s, average latency 2 ms
in flight = 50,000 x 0.002 = 100 requests, cluster-wide
use 2 to 4 times that as a cap: 200 to 400

Start near that cap, then watch p99 latency and timeouts. If latency climbs while throughput stays flat, you are too high. If the cluster's CPU and disk are idle, go up. The Java driver 4.x also limits requests per connection (max-requests-per-connection, default 1024, check your version), but I still cap in my own code with a semaphore, so one bulk job cannot starve the live traffic.

I run bulk loads off-peak, and with a hard stop if p99 read latency on the live path rises. The cap is cheap to change, so I make it a setting and not a constant.

"Is there a tool for loading CSV?"

Yes. The DataStax Bulk Loader, dsbulk, reads CSV or JSON files and loads them with the concurrency and retry handling already done. Compare it with the relational habit:

bulk_loadillustrative
# illustrative
# PostgreSQL: one server-side bulk path
psql -c "\copy menu_items FROM 'menu.csv' CSV HEADER"
# Cassandra: client-side loader, token-aware and asynchronous
dsbulk load -url menu.csv -k quickbite -t menu_by_restaurant -header true

PostgreSQL's COPY goes to one primary and is bounded by that machine. dsbulk sends single-row writes to the right replicas in parallel, so it scales with the number of nodes.

For very large one-off loads there is also the offline route: build SSTable files with CQLSSTableWriter and stream them with sstableloader. It is more work to set up. Check the current docs for which tools your distribution supports and for their option names, and test the load on a staging cluster of the same size first, because a load that looks fine on three nodes can overwhelm a small production cluster.

"Does an unlogged batch help?"

No, not across partitions. An unlogged batch skips the batch log, so it is cheaper than a logged one, but it still goes through one coordinator.

Count it for 500 rows in 500 different partitions at RF 3. That coordinator receives 500 mutations in one message, keeps them in memory, and sends 1,500 replica writes. If it times out, the client cannot tell which of the 500 landed. With 500 asynchronous single-row writes from a token-aware driver, each write goes to a replica of its own key, so the work is spread over every node and a failure affects one row.

There is also no atomicity: unlogged means if the coordinator dies halfway, some rows are applied and some are not.

I use unlogged batches only inside one partition, where they cost nothing extra and the rows apply together. Across partitions, I use async single writes.

"What about prepared statements?"

Prepare once and bind many times. A prepared statement is parsed and planned once on the server, and every later call sends only the statement id and the values.

  1. Prepare at startup: the driver sends the CQL text and gets back an id plus metadata, including which bound values form the partition key.
  2. Bind and route: for each call the driver hashes the partition-key values with Murmur3, finds the replicas, and sends the write straight to one of them.
  3. Re-prepare automatically: if a node forgets the id, for example after a restart, the driver prepares it again for you.

An unprepared statement built by string concatenation costs a parse every time, cannot be routed by token, and is open to injection. PostgreSQL has prepared statements too, but they save parsing only, because there is one primary to send to. In Cassandra they also decide which node receives the write.

Q60. "Why are counters tricky in Cassandra, and when would you use one?"

Reveal answer

Strong answer A counter column holds a number you change with SET likes = likes + 1. Cassandra stores increments, not the final value, and merges them across replicas.

Counters are not idempotent. If an increment times out and you retry, it may have applied twice. So counts can drift slightly.

Counters also live in their own table type: all non-key columns must be counters. Use them for approximate numbers, such as page views or likes, not for money or stock.

Picture it A like button on a restaurant.

The setup: QuickBite counts likes per restaurant. A tap is retried after a timeout.

Relational · PostgreSQL

An atomic UPDATE inside a transaction is exact.

likes.sqlruns offline
UPDATE restaurants
   SET likes = likes + 1
 WHERE id = 3;
-- row lock; exact; retry-safe if wrapped
-- in a transaction that you can roll back

Cassandra · CQL

A counter table. An increment is sent, not a value.

likes.cqlruns offline
CREATE TABLE restaurant_likes (
  restaurant_id int PRIMARY KEY,
  likes counter
);
UPDATE restaurant_likes
   SET likes = likes + 1
 WHERE restaurant_id = 3;

The shift: Relational counters are exact because of locks; Cassandra counters are fast and distributed but can double-count on retry.

What you see: A timeout, a retry and the double count.

counter.txtruns offline
# illustrative output
t0  likes = 100
t1  UPDATE likes = likes + 1   -> TIMEOUT (unknown)
t2  retry UPDATE likes + 1     -> OK
t3  read likes                 -> 102 (or 101)
-- the first increment may have landed anyway

Why: The client cannot tell whether the first request applied. With a counter there is no way to make the retry safe, so the number is approximate.

Land it I use counters for tolerant numbers, and for exact numbers I count events in a normal table or keep the value in a relational database.

Likely follow-ups
"What is an exact alternative?"

The exact alternative is to store the facts and count them. Insert one row per like, with the pair as the key, so a repeated request overwrites itself.

likes.cqlillustrative
-- illustrative
CREATE TABLE likes_by_restaurant (
  restaurant_id uuid, customer_id uuid, liked_at timestamp,
  PRIMARY KEY ((restaurant_id), customer_id));
-- PostgreSQL version: INSERT ... ON CONFLICT DO NOTHING; then COUNT(*)

A retry is safe, and one person cannot like twice. The count is the number of rows, read by a query or by a periodic rollup job that writes the total into another small table.

Mind the partition size. If a popular restaurant has 500,000 likes at about 50 bytes each, the partition is about 25 MB, which is fine. At 5 million likes it passes the ~100 MB guideline, so I would add a bucket to the key. For the number on screen, a counter plus a nightly reconcile from these rows gives speed and exactness.

"Why can't a counter table hold other columns?"

Because a counter column follows different merge rules from a normal column. A normal cell is decided by timestamp, so the newest value wins. A counter is stored as increments from each replica, and replicas merge them by adding them up.

Mixing the two in one row would give the engine two rules for one record. So Cassandra requires that every non-key column in a counter table is a counter. There is also an extra cost: a counter update reads the local value first, so it is slower than a normal append write. Counter columns also do not support TTL.

The usual shape is two tables with the same key. Descriptive data goes in restaurants, and the counts go in restaurant_stats with only counter columns. The app reads both when it needs the page.

This is the opposite of the relational habit of putting likes_count next to the name in one row, and it is a good example of the table-per-purpose way of thinking.

"Can you delete or reset a counter?"

You can delete the row, but you should not reuse the same key afterwards. A delete leaves a tombstone, and incrementing a counter whose old tombstone and old increments still exist on other replicas can give wrong values. The safe habit is that a deleted counter key stays deleted.

To reset a counter, read the current value and write the negative of it. Increments commute, so the ones that arrive between your read and your write are not lost, but the final value can end up slightly above or below zero. That race is acceptable for display numbers.

The better design is never to reset. Use a counter per period, such as (restaurant_id, day), so each day starts at a new key at zero and old days age out with their partition.

I decide this before writing the table, because there is no clean way to change it later.

"Does Cassandra 5.0 change this?"

Counters still work the same way in 5.0, with the same retry problem: a timed-out increment may or may not have applied, and a blind retry can count twice. I know of no change that makes them exact (check the 5.0 release notes).

For exact transactional counts there are two paths. The Accord work in the 6.0 alpha aims at multi-partition transactions, but it is a preview, off by default, and not for a production design today. The practical path is to keep the exact number in PostgreSQL, or to store one row per event in Cassandra and count them, as in the first follow-up.

My rule: a counter may feed a dashboard that tolerates a small error. Anything that touches money, stock or a limit uses events or a relational transaction.

Drill · Deletes, tombstones and TTL

Cassandra has no real delete, only a marker called a tombstone. These six questions are about how that marker works, how it ruins reads when misused, and how TTL and bucketing avoid deleting by hand.

Q61. "What is a tombstone, and why doesn't DELETE free space right away?"

Reveal answer

Strong answer A tombstone is a marker that says "this value was deleted at time T". Cassandra never edits files in place, so a delete is a new write of this marker.

The marker must stay long enough to reach every replica. If a replica missed the delete and the marker vanished, that replica would later send the old value back, and it would look alive again.

Compaction removes the marker and the data it covers, but only after gc_grace_seconds (default 864,000 s, ten days) has passed.

Picture it A cancelled order row.

The setup: QuickBite deletes order 42 from orders_by_customer. The row sits in an SSTable that is already on disk.

Relational · PostgreSQL

DELETE removes the row; vacuum frees the space later.

delete.sqlruns offline
DELETE FROM orders WHERE id = 42;
-- row marked dead by this transaction
-- invisible to new snapshots
-- VACUUM frees the space later
SELECT count(*) FROM orders WHERE id = 42; -- 0

Cassandra · CQL

DELETE writes a marker; space is freed in compaction.

delete.cqlruns offline
DELETE FROM orders_by_customer
 WHERE customer_id = 7
   AND order_id = 42;
-- writes a tombstone, not a removal
-- old SSTable still holds the row until
-- compaction after gc_grace_seconds

The shift: A relational delete hides the row from new readers; a Cassandra delete adds a second record that must travel to every replica.

Make the invisible visible: Where the row and its tombstone live on disk.

tombstone.txtruns offline
# illustrative output
SSTable-1 (old):  cust 7 | order 42 | total 18.50
SSTable-2 (new):  cust 7 | order 42 | TOMBSTONE @ t=500
read = merge both -> newest wins -> row hidden
after compaction past gc_grace (10 days):
SSTable-3:        (both removed)

Why: A read must merge both files and see the marker, so tombstones add work until they are purged.

Land it I treat every delete as a write that costs a read later, and I design so deletes are rare.

Likely follow-ups
"Can I free space immediately?"

Not safely, and not immediately. A tombstone is only removed by compaction after gc_grace_seconds has passed, and a delete first adds a marker, so disk use goes up before it goes down.

You can lower gc_grace_seconds on one table, but the rule is that repair must complete on every replica in less time than that value. Example: if your repair cycle takes 5 days and runs weekly, a grace of 1 day lets a replica that missed a delete keep the old row after the marker is purged, and the row returns (Q63).

Other levers exist, with limits. A major compaction (nodetool compact) can purge markers already past grace, but it does not shorten the wait. TRUNCATE or dropping a table frees space at once, but removes everything.

In an emergency I add disk or a node first, then fix the model so deletes are rare.

"Do updates create tombstones?"

Yes, one kind: writing null means "delete this cell", so it writes a tombstone. An update with a real value does not.

null_tombstone.cqlillustrative
-- illustrative
INSERT INTO customers_by_id (customer_id, name, email)
VALUES (?, 'Asha', null);      -- writes a tombstone for email
INSERT INTO customers_by_id (customer_id, name)
VALUES (?, 'Asha');            -- writes nothing for email

The common accident is a prepared statement with ten columns where the app binds null for the six fields the user left blank. Each insert then writes six tombstones, and a table with millions of such rows is slow to read. In the Java driver 4.x you can leave the value unset on the bound statement, or leave the column out of the CQL.

In PostgreSQL a null is just a value and costs nothing special. Overwriting a whole collection column (a list or set) also writes a range tombstone for the old content, so I prefer adding elements to replacing the collection.

"Are there different kinds of tombstones?"

Yes, there are four kinds, and cost depends on which one you create.

KindCreated byCost to read
Cellsetting one column to null, or an expired TTL cellOne marker per cell
RowDELETE of one full primary keyOne marker per row
Rangedelete on a clustering prefix or rangeOne marker covers many rows
PartitionDELETE with only the partition keyOne marker covers the partition

Cheap deletes are the big ones: a partition tombstone is a single marker, and a reader that meets it skips the whole partition. The expensive pattern is deleting 10,000 rows one at a time, which leaves 10,000 markers that every later read walks through, up to the 1,000 warning and 100,000 failure thresholds.

So when I design deletes, I ask which unit goes away together, and make that unit a partition or a clustering range.

"Is it the same as a relational soft delete?"

They are different things. A soft delete in PostgreSQL is a column that you add, set and filter on in every query, and the row is still there. A tombstone is the engine's own marker, and it makes the data invisible to reads, then removes it later.

delete_styles.sqlillustrative
-- illustrative
-- PostgreSQL soft delete: you maintain the column and the filter
UPDATE orders SET deleted_at = now() WHERE id = 42;
-- Cassandra delete: the engine writes a marker, purged after gc_grace
DELETE FROM orders_by_id WHERE order_id = ?;

A Cassandra delete does not keep history for you, and the data still occupies disk until compaction removes it. If the business wants to keep a cancelled order, or show "deleted by user", I add a status column and update it on purpose, usually with a TTL for eventual removal.

That also avoids tombstones in a partition that is read all the time, and it keeps the history that an auditor may ask for later.

Q62 · Scenario. "Reads on a table that 'acts like a queue' suddenly fail with 'tombstone_failure_threshold exceeded'. What happened?"

Reveal answer

Strong answer This is the queue anti-pattern. A table where rows are inserted, processed and deleted in the same partition piles up tombstones. A read that scans the partition head must step over all the dead rows first.

The warning threshold is 1,000 tombstones per read and the failure threshold is 100,000. Past that, Cassandra aborts the read to protect the node.

Fix the design, not the setting. Use time buckets so old buckets are dropped whole, or use a real queue such as Kafka and keep Cassandra for state.

Picture it Fifty thousand dead rows at the head of a partition.

The setup: A jobs_by_queue table. Workers read the oldest pending job and delete it after processing.

Relational · PostgreSQL

A Postgres jobs table with SKIP LOCKED just works, and vacuum cleans.

jobs.sqlruns offline
SELECT id FROM jobs
 WHERE status = 'PENDING'
 ORDER BY id LIMIT 1
 FOR UPDATE SKIP LOCKED;
DELETE FROM jobs WHERE id = $1;
-- vacuum reclaims the dead rows

Cassandra · CQL

Reading from the head scans every dead row.

jobs.cqlruns offline
SELECT * FROM jobs_by_queue
 WHERE queue = 'emails' LIMIT 1;
-- ❌ TRAP: the oldest 50,000 rows are
-- deleted; each leaves a tombstone that
-- the read must skip before the first
-- live row

The shift: A relational queue deletes cheaply behind a lock; in Cassandra the deleted head of a partition becomes a graveyard every read must walk.

What you see: The warnings in the node log, then the failure.

tombstone-log.txtruns offline
# illustrative output
WARN  Read 1 live rows and 1042 tombstone cells
      for query SELECT * FROM jobs_by_queue ...
ERROR Scanned over 100001 tombstones; query aborted
      (tombstone_failure_threshold = 100000)

Why: The live data is one row, but the scan reads 100,001 dead cells first. Latency grows with the dead count, not with the live count.

Land it I never model a queue as insert-then-delete in one partition; I bucket by time and drop buckets whole, or use Kafka.

Likely follow-ups
"What is the bucketed fix?"

Make the partition a time bucket, and delete whole buckets, never rows inside them.

  1. Key: partition by (queue, hour) with the job id as clustering column, so each partition holds one hour of work.
  2. Work: workers read only the current bucket, so reads never walk through dead rows of older hours. A finished job gets a status update, not a delete.
  3. Drop: when an hour is fully done and old enough, delete the whole partition, which writes a single partition tombstone.

Here is the shape:

jobs_by_hour.cqlillustrative
-- illustrative
CREATE TABLE jobs_by_hour (
  queue text, hour timestamp, job_id timeuuid, payload text,
  PRIMARY KEY ((queue, hour), job_id));
DELETE FROM jobs_by_hour WHERE queue = 'emails' AND hour = '2026-11-25 10:00:00+0000';

For reads in the healthy bucket, there are no tombstones to skip. The cost is that a job picked up late spans two buckets, so workers check the current and previous hour. Choose the bucket so one partition stays well under the 100 MB guideline: if the queue gets 20 jobs a second at 1 KB each, an hour is about 72 MB, so I would use 15-minute buckets instead.

"Can TTL replace the deletes?"

Yes for data that expires on its own, but TTL does not remove tombstones, it creates them. When a cell's TTL runs out it turns into a tombstone, and lots of expired cells in one partition behave like lots of deletes.

Take a queue partition with 200,000 rows each given a one-hour TTL. After an hour a read at the head must step over the expired rows until compaction removes them, and the read can hit the 1,000 warning or the 100,000 failure threshold exactly as before.

What fixes it is time-bucketed partitions combined with TimeWindowCompactionStrategy (Q69). TWCS puts data from the same time window in the same file, so when every cell in a file has expired and the grace period is over, Cassandra drops the whole file without reading it.

So TTL is a good replacement for delete jobs when you also bucket by time and use TWCS, and a bad one when everything sits in a single partition.

"Should I raise the failure threshold?"

No. The failure threshold is a safety valve, and raising it only moves the crash somewhere more painful.

Here is what it protects. To answer one read, the node must hold the tombstones it scans, and the coordinator must receive them, in memory. At 100,000 tombstones per read this is already heavy. If you raise the limit tenfold to 1,000,000, a single bad query can fill the heap, trigger long garbage-collection pauses, and make the node look dead to its peers. Then the load shifts to other nodes, which hit the same problem.

The warning at 1,000 is the useful signal. The log line says how many live rows and tombstone cells a query scanned, and for which table, so I treat each one as a bug report on the data model.

I would raise the limit only for a day, as a bridge, while the new bucketed table is being back-filled. Then I put it back.

"What do I use instead of a queue?"

Use the right tool for each half of the job: a log for the work list, and a table for the state of each job.

  1. Work list: put jobs on a Kafka topic (see the Kafka chapter). Consumers read in order, track offsets, and nothing is deleted. In Kafka 4.2, share groups give queue-style per-record acknowledgement if you need it.
  2. Job state: keep one row per job in jobs_by_id with a status column. Updates overwrite the same row, so there are no deletes.
  3. Workers: a worker takes a message, does the work, writes DONE, and acknowledges. A retry repeats the same upsert, so it is safe.

The rule I remember is to keep the work list outside Cassandra and the state inside. If a lookup of one job by id is not needed, I skip the table entirely.

Q63. "What is gc_grace_seconds, and what is a 'zombie' row?"

Reveal answer

Strong answer gc_grace_seconds is how long Cassandra keeps a tombstone before compaction may remove it. The default is 864,000 seconds, ten days.

During those days repair must run, so every replica learns about the delete. After a successful repair all three copies hold the marker.

A zombie is a deleted row that comes back. It happens when a replica missed the delete, the marker was purged on the other replicas, and then repair copied the old row from the stale replica.

Picture it Three replicas, one missed the delete.

The setup: Replica C is down for 12 days. The other two purged the tombstone after day 10.

Relational · PostgreSQL

Postgres has no equivalent, because deletes go through one log.

pg.sqlruns offline
DELETE FROM orders WHERE id = 42;
-- the standby replays the same WAL record
-- no replica can hold an old copy

Cassandra · CQL

Each replica decides on its own, so the marker has to outlive the outage.

zombie.cqlruns offline
DELETE FROM orders_by_id WHERE id = 42;
-- A,B: tombstone, purged at day 10
-- C offline for 12 days
-- day 12: C returns holding the old row
-- repair copies it back  -> zombie

The shift: One log means no zombies; many replicas mean the marker must live longer than any outage.

Make the invisible visible: The timeline of a zombie.

zombie.txtruns offline
# illustrative output
day 0   delete -> tombstone on A,B  (C offline)
day 10  gc_grace over: A,B compact the tombstone away
day 12  C starts, still holds order 42 (old value)
day 12  repair: A,B have no row, C has one -> C wins
        order 42 is alive again

Why: The rule: every node must be repaired, or replaced, within gc_grace_seconds of being down. A node down longer than that should be wiped and rebuilt, not just restarted.

Land it I keep gc_grace_seconds longer than my longest tolerated outage and repair schedule, and rebuild any node that was down longer.

Likely follow-ups
"Can I lower gc_grace_seconds?"

Yes, when the repair schedule and your outages allow it. The rule is that gc_grace_seconds must be longer than the time between two successful repairs of the table, plus the longest outage you accept before a node is rebuilt.

grace_budgetillustrative
# illustrative
repair cycle   every 7 days (the full run takes 3 days, so allow 7)
node outage    accept up to 3 days before rebuilding the node
gc_grace >= 7 + 3 = 10 days     -> the default of 864000 s is right

For a table that is only written with TTL and never deleted by hand, there is no delete that a replica could miss, so lowering it to a day or two is common, since expired data can leave the disk sooner. Check the current docs for the guidance on your compaction strategy.

For a table with real deletes and a weekly repair, I leave the default alone. Lowering it without repair is how zombies are made, and a shorter grace saves disk but costs correctness when something goes wrong.

"What about TTL data?"

Expired TTL cells become tombstones, so TTL data is subject to the same grace wait, and total life on disk is the TTL plus gc_grace_seconds.

ttl_plus_graceillustrative
# illustrative
TTL 7 days + gc_grace 10 days = 17 days on disk
at 100 GB/day:   17 x 100 GB = 1.7 TB   instead of  7 x 100 GB = 700 GB
gc_grace 1 day (no hand deletes): 8 days = 800 GB

With TWCS the whole file for an old window is dropped once every cell in it has expired and the grace has passed, so the disk comes back in steps, not gradually. Mixing different TTLs in one table spoils that, because one long-lived cell keeps a whole file alive.

The plan is to size disk for the 17 days, not the 7, and to leave about half the disk free as headroom for compaction. For QuickBite's rider_track, with a 7-day TTL, I would also lower gc_grace_seconds since nothing deletes by hand. A cheaper disk bill is the reward, and the risk is only that a node down longer than the new grace must be rebuilt, not just restarted.

"How do I know I'm at risk?"

I check three things, because zombies come from repair gaps and not from the data itself.

  1. Last repair per table: from the repair scheduler. Cassandra Reaper shows the age of the last successful repair for each token range. If the oldest range is older than gc_grace_seconds, you are exposed now.
  2. Longest node outage: look at monitoring for any node that was down for longer than gc_grace_seconds. Such a node must not rejoin as is; wipe it and rebuild it, or repair it before it serves reads.
  3. Settings per table: list gc_grace_seconds for every table, because someone may have lowered it for one table and forgotten.

I alert when repair age passes about 70 percent of the grace, so there is time to react before the real deadline.

"Does a single-node cluster care?"

No. With one copy of the data there is nobody to disagree with, so a zombie cannot appear. The problem needs a replica that missed the delete and another replica that did not, which means RF above one.

The same applies to a PostgreSQL primary with no standby. One history, one answer.

This is also why the bug is a classic surprise in production. A developer's laptop runs a single node, deletes work perfectly, and the tests pass. Months later a node is down over a long weekend in a three-node cluster, a delete happens, and ten days after, rows reappear in reports.

My habit is to run integration tests against a three-node cluster with RF 3 whenever the test is about deletes, repair or consistency. A single-node test cannot show the problem, so it cannot prove its absence.

Q64. "How does TTL work, and what are its traps?"

Reveal answer

Strong answer A TTL (time to live) is a number of seconds after which a cell expires. You set it per write with USING TTL 3600 or for the table with default_time_to_live.

When the time is up the cell becomes a tombstone and is purged after the grace period. You never run a delete job.

Trap one: the TTL belongs to the cell, not the row, and an update with no TTL gives the new value no expiry. Trap two: a massive expiry at the same moment makes many tombstones at once.

Picture it Keep rider positions for one hour.

The setup: QuickBite stores the last GPS points of each rider and wants them gone after an hour.

Relational · PostgreSQL

A relational app runs a cron delete.

ttl.sqlruns offline
-- every 5 minutes
DELETE FROM rider_points
 WHERE ts < now() - interval '1 hour';
-- locks, bloat, vacuum, a job to monitor

Cassandra · CQL

The write carries its own expiry.

ttl.cqlruns offline
INSERT INTO rider_points
  (rider_id, ts, lat, lon)
VALUES (9, toTimestamp(now()), 12.97, 77.59)
USING TTL 3600;  -- gone in 1 hour
-- or default_time_to_live = 3600 on table

The shift: Relational expiry is a job you run; Cassandra expiry is a property of the write.

What you see: TTL counting down, and the update trap.

ttl.txtruns offline
# illustrative output
SELECT lat, TTL(lat) FROM rider_points ...;
 lat   | ttl(lat)
-------+---------
 12.97 | 3597
UPDATE rider_points SET lat = 12.98 ...;  -- no USING TTL
 -- ❌ TRAP: lat now has NO expiry (ttl = null)

Why: Each cell keeps the TTL it was written with. A later write without TTL replaces the cell with a non-expiring one. Setting default_time_to_live on the table avoids the trap.

Land it I set default_time_to_live on the table for time-bound data, so no write can forget it.

Likely follow-ups
"When do expired rows leave the disk?"

The cell does not leave the disk when the TTL ends. Several stages pass, and disk use lags the TTL by days.

  1. At expiry: reads stop returning the cell at once, because the engine checks the expiry time on every read. The cell is still in the file.
  2. Grace period: the expired cell is now a tombstone and stays for gc_grace_seconds, 10 days by default.
  3. Compaction: only after that can a compaction remove it. With TWCS, the whole file of an old window is deleted at once when everything in it has expired and the grace has passed.

A 7-day TTL with a 10-day grace therefore means about 17 days from write to disk space returned (illustrative; compaction timing adds more). I plan disk capacity for that number, not for the 7.

"Can I change a TTL later?"

Only for new writes, and you cannot update a TTL in place. Changing default_time_to_live on the table affects writes that arrive afterwards. Cells already written keep the expiry they were given at write time.

alter_ttl.cqlillustrative
-- illustrative
ALTER TABLE rider_track WITH default_time_to_live = 1209600;
-- 14 days (14 x 86400), applies to new writes only

To change the life of old data you must rewrite it: read the rows and write them again with USING TTL, which creates load and new tombstones. For a big table I would rather start a new table with the new value and let the old one expire.

So I decide the TTL early, from the business rule (for example, a rider's track is useful for seven days), and write it down. PostgreSQL has no TTL, so there the same rule is a nightly DELETE job.

"What is the largest TTL?"

It is a 32-bit field counting seconds, and the documented maximum TTL is 630,720,000 seconds, which is 20 years. The expiry time itself is stored as a date in seconds since 1970, which brings the year-2038 limit into play. Recent versions added overflow handling; check the docs for the exact behaviour in your version.

The arithmetic is simple. 20 years is 20 x 365 x 86,400 = 630,720,000 seconds. A write with a TTL that ends after the date limit is capped or rejected, depending on the policy.

I would never design around a TTL measured in decades. Data that must live that long should have no TTL, and its removal should be an explicit, planned operation: delete by partition, or use a table per period that you drop whole.

For data you only need for weeks or months, TTL is exactly right.

"TTL on a primary key column?"

No, TTL applies to non-key cells only. A primary key column is never given an expiry. What matters is how the row is created.

row_marker.cqlillustrative
-- illustrative
INSERT INTO menu_by_restaurant (restaurant_id, item_id, name)
VALUES (?, ?, 'special') USING TTL 3600;   -- the whole row expires
UPDATE menu_by_restaurant USING TTL 3600 SET name = 'special'
WHERE restaurant_id = ? AND item_id = ?;   -- only name expires

The row is only as alive as its markers. INSERT also writes a small marker meaning "this row exists", and it gets the TTL too, so the row disappears when everything has expired. UPDATE writes no marker, so the row lives as long as any cell without an expiry remains.

So to expire a whole row, I use INSERT ... USING TTL, and I set the table-level default so that no write path can forget it. The classic mistake is a plain UPDATE path that writes a value without any TTL: that cell never expires, and the row stays alive forever.

Q65 · Design. "Design a notification 'inbox' where users read and dismiss messages. Deleting a read message is common."

Reveal answer

Strong answer Avoid the one-row-per-message-then-delete pattern inside a single huge partition. Dismissing a message by deleting rows creates tombstones inside the partition the user reads every time.

Better: partition by (user_id, month), order by time, and store a read flag or a status column on the row. Dismissal is an update, not a delete.

Expire the whole thing with a TTL (for example 90 days). Old months leave on their own.

Picture it One user, a hundred notifications a day.

The setup: A busy user gets 100 a day and dismisses most.

Relational · PostgreSQL

A normalised table; delete or flag a row.

inbox.sqlruns offline
CREATE TABLE notifications (
  id bigserial PRIMARY KEY,
  user_id bigint, body text,
  created timestamptz, dismissed bool);
CREATE INDEX ON notifications (user_id, created);
UPDATE notifications SET dismissed = true ...

Cassandra · CQL

A bucketed table, a flag, a table TTL.

inbox.cqlruns offline
CREATE TABLE inbox_by_user_month (
  user_id bigint, month text,
  created timeuuid, body text,
  dismissed boolean,
  PRIMARY KEY ((user_id, month), created)
) WITH CLUSTERING ORDER BY (created DESC)
  AND default_time_to_live = 7776000;

The shift: Relationally you index and filter; in Cassandra you shape the partition so deleting is never needed.

What you see: The read and the dismissal.

inbox-read.txtruns offline
# illustrative output
SELECT * FROM inbox_by_user_month
 WHERE user_id = 7 AND month = '2026-11'
 LIMIT 20;                  -- newest 20, one partition
UPDATE inbox_by_user_month SET dismissed = true
 WHERE user_id = 7 AND month = '2026-11'
   AND created = <timeuuid>;  -- an update, no tombstone

Why: Updates write a newer cell and leave the row in place. Reads stay in one partition and the oldest months expire as whole windows.

Land it I turn a delete into a status update plus a TTL, and bucket by month so one partition never grows without bound.

Likely follow-ups
"How do I show only unread?"

Keep the unread state inside the partition and filter it with a small index, or filter in the application. Both are cheap because the partition is one user in one month.

unread.cqlillustrative
-- illustrative
CREATE INDEX inbox_status_idx ON inbox_by_user_month (status) USING 'sai';
SELECT * FROM inbox_by_user_month
WHERE user_id = ? AND month = '2026-11' AND status = 'UNREAD' LIMIT 20;
-- PostgreSQL: a partial index WHERE status = 'UNREAD' does this job

The partition key is given, so the SAI index only searches that one partition, not the cluster. If I do not want an index at all, I read the newest 50 rows and filter on the app side, which costs one read of about 25 KB (50 rows at 500 bytes, illustrative).

I would not copy unread messages into a second table that is deleted from when read. That recreates the tombstone problem in a smaller place. And I would never use ALLOW FILTERING on a partition I do not control the size of.

"What is the partition size?"

Small, if I do the arithmetic before choosing the bucket.

inbox_sizeillustrative
# illustrative
normal user:  100/day x 30 days = 3,000 rows x 500 B  =   1.5 MB
spammy user:  10,000/day x 30   = 300,000 rows x 500 B = 150 MB
spammy user, day bucket: 10,000 rows x 500 B           =   5 MB

The normal user is far below the guideline of about 100 MB and 100,000 rows, and the heavy-bucket row count of 10,000 per day is far below it as well. The spammy user, with a monthly key, is above both limits, which is when reads, repair and compaction start to slow down.

I would also ask how many users are heavy, not only how heavy the heaviest is, because that decides whether the exception is a rule. The key choice follows. I use (user_id, month) for everyone, and I switch the heavy accounts to a day bucket, which means the reader checks the current and previous bucket. If most users are heavy, I make the day bucket the default and accept two small reads.

"Why timeuuid for created?"

A timeuuid is a time-based unique id: it holds a timestamp with 100-nanosecond precision and extra bits that make it unique. Cassandra sorts it by the time part, so it works as a clustering column that orders messages and also identifies each one.

A plain timestamp has millisecond precision. If two messages for the same user and month arrive in the same millisecond, they have the same primary key, and because every write is an upsert, the second silently replaces the first.

timeuuid.cqlillustrative
-- illustrative
INSERT INTO inbox_by_user_month (user_id, month, created, title)
VALUES (?, '2026-11', now(), 'Order delivered');
SELECT toTimestamp(created), title FROM inbox_by_user_month
WHERE user_id = ? AND month = '2026-11' LIMIT 20;

In PostgreSQL I would use an identity column for uniqueness and a timestamptz for time. Here one column does both jobs, and toTimestamp() recovers the readable time. The id also works as a stable cursor for paging: the app remembers the last created it saw and asks for older ones.

"Can I hard-delete on user request, for privacy?"

Yes. A privacy deletion is a legitimate delete, and the way to do it cheaply is by partition.

  1. Find the partitions: the partitions are (user_id, month). I count the months from the signup date to today, so there is no table scan.
  2. Delete by partition: run DELETE FROM inbox_by_user_month WHERE user_id = ? AND month = ? for each month. Each writes one partition tombstone, which is cheap to write and to read.
  3. Wait for the purge: reads stop showing the data at once, but the bytes leave the disk only after gc_grace_seconds and compaction. Repair must reach every replica before that.

I would tell the privacy team that physical removal lags the logical delete by about ten days, and that backups and snapshots need their own expiry rule. I leave the exact legal wording to them.

Q66. "What is the difference between deleting a row, a range and a whole partition in terms of cost?"

Reveal answer

Strong answer A row delete writes one tombstone for one row. A range delete writes one tombstone that covers a range of clustering values. A partition delete writes one tombstone for everything under that partition key.

Range and partition deletes are cheap to write and cheap to read, because the reader sees one marker and skips the whole region.

The costly case is deleting rows one by one: 10,000 single-row deletes make 10,000 markers to walk. Prefer one range or partition delete when you can.

Picture it Remove one day of readings.

The setup: A sensor has 86,400 readings for one day in a bucketed partition.

Relational · PostgreSQL

DELETE ... WHERE ts BETWEEN is one statement, but it touches every row in the heap.

range.sqlruns offline
DELETE FROM readings
 WHERE sensor_id = 5
   AND ts >= '2026-11-01'
   AND ts <  '2026-11-02';
-- 86,400 row versions marked dead

Cassandra · CQL

Drop the partition for that day, one marker.

range.cqlruns offline
DELETE FROM readings_by_sensor_day
 WHERE sensor_id = 5
   AND day = '2026-11-01';
-- ✅ partition tombstone: ONE marker
-- vs 86,400 single-row deletes

The shift: Relational cost grows with the rows touched; Cassandra cost depends on the shape of the delete.

Make the invisible visible: Markers written by each method.

markers.txtruns offline
# illustrative output
method                      tombstones written
86,400 single-row deletes   86,400  (reads must skip all)
1 range delete (clustering) 1
1 partition delete          1  <- best
TTL 1 day on each row       86,400 expire together

Why: The reader merges tombstones at read time. One marker covering a wide area is cheap; many small markers are not.

Land it I delete at the largest unit I can: whole partitions by key, or a clustering range, never row by row.

Likely follow-ups
"Can I do a range delete on any column?"

No. A range delete follows the primary key, so it works on the clustering columns, as a prefix, in order. You cannot range-delete by a regular column, because Cassandra would have to read the rows first to know which ones match.

Take orders_by_customer with the key ((customer_id), placed_at DESC, order_id). Deleting all orders before a date is a legal range delete, because placed_at is the first clustering column.

range_deleteillustrative
-- illustrative
-- Cassandra: allowed, it follows the clustering order
DELETE FROM orders_by_customer WHERE customer_id = ? AND placed_at < '2026-01-01';
-- PostgreSQL: any column works, the planner finds the rows
DELETE FROM orders WHERE customer_id = 7 AND status = 'CANCELLED';

Deleting by status in Cassandra would be rejected, because status is not a key column. So the key and the bucket design decide which deletes are cheap. If the business needs to remove all CANCELLED orders, I either put status into the key design or accept a read followed by single deletes. I check the planned delete jobs while I design the table, not after.

"Is TRUNCATE better for clearing a table?"

TRUNCATE is the right tool to clear a whole table, and it is not a tombstone. By default Cassandra first takes a snapshot (the setting is auto_snapshot) and then discards the SSTables and the memtable, so it is fast and writes no markers.

The catch is that it needs every node to be up. If any replica is down, the request fails, because the cluster cannot be sure all copies are cleared. It also has its own timeout, and on a very large table it can take a while to remove the files.

The snapshot also means the disk space is not freed until you remove the snapshot, with nodetool clearsnapshot. That surprises people who truncate to reclaim space.

I use it in test and staging environments and for tables I rebuild completely. I do not run it on a live table that serves traffic, because readers see an empty table the moment it completes.

"What does the relational DROP PARTITION compare to?"

The nearest relational idea is dropping a whole partition of a partitioned table, and it is closer to TWCS than to a row delete.

drop_partitionillustrative
-- illustrative
-- PostgreSQL: detach and drop a month; files are removed at once
ALTER TABLE events DETACH PARTITION events_2026_10;
DROP TABLE events_2026_10;
-- Cassandra: a partition delete writes one marker; space returns later
DELETE FROM sensor_by_day WHERE sensor_id = ? AND day = '2026-10-01';

In PostgreSQL the files disappear when the table is dropped, and the space is back at once. In Cassandra a partition delete writes one cheap marker, but the data stays until compaction after the grace period.

The behaviour that matches PostgreSQL is a table per time period that you drop whole, or TWCS dropping an expired file. That is why I use time buckets for data that has to be removed regularly: the unit of deletion and the unit of storage line up, so removal is a drop of one thing, not a hunt for many rows.

"Does a partition delete free space immediately?"

No. A partition delete writes one marker, and the space comes back only after the grace period and a compaction that can actually merge the marker with the data it covers.

Take a partition of 10 GB deleted today with the default 10-day grace. Today the disk grows by a few bytes and reads stop returning the data. Ten days later the marker becomes purgeable. After that, a compaction involving the files that hold the data finally rewrites them without it. The disk shrinks later still, and compaction needs temporary room while it runs.

One exception is TWCS: if the whole window is expired and nothing overlaps, it deletes the file directly, with no rewrite.

So when I plan a bulk cleanup, for example removing a year of old data to free a full disk, I do not rely on it. I add disk first, delete in slices, and watch free space and pending compactions during the days that follow.

Drill · Read path, write path and compaction

Storage mechanics decide speed. These four questions check that you can explain in plain words why writes are cheap, reads merge pieces, and compaction keeps the number of pieces low.

Q67. "Walk me through the Cassandra read path. Why can a read be slower than a write?"

Reveal answer

Strong answer A read first finds the replicas with the partition key's token. On each replica it checks the memtable (recent writes in memory) and then the SSTables (immutable files on disk).

For each SSTable it asks a Bloom filter ("could this partition be here?"), then the partition index, then reads the rows. It merges all pieces by timestamp and returns the newest.

A write only appends to the commit log and memtable. A read may touch many files and merge them, so a read is slower than a write and gets worse with more SSTables.

Picture it One row found across four places.

The setup: Order 42 was written in the morning, updated at noon and again now.

Relational · PostgreSQL

Postgres: B-tree index to the heap page, check row visibility.

read.sqlruns offline
SELECT * FROM orders WHERE id = 42;
-- 1 walk B-tree from root to leaf
-- 2 follow pointer to heap page
-- 3 check the row version is visible
-- one place holds the row

Cassandra · CQL

The row may live in several files; merge them.

read.cqlruns offline
SELECT * FROM orders_by_id WHERE id = 42;
-- 1 token -> replicas (partitioner)
-- 2 memtable (memory)
-- 3 each SSTable: Bloom filter, then index
-- 4 merge cells, newest timestamp wins

The shift: Relational reads follow one pointer to one row; Cassandra reads assemble a row from pieces.

Make the invisible visible: Four sources for one row.

readpath.txtruns offline
# illustrative output
memtable        status=PREPARING   ts=900
SSTable-3       status=ACCEPTED    ts=700
SSTable-2       (bloom: not here)  skipped
SSTable-1       total=18.50        ts=100
merged row: total=18.50, status=PREPARING

Why: Each file costs a Bloom check and maybe a disk read. Compaction (Q69) keeps the number of files low.

Land it I say a write is one append, a read is a merge, and I keep SSTables per read low with the right compaction.

Likely follow-ups
"What does the Bloom filter do?"

A Bloom filter is a small in-memory summary of which partition keys a file might contain. It answers "definitely not here" or "maybe here". It never gives a false negative, so a data file that holds the key is never skipped, but it sometimes gives a false positive, which costs one wasted disk lookup.

bloom_mathillustrative
# illustrative
bloom_filter_fp_chance = 0.01  ->  about 10 bits per partition key
100,000,000 partitions x 10 bits = 1,000,000,000 bits = about 125 MB of memory
a read over 10 SSTables with only 1 holding the key:
  with 1% false positives, about 0.09 extra disk lookups instead of 9

That is the whole point: the read skips nearly every file that does not hold the key without any disk access. A lower false-positive chance costs more memory per key. The default is about 0.01 for most strategies (check the docs for your table's strategy), and I only tune it when memory is tight or when a table has very many files. It is a cheap structure that pays for itself on almost every read.

"Where do key cache and row cache fit?"

They are separate caches at different levels, and neither is the main source of speed.

  1. Key cache: remembers, for each partition, the offset of its start in an SSTable. A hit skips the partition-index lookup. It is on by default and small, and it helps most with many hot, small partitions.
  2. Row cache: holds whole hot partitions in memory. It is off by default and rarely worth it, because any write to the partition invalidates it, and a big partition will not fit.
  3. OS page cache: does most of the work. The recently read parts of the SSTable files live in the operating system's memory, so a hot read does not reach the disk at all.

This is why I leave memory for the operating system and do not give the whole machine to the Java heap. If the working set outgrows the page cache, read latency rises even when nothing in Cassandra has changed.

"What is the coordinator's role?"

Any node can be coordinator, and the coordinator is the node the client talked to for this request. It does four jobs.

  1. Find replicas: hash the partition key to a token, and look up the replicas that own it.
  2. Ask: send a full data request to one replica and digest (hash) requests to as many others as the consistency level needs.
  3. Compare: if the digests differ, fetch full data, pick the newest cell by timestamp, and repair the stale replica.
  4. Answer: return the merged result. If a replica is slow, a speculative retry may ask another one early.

A token-aware driver sends the request straight to a node that is a replica for the key, so the coordinator is also a replica and the extra hop disappears. That saves about one network round trip per request, which matters at high request rates.

"How does Postgres differ in tuning?"

The goal is the same, touching little data, but the knobs are different, because the storage engines are different.

QuestionPostgreSQLCassandra
Where does the speed come from?Right index, shared buffers, planner choiceRight table for the query, so one partition is read
Main tuning knobsshared_buffers, work_mem, indexes, autovacuumCompaction strategy, partition size, bloom filter chance, cache sizes
How do I find the slow part?EXPLAIN (ANALYZE, BUFFERS)nodetool tablehistograms, tracing, SSTables per read
What bloats over time?Dead rows, until vacuumMany SSTables and tombstones, until compaction

In PostgreSQL I can add an index to fix a slow query. In Cassandra the equivalent is often a new table, because the planner will not invent a better access path. So I tune by checking SSTables per read first, then partition size, then tombstones.

Q68. "Why are Cassandra writes so fast?"

Reveal answer

Strong answer A write does two cheap things: it appends the mutation to the commit log on disk (sequential, no seeking) and puts it in the memtable in memory. Then it acknowledges.

No index is updated, no old row is read, no page is rewritten. The memtable is later written out as an immutable SSTable in one sequential flush.

The cost is moved to later: compaction merges files in the background. That is why heavy writes need disk headroom.

Picture it Count the disk operations for one write.

The setup: An insert of one order row with a table that has no secondary indexes.

Relational · PostgreSQL

Postgres writes to the WAL, then updates the heap page and every index.

write.sqlruns offline
INSERT INTO orders (id, cust, total)
VALUES (42, 7, 18.50);
-- 1 WAL record (sequential)
-- 2 heap page (random)
-- 3 each index: B-tree leaf (random)
-- 4 later: checkpoint, vacuum

Cassandra · CQL

Append and remember; merge later.

write.cqlruns offline
INSERT INTO orders_by_id (id, cust, total)
VALUES (42, 7, 18.50);
-- 1 commit log append (sequential)
-- 2 memtable insert (memory)
-- ack; no read, no index, no seek
-- later: flush, compaction

The shift: Relational engines pay at write time to keep reads cheap; Cassandra pays at read and compaction time to keep writes cheap.

Make the invisible visible: The life of the write.

write-path.txtruns offline
# illustrative output
t=0 ms  commit log append (sequential, fsync batch 10 ms)
t=0 ms  memtable updated
t=1 ms  ack to client at the chosen consistency
t=5 min memtable full -> flushed to SSTable-7
later   compaction merges SSTable-7 with others

Why: Sequential appends are the fastest thing a disk does. Moving random work to the background is the core trick.

Land it I describe writes as append plus memory, and I remember the debt: compaction and disk space.

Likely follow-ups
"Is the commit log needed if memtable is in memory?"

Yes, because the memtable is only memory, and a crash empties memory. The commit log is the safety copy. It is a sequential file that every write is appended to, and when the node restarts it replays the log to rebuild the memtable.

This is the same idea as PostgreSQL's write-ahead log. PostgreSQL also acknowledges a commit once the change is in the log, and writes the data pages later at a checkpoint. Cassandra's difference is that the final home, the SSTable, is written once and never edited.

log_lifeillustrative
# illustrative
write -> commit log segment (append) + memtable (memory) -> ack
memtable full or log too large -> flush to a new SSTable
all writes in a log segment now safe in SSTables -> segment recycled

So the commit log is for durability and the SSTable is the long-term store. I put the commit log on its own fast disk where I can, because its fsyncs should not wait behind compaction reads.

"What is commitlog_sync?"

It decides when the commit log is forced to disk, and so how much a node can lose if its power fails.

  1. periodic: the default. The write is acknowledged immediately, and the log is synced every 10 seconds (commitlog_sync_period). It is the fastest, and a power cut can lose up to about 10 seconds of writes on that node.
  2. group: the write waits for the next sync in a short window, so acknowledged writes are on disk, and many writes share one sync.
  3. batch: the write waits for its own sync before it is acknowledged. It is the safest and slowest.

The loss only matters if every replica loses power at once, because the other replicas still hold the data. With RF 3 across racks that is unlikely. The PostgreSQL parallel is synchronous_commit = off, which can also lose a very short tail of commits. I keep the default for most tables and use group mode when a business rule says no acknowledged write may be lost.

"Does an upsert cost the same as an insert?"

Yes. An upsert costs the same as an insert, because Cassandra never reads before it writes. An insert of a new row and an overwrite of an existing row are the same append of a cell with a timestamp.

upsert.sqlillustrative
-- illustrative
-- PostgreSQL: UPDATE finds the old row, writes a new version, leaves a dead one
UPDATE menu SET price = 200 WHERE id = 1;
-- Cassandra: INSERT and UPDATE both append a cell with a timestamp
UPDATE menu_by_restaurant SET price = 200 WHERE restaurant_id = ? AND item_id = ?;

That is why CQL treats the two as one idea. A small difference: INSERT also writes a row marker, so the row exists even if all other cells are later deleted, and UPDATE does not.

The exceptions that do read first are counters and lightweight transactions, which is one reason they are slower and used sparingly. The relational cost of an update, a new row version plus later vacuum work, simply does not exist here; Cassandra pays the bill later in compaction instead.

"What slows writes down?"

Writes are fast until something upstream or downstream runs out of room.

First, the commit log disk. A slow or shared disk makes every sync slow, which shows up as latency on all writes. Second, compaction falling behind: flushes keep creating files, so reads and flushes slow down and memtables back up. Third, large partitions and big batches: a batch ties up the coordinator, and flushing a huge partition takes longer.

Fourth, too many tables. Each table has its own memtable, so hundreds of tables create memory pressure and many small flushes. Fifth, Java garbage-collection pauses, which stall a node for hundreds of milliseconds.

To see it, I look at nodetool tpstats for pending or dropped mutations, and at pending compactions. My first fixes are a separate fast disk for the commit log, then fewer and smaller batches, then more nodes. I would not tune memtable settings before measuring.

Q69. "Which compaction strategy would you choose for a chat table, a sensor table and a read-heavy catalogue?"

Reveal answer

Strong answer Compaction merges SSTables so reads touch fewer files and old data is dropped. The strategy decides which files are merged and when.

STCS (size-tiered, the long-time default) is good for write-heavy loads. LCS (leveled) keeps rows in few files per level, good for read-heavy work with updates. TWCS (time-window) groups files by time, ideal for time series with a TTL. UCS (new in 5.0) is one adaptive strategy that can behave like the others.

So: chat messages are append-heavy and read mostly recent data (TWCS or STCS), sensor data with TTL uses TWCS, and a catalogue with frequent updates and many reads uses LCS or UCS.

Picture it Pick by access pattern, not by habit.

The setup: Three tables with different shapes.

Relational · PostgreSQL

Postgres has one engine; you tune autovacuum and indexes.

vacuum.sqlruns offline
ALTER TABLE readings SET (
  autovacuum_vacuum_scale_factor = 0.02);
-- partition by month, drop old tables
DROP TABLE readings_2026_08;

Cassandra · CQL

The strategy is a per-table setting.

compaction.cqlruns offline
ALTER TABLE readings_by_sensor_day WITH
 compaction = {
  'class': 'TimeWindowCompactionStrategy',
  'compaction_window_unit': 'DAYS',
  'compaction_window_size': 1};

The shift: Relationally you tune one general engine; in Cassandra you pick a storage layout to match each table's access pattern.

Make the invisible visible: Choosing by the table's shape.

compaction-choice.txtruns offline
# illustrative output
table              pattern                  pick
messages_by_conv   append, read recent      TWCS or STCS
readings (TTL 30d) append, expire by time   TWCS
catalogue_by_cat   read-heavy, updates      LCS (or UCS)
unsure / mixed                              UCS (5.0)

Why: TWCS lets a whole old window be deleted as one file. LCS pays extra write work to keep each row in few files. STCS is cheapest for writes but may leave a row in many files.

Land it I match compaction to the shape: TWCS for time series with TTL, LCS for read-heavy updated data, STCS for general writes, and UCS when I want one adaptive default on 5.0.

Likely follow-ups
"What is the cost of LCS?"

LCS pays for its cheap reads with extra writes. It keeps files in levels, each level about ten times larger than the one above, and data that moves up a level is rewritten so that no key range appears twice in a level. That rewriting is write amplification.

Worked example with an assumed factor: ingest of 100 MB/s and write amplification 10 means about 1 GB/s of compaction writing (illustrative; the real factor depends on the data and the level count).

The benefit is that a read looks at about one file per level, so latency is steady and space overhead is low. For a mostly-read table such as a menu catalogue, that trade is good.

For write-heavy data, LCS can fall behind and files per read rise. Then I use TWCS for time series, or STCS or UCS for general writes.

"Why does TWCS break with out-of-order writes?"

TWCS only works well if data in a time window arrives in that window. Three things break the assumption.

  1. Late or backdated writes: a backfill that writes last month's rows puts old data into the files of the current window, so those files can never be dropped whole.
  2. Mixed TTLs: one long-lived cell in a file keeps the whole file alive after the rest has expired.
  3. Repair streaming: repair can bring old data into new files, so repairs on a TWCS table need care. Check the current docs for the recommended repair setup.

The result is that disk is not returned on schedule and old windows keep being compacted. For QuickBite's rider_track (7-day TTL, no backfill) it fits well. If I must backfill, I write the history to a separate table, or give it the right timestamps and keep it out of the live table.

"Can I change the strategy on a live table?"

Yes, with an ALTER TABLE, but the cost is real. The new strategy only changes how future compactions choose files, so the existing SSTables are reorganised gradually, using disk and I/O.

alter_compactionillustrative
-- illustrative
ALTER TABLE menu_by_restaurant
WITH compaction = {'class': 'LeveledCompactionStrategy'};

For a large table, moving from STCS to LCS can mean rewriting most of the data into levels, which may take hours or days and needs free space while it runs. Reads can get worse before they get better.

My plan is: try it on a copy of the data, pick an off-peak time, lower compaction_throughput so live traffic is not hurt, and watch pending compactions and read latency. Have a rollback ready, which is the same ALTER with the old class. I would not change several tables at once.

"What is UCS in one sentence?"

UCS is the Unified Compaction Strategy, introduced in Cassandra 5.0, one strategy that can behave like tiered or leveled compaction depending on one setting.

The setting is scaling_parameters. A tiered-style value such as T4 favours cheap writes. A leveled-style value such as L10 favours fewer files per read. It can differ per size level, so small files can be tiered and large ones leveled. UCS also splits data by token range into shards, so compactions run in parallel and files stay bounded.

ucs.cqlillustrative
-- illustrative
ALTER TABLE menu_by_restaurant WITH compaction =
  {'class': 'UnifiedCompactionStrategy', 'scaling_parameters': 'T4'};

The attraction is one default for many tables and a way to change behaviour without a different class. The names and defaults are still evolving, so I check the current docs and test on my data before making it the default everywhere.

Q70 · Scenario. "Read latency on a table has crept from 3 ms to 40 ms over six weeks. Nothing changed in the code. What do you check?"

Reveal answer

Strong answer Suspect SSTables per read first. If compaction falls behind, one partition spreads over dozens of files and each read merges them all.

Then check partition size (wide partitions are slower to read), tombstones per read, and the disk (iowait). Look at nodetool tablehistograms and nodetool tablestats.

Fix by catching compaction up, changing the strategy to fit, adding nodes, or shrinking partitions with a better bucket.

Picture it Read the numbers, not the story.

The setup: The orders_by_customer table, 6 weeks of steady growth.

Relational · PostgreSQL

Postgres: look at the plan and the bloat.

explain.sqlruns offline
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 7;
-- check: index used? heap fetches?
-- table bloat? autovacuum behind?

Cassandra · CQL

Look at files per read and partition size.

tablestats.txtruns offline
$ nodetool tablehistograms qb orders_by_cust
$ nodetool tablestats qb.orders_by_cust
-- SSTable count?  SSTables per read?
-- partition size p99?  tombstones per read?
-- pending compactions?

The shift: Relational diagnosis starts from the query plan; Cassandra diagnosis starts from the storage statistics.

What you see: A table that has too many files per read.

histo.txtruns offline
# illustrative output
Percentile  SSTables  Write(us)  Read(us)  Partition(bytes)
50%         12        20         9800      4200
99%         31        60         41000     90000
pending compactions: 214   (was 3 in week 1)
-- 12 files per read is far above a healthy 1-3

Why: Median 12 SSTables per read means each lookup merges a dozen files. Compaction cannot keep up with writes, so give it more IO or switch the strategy.

Land it I check SSTables per read, partition size, tombstones, and pending compactions before touching the query.

Likely follow-ups
"How do I help compaction catch up?"

I help it by giving it more room, and by taking competing work away, in this order.

  1. Raise throughput: compaction_throughput limits how fast compaction may write. Raise it for a while, for example with nodetool setcompactionthroughput 128, and watch the effect on read latency.
  2. Remove competition: pause heavy repairs and bulk loads, because they create more files and compete for the same disk.
  3. Add capacity: more disks, more nodes, or more concurrent compactors, if CPU and disk have room. Keep free space, since size-tiered compaction may need up to half the disk free for a big merge.

Then I watch pending compactions fall:

watch_compactionillustrative
# illustrative
nodetool setcompactionthroughput 128
nodetool compactionstats      # pending tasks should trend down

If it falls and read latency recovers, the cause was compaction. If not, I move to the next suspect.

"What if SSTables per read is fine?"

Then I look at the other suspects, one at a time, using numbers instead of guesses.

First, tombstones per read: nodetool tablestats shows the average tombstones per slice, and the log warns above 1,000. Second, partition size: tablehistograms shows the p99 and the maximum, and a wide partition is the usual suspect after months of growth.

Third, the disk. If iostat shows high wait time, the box is simply too slow for the data. Cassandra expects local SSD or NVMe, not network storage with unpredictable latency.

Fourth, and often missed: the working set may have outgrown the operating system's page cache. Six weeks of growth can push hot data out of memory, and a read that used to come from RAM now goes to disk. That alone can turn 3 ms into 40 ms. Then the fix is more memory per node or more nodes, not a query change.

"Could it be the driver?"

Yes, and I check it by comparing two numbers. nodetool proxyhistograms shows the coordinator's read latency, and nodetool tablehistograms shows the local read latency on the replica. If those are healthy but the application sees a lot more, the time is lost on the client side or in the network.

latency_gapillustrative
# illustrative
coordinator p99 (proxyhistograms)   6 ms
application p99 (driver metrics)   40 ms
unexplained gap                    34 ms -> client, driver, or network

Common client causes are a retry loop that repeats slow requests, a missing token-aware policy so every request takes an extra hop, a connection pool that is too small so requests queue, and application garbage-collection pauses. The Java driver also has speculative executions, which can help with a slow node but double the load if set carelessly.

So I look at the driver's own metrics before I touch the cluster.

"How would I alert on this early?"

I alert on the early signals and on high percentiles, never on the average. A slow creep from 3 ms to 40 ms is nearly invisible in an average, because most requests stay fast while a growing minority is slow.

A worked example: 95 reads at 3 ms and 5 reads at 40 ms give an average of (95 x 3 + 5 x 40) / 100 = 4.85 ms, which looks fine, while the p99 is 40 ms.

SignalWhy it warns early
Pending compactions above a thresholdFiles are piling up before reads feel it
SSTables per read, p99Direct measure of merge work per read
p99 read latency per tableThe user-visible symptom
Tombstones scanned warningsThe delete pattern is hurting reads
Largest partition sizeA wide partition is growing

I set each threshold from a normal week of data, then page on a sustained breach instead of a single spike.

Drill · Queries, indexes and clients

Most production incidents come from asking the cluster a question its keys cannot answer. These questions cover wide and hot partitions, filtering, indexes and materialized views.

Q71 · Scenario. "Reads on one table time out after it grew. A senior says 'wide partition'. What does that mean and how do you prove it?"

Reveal answer

Strong answer A wide partition is one partition key holding a huge number of rows or bytes. Cassandra reads a partition from one replica set, so one giant partition means a giant read and big memory use.

The guideline is to keep partitions under about 100 MB and 100,000 rows. It is not a hard rule, but beyond it reads, repair and compaction all slow down.

Prove it with nodetool tablehistograms (partition size p99, max) and nodetool tablestats (compacted partition maximum bytes). Fix by adding a time or hash bucket to the partition key.

Picture it One customer, two years of events in one partition.

The setup: The key is customer_id only. A power user has 3 million events at 200 bytes: 600 MB.

Relational · PostgreSQL

Postgres hides this: the index finds a slice of rows by (customer, time).

events.sqlruns offline
SELECT * FROM events
 WHERE customer_id = 7
 ORDER BY ts DESC LIMIT 50;
-- index scan reads about 50 index entries
-- table size does not matter

Cassandra · CQL

The partition is one unit; shrink it with a bucket.

events.cqlruns offline
-- ❌ TRAP: PRIMARY KEY (customer_id, ts)
-- ✅ bucket by month
PRIMARY KEY ((customer_id, month), ts)
-- 3M events over 24 months
-- = about 125,000 rows per partition

The shift: A relational index slices a big table for you; in Cassandra the partition key itself must keep each slice small.

Make the invisible visible: The numbers that prove it.

wide.txtruns offline
# illustrative output
$ nodetool tablehistograms qb events_by_customer
Partition Size (bytes): 50%=9 KB  99%=210 MB  max=612 MB
Cell Count:            50%=40    99%=1.1M    max=3.0M
$ nodetool tablestats ...  Compacted partition maximum bytes: 641 MB

Why: The median is tiny, the max is 600 MB. The pain comes from a handful of power-user partitions, which is why averages hide it.

Land it I read the p99 and max of partition size, not the average, and I bucket any key whose rows grow without bound.

Likely follow-ups
"How do I pick a bucket size?"

Estimate rows per partition and bytes per row, then choose the largest bucket that stays under both guidelines: about 100 MB and about 100,000 rows. Size it for the heaviest key, not the average one.

bucket_mathillustrative
# illustrative
50 rows/day x 200 B, monthly bucket = 1,500 rows = 300 KB   -> fine, even a yearly bucket works
5,000 rows/day x 200 B, monthly bucket:
  150,000 rows = 30 MB   -> under 100 MB but over 100,000 rows
5,000 rows/day, weekly bucket = 35,000 rows = 7 MB  -> good

The second line shows that the row count can be the limit before the size is. A larger bucket means fewer partitions to read for a long history, and a smaller bucket means less work per read and per repair, so I take the largest that fits with a margin of two or three times for growth.

I also write the choice in the design doc with the assumption behind it, so someone can rerun the arithmetic when traffic changes. PostgreSQL never asks this question, because a heap table grows without a per-key size limit; in Cassandra the key design is where the limit lives.

"What if the bucket makes reads awkward?"

The reader pays a small extra step. A query for the last 50 events reads the newest bucket, and only if that returns fewer than 50 rows does it read the one before.

two_bucketsillustrative
-- illustrative
SELECT * FROM events_by_sensor_month
WHERE sensor_id = ? AND month = '2026-11' LIMIT 50;    -- returned 12 rows
SELECT * FROM events_by_sensor_month
WHERE sensor_id = ? AND month = '2026-10' LIMIT 38;    -- 50 - 12 = 38 more
-- PostgreSQL: one query, ORDER BY ts DESC LIMIT 50

That is two small reads, each from a single partition, instead of one huge one, and the second read only happens when the first came back short. For a long range, such as a whole year, the app runs the twelve monthly reads in parallel and merges the results, which is still cheaper than one read across an oversized partition.

The judgement is to choose the bucket so that the usual question fits in one or two buckets. If most queries need ten buckets, the bucket is too small.

"Does Cassandra 5.0 make wide partitions OK?"

It helps, but it does not remove the guideline. Cassandra 5.0 introduced trie-based SSTables, which index large partitions with less memory and fewer seeks, so a read inside a big partition is cheaper than before. Check the current docs for the exact format and defaults in your version.

The reasons to stay small are elsewhere. Compaction rewrites a partition each time it merges the files that hold it, so a huge partition means huge rewrites. Repair compares and streams data in ranges, and one giant partition is hard to split into small pieces. A digest mismatch makes a replica read the whole requested slice again, and a big slice means heap pressure and garbage-collection pauses.

There is also a placement limit: one partition lives on one replica set, so it cannot spread across the cluster.

I model small partitions regardless, and treat the new format as a safety margin, not as permission.

"Can I fix an existing wide partition?"

You cannot shrink a partition in place, because the partition key is part of the table's identity. You migrate to a new table with a better key, in stages.

  1. Create: make the new bucketed table, for example with (sensor_id, month) as the partition key.
  2. Dual-write: change the app to write both tables from a chosen moment. Reads still use the old table.
  3. Backfill: copy history in slices, one old partition at a time, using paging, with the original timestamps (USING TIMESTAMP) so old data cannot beat newer writes.
  4. Verify and switch: compare counts and sample rows, move reads to the new table, and later drop the old one after taking a snapshot.

Q96 walks through the same method for any key change. PostgreSQL has a similar-looking ALTER TABLE that rewrites the table in place; Cassandra has no way to change a primary key, so the migration is part of the job.

Q72 · Scenario. "One sensor id is 100 times busier than the others and one node is at 95 percent CPU. What is a hot partition and how do you spread it?"

Reveal answer

Strong answer A hot partition is one partition key that gets most of the traffic. All its replicas are the same three nodes, so those nodes run hot while the others idle.

Cassandra spreads different keys across the ring, but it cannot spread one key. Add a second component to the key, a shard number, to cut the hot key into several partitions.

Writes pick a shard at random (0 to N-1). Reads query all N shards and merge. You trade one extra fan-out read for even load.

Picture it One viral restaurant on a Friday night.

The setup: Restaurant 3 gets 4,000 orders a minute while the rest get 40 (illustrative).

Relational · PostgreSQL

A relational DB just serves it; row locks are the bottleneck.

hot.sqlruns offline
UPDATE restaurants
   SET orders_today = orders_today + 1
 WHERE id = 3;   -- all writers queue on one
-- row lock; one primary

Cassandra · CQL

Add a shard to the key.

shard.cqlruns offline
CREATE TABLE orders_by_rest_shard (
  restaurant_id int, shard tinyint,
  day date, order_id timeuuid,
  PRIMARY KEY ((restaurant_id, shard, day),
               order_id));
-- shard = hash(order_id) % 8

The shift: A relational hot row waits on a lock; a Cassandra hot key burns three nodes, so you add a shard to the key.

Make the invisible visible: Load before and after sharding.

hot-shard.txtruns offline
# illustrative output
before: partition (3, 2026-11-23)  4000 w/min -> nodes A,B,C busy
after : (3,0..7, day) 8 partitions 500 w/min each
        spread over about 8 different replica sets
read  : 8 small SELECTs, merged in the app

Why: Replica sets are chosen by the partition key's token. A different shard gives a different token and so a different set of nodes.

Land it I shard only keys I can prove are hot, because every shard costs the reader one more query.

Likely follow-ups
"How do I choose the shard count?"

I divide the peak write rate by what one partition comfortably handles, then round up to a power of two.

shard_mathillustrative
# illustrative
peak writes for the hot sensor   20,000 / s
one partition comfortably        about 2,500 / s  (measure on your hardware)
shards needed                    20,000 / 2,500 = 8
with room to grow                use 16

Measure the per-partition figure on your own hardware, because it varies with row size and disks. Keep the number small. Every shard is one more query for the reader, so 16 shards means 16 parallel reads for a full view of that sensor, and the slowest of the 16 decides the latency of the whole read.

Also remember that changing the count later reroutes new writes, while old data stays where it was. Readers must then ask the old and new shard numbers, so choose with some headroom and write the value in the schema notes. I make the shard function one named method that every writer calls.

"Can I shard by something meaningful?"

Yes, and it is usually better. If the attribute is something the reader already filters by, the extra partitions cost nothing, because the query was going to ask for that attribute anyway.

For QuickBite's busiest restaurant, orders for one day could go into (restaurant_id, day, zone). The kitchen dashboard can read its own delivery zone, and a restaurant-wide view reads a few zones in parallel. Compare that with a random shard number, where every read has to ask all shards, and the shard has no meaning for a person.

The limits: a real attribute can be uneven. If one zone holds 70 percent of the orders, that zone is still hot, and I would add a hash on top of it.

So the order is: a meaningful key the query already uses, then a random hash as the fallback.

"How do I detect hot partitions?"

Use nodetool toppartitions, which samples a table for a short time and reports the busiest partition keys.

toppartitionsillustrative
# illustrative
nodetool toppartitions quickbite rider_latest 10000
# samples for 10,000 ms, then lists the top keys for reads and writes

Before that, per-node signals point at the problem. One node with 95 percent CPU while the others idle, uneven per-node read or write counts, or a single node with high latency are the first hints. The driver's own per-node metrics tell the same story from the client side.

Then I confirm with the sampler and check that the same keys appear on the busy nodes, which rules out a node problem such as a slow disk. I run it in a quiet period too, to learn what normal looks like. Dashboards of load per node are the first alarm; the sampler is the proof. A key that tops the list for both reads and writes is the first one I shard.

"Does a bigger cluster help?"

No, not for a single hot key. The key's replicas are fixed, three nodes at RF 3, whether the cluster has 6 nodes or 600. Adding nodes spreads the other keys and gives them more room, but the hot key still lands on the same three.

Raising RF changes only part of the picture. Reads at ONE or LOCAL_ONE can then go to more replicas, but every write still goes to all replicas, so a write hot spot gets worse, not better, because there are more copies to update.

What helps is to change the data model: shard the key (the previous questions), or put a cache in front of reads if the hot key is read-heavy and the value changes rarely.

So I do the capacity math per partition, not per cluster, and I say clearly in the review that sharding is the real fix and extra nodes are not.

Q73 · Scenario. "A developer says 'the query works if I add ALLOW FILTERING'. Is that a fix?"

Reveal answer

Strong answer No. ALLOW FILTERING tells Cassandra: "I know this query cannot use the primary key, go ahead and scan." It reads rows and throws away those that do not match.

On a tiny table or inside one partition, it is fine. Without a partition key it reads every partition on every node, so cost grows with total data, not with the answer size.

The honest fix is to design a table whose key matches the question, or to add a SAI index for a column filter inside a restricted partition.

Picture it Find orders that are 'LATE'.

The setup: The table is orders_by_customer, keyed by customer. The query asks for all late orders across customers.

Relational · PostgreSQL

An index on status is natural.

late.sqlruns offline
CREATE INDEX ON orders (status);
SELECT * FROM orders
 WHERE status = 'LATE';
-- planner picks the index

Cassandra · CQL

The query does not fit the key, so give it its own table.

late.cqlruns offline
-- ❌ TRAP
SELECT * FROM orders_by_customer
 WHERE status = 'LATE' ALLOW FILTERING;
-- ✅ a table for the question
-- PRIMARY KEY ((day, status), order_id)
SELECT * FROM late_orders_by_day
 WHERE day = '2026-11-23' AND status = 'LATE';

The shift: A relational planner finds an access path for any filter; Cassandra requires the path to be the table's key.

What you see: The cost grows with the table, not the answer.

filtering.txtruns offline
# illustrative output
rows in table: 10M    rows matching: 40
ALLOW FILTERING: reads 10M rows, returns 40
  1M rows -> 0.4 s     10M -> 4 s     100M -> timeout
late_orders_by_day: reads about 40 rows, 3 ms

Why: The answer stays 40 rows but the scan grows with the data. It works in the test with 1,000 rows and fails in production.

Land it I treat ALLOW FILTERING in application code as a design bug and ask which question needs its own table.

Likely follow-ups
"When is ALLOW FILTERING acceptable?"

It is acceptable when the cost is bounded and the query is not on the hot path. There are three honest cases.

allow_filtering.cqlillustrative
-- illustrative
-- 1. restricted to one partition: scans only that partition
SELECT * FROM orders_by_restaurant_day
WHERE restaurant_id = ? AND day = '2026-11-25' AND status = 'READY' ALLOW FILTERING;

In that example the partition holds at most a few thousand rows, so the filter reads a few thousand rows and returns the matches. That is fine.

Case two is a small table, such as a list of 50 cities, where a scan costs nothing. Case three is an operator running a one-off query by hand on a quiet cluster. In none of these is the cost growing with the data.

I would reject it in application code whose table grows. The Cassandra documentation gives the same advice, because the cost scales with total data and not with the size of the answer.

"What about SAI?"

SAI is the proper answer for column filters, because it gives you an index instead of a scan. With an index, WHERE status = 'READY' works without ALLOW FILTERING.

sai.cqlillustrative
-- illustrative
CREATE INDEX orders_status_idx ON orders_by_restaurant_day (status) USING 'sai';
-- fast: partition key given, index searches only this partition
SELECT * FROM orders_by_restaurant_day
WHERE restaurant_id = ? AND day = '2026-11-25' AND status = 'READY';

The partition key still matters. Without it, a SAI query is sent to many nodes, because each node indexes only its own data, so cost grows with the cluster. SAI is cheaper than the old index, but it is not free.

So I use SAI to filter within a partition or a modest table, and I still give hot paths their own table (Q74). To check a design, I run the query on a staging table of production size and look at the latency, since Cassandra has no planner to ask.

"How do I explain this to a Postgres developer?"

A PostgreSQL developer already knows the behaviour, just not the refusal. Without an index, PostgreSQL will do a sequential scan and return the answer, slowly, on one machine. Cassandra refuses by default, because its data is spread over many machines and a scan is a scan of all of them.

seq_scan.sqlillustrative
-- illustrative
-- PostgreSQL: no index on status, so it scans the table and answers
SELECT * FROM orders WHERE status = 'READY';
-- Cassandra: rejected unless you add ALLOW FILTERING
SELECT * FROM orders_by_id WHERE status = 'READY';
-- error: ... use ALLOW FILTERING

The error message is a protection. It is the database saying that the cost is unpredictable. A table of 10 GB scans quickly on one PostgreSQL machine, and the same query on 10 TB over fifty nodes does not, even though it reads the same way.

So adding the flag does not fix the query. It just removes the guard, which is why I treat it as a signal to ask which question deserves its own table.

"Why not make everything an index?"

Because an index in Cassandra is local to each node. A query without the partition key cannot know which node holds the match, so the coordinator has to ask many nodes, enough to cover every token range. In a 30-node cluster that is up to tens of requests for one query (illustrative), and the number grows when you add nodes, the opposite of what scaling should do.

Every index also costs on the write path. Each write must update the index as well as the table, and each node carries index files that need compaction, so a table with five indexes does noticeably more work per write.

A table keyed for the question has none of this. The query goes to one partition on a few replicas, and the cost does not depend on the cluster size.

So my rule is one table per important question, and an index only for the secondary filters that I accept paying for.

Q74. "When is a secondary index OK in Cassandra, and what does SAI change?"

Reveal answer

Strong answer A legacy secondary index is stored locally on each node. A query on it without the partition key asks every node, so it is slow and gets slower with a bigger cluster. It suits low-cardinality columns inside a single partition only.

SAI (Storage-Attached Indexing, 5.0) is the modern index. It is faster, smaller, supports ranges and several columns, and the vector type uses it for nearest-neighbour search. SASI is deprecated.

Rule of thumb: a SAI index is fine as a filter on top of a partition key, or for modest-size tables. It does not replace a table designed for the query.

Picture it Search a customer's orders by status.

The setup: The partition is a customer; the filter is status.

Relational · PostgreSQL

A normal B-tree index serves any filter.

idx.sqlruns offline
CREATE INDEX ON orders (status);
SELECT * FROM orders
 WHERE customer_id = 7
   AND status = 'LATE';

Cassandra · CQL

SAI inside one partition.

sai.cqlruns offline
CREATE INDEX orders_status_sai
  ON orders_by_customer (status)
  USING 'sai';
SELECT * FROM orders_by_customer
 WHERE customer_id = 7
   AND status = 'LATE';  -- ✅ one partition

The shift: A relational index is global and the planner uses it; a Cassandra index is local to each node, so give it a partition key to narrow the search.

Make the invisible visible: Cost of the same filter with and without the key.

sai-cost.txtruns offline
# illustrative output
WHERE customer_id = 7 AND status='LATE'  (SAI)
  -> 1 partition, 3 replicas asked        3 ms
WHERE status = 'LATE'                    (SAI, no key)
  -> all nodes asked, results merged     grows with cluster

Why: The partition key tells the coordinator which replicas to ask. Without it, every node is asked, because each index only knows its own data.

Land it I use SAI to filter within a partition or on smaller tables, and I still give hot paths their own table.

Likely follow-ups
"What can SAI do that the old index cannot?"

SAI supports more kinds of query, and it does so with less storage.

CapabilityLegacy secondary indexSAI (5.0)
Equality on one columnYesYes
Range on numbers and datesNoYes
Combine several indexed columns with ANDLimitedYes
Text matching optionsBasicMore options; check the docs
Vector nearest-neighbour searchNoYes, with the vector type
vector.cqlillustrative
-- illustrative
CREATE INDEX menu_ann ON menu_vectors (embedding) USING 'sai';
SELECT name FROM menu_vectors
ORDER BY embedding ANN OF [0.1, 0.8, 0.3] LIMIT 5;

The query returns the five menu items whose embedding is closest to the given vector, which is how you would build a "dishes like this one" feature, and it uses the index instead of comparing every row. In PostgreSQL the same job needs an extension such as pgvector. SAI also needs the same partition-key discipline as any other index when you combine it with filters.

"Does SAI make denormalisation unnecessary?"

No. SAI makes more queries possible, but a table keyed for the query is still the fastest and the most predictable.

Take two QuickBite questions. First, "orders for one restaurant on one day, newest first". It is asked all day, so it has its own table, orders_by_restaurant_day, and the answer is one sequential read of one partition. Second, "which of those orders are CANCELLED". It is asked rarely and changes with the report, so a SAI index on status, used inside that partition, is a good fit.

A relational design would do both with one table and two indexes, and the planner would pick. Cassandra has no planner of that kind, so I choose the access path at design time.

The split I use is roughly: the frequent, latency-critical questions get tables, and the varied, occasional ones get SAI. If a SAI query becomes a hot path, I promote it to a table.

"What about cardinality?"

Cardinality is the number of distinct values in a column, and it decides how useful an index is.

ColumnDistinct valuesWhat I do
Phone numberOne per customerA key: customers_by_phone
Order statusAbout 5SAI with a partition key
Restaurant cuisineAbout 50SAI, a good fit
Boolean flag2SAI only inside a partition

Very high cardinality means each value matches one row, so a lookup is better served by a table keyed on it. Very low cardinality without a partition key matches half the table, which is a scan. The middle is where SAI helps.

I test with my own data sizes, because the right answer depends on how many rows each value matches. A quick estimate is rows in the partition divided by distinct values: 5,000 orders and 5 statuses is about 1,000 rows per status, a small result, so SAI inside that partition is cheap.

"How is it kept in sync?"

SAI is built into the same storage as the table, which is why it costs less to write than the old index.

  1. Memtable: each memtable keeps a small in-memory index for the rows it holds, updated as writes arrive.
  2. Flush: when the memtable is flushed to an SSTable, the index files are written next to it, as part of the same flush.
  3. Compaction: when SSTables are merged, the index files are merged and rebuilt with them, so index and data stay together.
  4. Read: a query checks the index of each memtable and SSTable that could match, and merges the results.

The legacy index was effectively a hidden second table with its own writes. Because SAI has no separate write path, the extra cost per write is smaller. The index is still local to each node, so a query without the partition key must reach many nodes.

Q75. "Why does everyone say 'don't use materialized views'?"

Reveal answer

Strong answer A materialized view (MV) is a table Cassandra keeps in sync for you, with a different primary key. It sounds like the denormalisation helper you wanted.

In practice it has had consistency and repair problems, can silently diverge from the base table, and each base write costs extra. In 5.0 MVs are still marked experimental and disabled by default, and are not recommended for production.

The safe replacement is a second table that your application writes in a logged batch, or a stream that updates it.

Picture it Orders by customer and by restaurant.

The setup: The base table is keyed by customer. A view would re-key it by restaurant.

Relational · PostgreSQL

A relational view is a stored query; materialized views refresh on demand.

mv.sqlruns offline
CREATE MATERIALIZED VIEW rest_orders AS
 SELECT rest_id, id, total FROM orders;
REFRESH MATERIALIZED VIEW rest_orders;
-- you choose when it refreshes

Cassandra · CQL

The hand-built table is written with the base write.

handbuilt.cqlruns offline
BEGIN BATCH
 INSERT INTO orders_by_cust (...) VALUES (...);
 INSERT INTO orders_by_restaurant_day (...)
   VALUES (...);
APPLY BATCH;
-- ✅ you control the write and the repair

The shift: A relational view is computed from one source; in Cassandra you own the copies, because the engine's helper is not production-safe.

Make the invisible visible: How an MV can drift from its base.

mv-drift.txtruns offline
# illustrative output
base write reaches replica A, view write is lost
 base:  order 42 = ACCEPTED
 view:  order 42 = (missing)
repair of the view cannot know the base value
-- check the current docs; MV support is experimental

Why: The view update is a second write with its own failure modes. If it is lost, nothing reruns it. Your own batch or event stream is at least visible and replayable.

Land it I build denormalised tables myself with logged batches, because that is a supported, testable path.

Likely follow-ups
"What about SAI instead of an MV?"

They solve different problems. SAI filters rows inside the same table. A materialized view builds a different table, with a different primary key, so you get a different sort order and lookup path. SAI cannot give you that.

mv_vs_tableillustrative
-- illustrative
-- an MV would be declared like this (experimental; avoid)
CREATE MATERIALIZED VIEW menu_by_cuisine AS
  SELECT * FROM menu_items WHERE cuisine IS NOT NULL AND item_id IS NOT NULL
  PRIMARY KEY ((cuisine), item_id);
-- the supported way: a normal table that your code also writes

For the lookup "all dishes of one cuisine, sorted by name" I build and write the second table myself, in a logged batch. For "which dishes in this restaurant are vegetarian" I use SAI on the existing table with the partition key given. SAI cannot change the order of the results or give you another way to find the data.

A PostgreSQL materialized view is another thing again: a stored query result refreshed on command, with no automatic per-write maintenance. The word is the same, the behaviour is not.

"Could a Kafka stream feed the copy?"

Yes, and it is a good fit when you need several copies or may need a new one later. It is the outbox pattern.

  1. Write once: the service saves the order and an outbox row in one transaction in its source database.
  2. Publish: a relay reads the outbox and publishes each change to a Kafka topic (see the Kafka chapter).
  3. Fan out: one consumer per table writes its Cassandra copy. Each write is an upsert on the same key, so a replay or a retry is harmless.
  4. Add later: a new table gets a new consumer group that reads the topic from the start, which backfills it from history.

The price is eventual consistency, usually a short lag, and the topic must keep enough history. In return there is no batch of several tables on the request path, and each copy can be rebuilt.

"Do other systems have the same helper?"

Yes, in different forms, and each has its own rules, so I would not copy conclusions between them.

ScyllaDB, which speaks CQL, offers materialized views and global secondary indexes with its own implementation, so a statement about Cassandra's views does not automatically hold there. DynamoDB has global secondary indexes, which the service maintains for you, with extra write cost and eventual consistency between the table and the index. PostgreSQL's materialized views are refreshed snapshots, as above.

The point is that each platform pays for the helper differently, in latency, in consistency, or in money.

In a design review I ask which platform is meant, and I read that platform's current documentation before relying on the feature. For Cassandra itself, the answer remains to build the copies in the application.

"Is there a plan to fix them?"

The views have been marked experimental for several releases, and I know of no committed plan that changes that for production use. Check the current project documentation, because plans move.

The 6.0 alpha introduces Accord transactions across partitions, which could one day make keeping several copies in step simpler. It is a preview, off by default, and I would not design a production system around it today.

So I design for the supported path now, and I keep the change cheap later: all writes to the copies go through one function in the code. If a better mechanism arrives and passes my tests, I change that one function.

In a review I say it plainly: leave views out of the design, and name the logged batch or the Kafka consumer as the mechanism.

Drill · Clients, paging and overload

How the application talks to the cluster matters as much as the schema. These five questions cover paging, prepared statements, backpressure, caching and what an overloaded node looks like.

Q76. "How do you paginate in Cassandra? Why is there no OFFSET?"

Reveal answer

Strong answer There is no OFFSET, because skipping N rows would still mean reading and discarding them on the replicas. Instead the driver gives you a paging state: an opaque token that marks where the last page ended.

You ask for a page of, say, 20 rows (the fetch size). The reply carries a paging state. To get the next page you send the same query with that state, and the server resumes where it stopped.

For an API, hand the paging state to the client as a cursor string. Do not let users jump to page 500.

Picture it Page through a customer's order history.

The setup: The customer has 400 orders; the screen shows 20 at a time.

Relational · PostgreSQL

OFFSET skips rows by reading them.

offset.sqlruns offline
SELECT * FROM orders
 WHERE customer_id = 7
 ORDER BY created DESC
 LIMIT 20 OFFSET 380;
-- reads and drops 380 rows first
-- page 20 costs more than page 1

Cassandra · CQL

A cursor resumes at a position.

paging.cqlruns offline
SELECT * FROM orders_by_customer
 WHERE customer_id = 7
 LIMIT 20;
-- driver returns rows + paging_state
-- next page: same query + paging_state
-- cost per page stays about the same

The shift: OFFSET counts from the start every time; paging state remembers where you were.

Make the invisible visible: Three pages and the cursor.

paging.txtruns offline
# illustrative output
page 1: rows 1-20    paging_state=0xA1...
page 2: rows 21-40   send 0xA1... -> new state 0xB2...
page 3: rows 41-60   send 0xB2... -> new state 0xC3...
each page cost about 4 ms, no matter the depth

Why: The state holds the last clustering position, so the server starts there instead of counting. Pages are consistent only as far as the data does not change between calls.

Land it I use paging state as an opaque cursor and refuse deep jump-to-page requests in the API.

Likely follow-ups
"Can the paging state be reused later?"

Treat it as short-lived: keep it for the length of one browsing session, not for days. The paging state is an opaque blob that records the query, the position of the last row, and a few details the coordinator needs to resume. If a deploy changes the schema, adds a column, or upgrades the driver, an old token can be rejected or point to the wrong spot.

Two more points matter for an API. First, the token is not signed, so a user who edits it may jump to rows they should not see, or crash the query. Sign it with an HMAC, or encrypt it, before it leaves your server.

Second, the token only works with the exact same query and bound values. Change the WHERE clause and the old token is useless.

My rule: a cursor lives minutes, is signed, and is bound to one query. If it fails, restart from page one rather than guess.

"What about the total count for 'page 3 of 40'?"

I would not offer an exact total at all. Counting rows in Cassandra means reading every row of the partition, or worse, every node for a table-wide count. That is the opposite of the cheap single-partition read the model is built for.

In PostgreSQL the habit is easy, so people copy it:

count, SQL vs CQLruns offline
-- illustrative
SELECT count(*) FROM orders WHERE customer_id = 7;   -- PostgreSQL: index scan, fine for small sets
SELECT count(*) FROM orders_by_customer
 WHERE customer_id = 7;                              -- CQL: reads the whole partition; avoid

PostgreSQL can answer from an index and its statistics. Cassandra has no such shortcut.

So change the screen: show Next and Previous, or "20+ orders". If a rough number is truly needed, keep a counter table and accept small drift (Q60), or store the count when you write.

If a product team asks for a total anyway, I push back with the cost: it is a scan for a number almost nobody reads closely.

"Does LIMIT replace paging?"

No, they do different jobs, and you often use both. LIMIT says "stop after N rows in total". Paging says "send me the answer in slices". With LIMIT 20 you get at most 20 rows and the query is over. With a fetch size of 20 and no LIMIT, you may get 20 rows, then ask for the next 20, until the partition is exhausted.

The trap is the screen that needs "all rows, but show them gradually". LIMIT cannot continue from where it stopped, because there is no OFFSET. Paging state can.

In PostgreSQL you would write LIMIT 20 OFFSET 40 and the server would walk past 40 rows each time. Cassandra instead resumes from a saved position, so page 50 costs about the same as page 1.

My choice: LIMIT for "latest 20" widgets, paging for lists and exports, and both together when the list has a hard maximum.

"What is a good fetch size?"

The fetch size is the number of rows the server returns per page; the Java driver 4.x default is 5,000 (check your driver's docs). That is sensible for a batch job but too big for a screen showing 20 orders, because the server and network work to deliver rows nobody sees.

  1. User screens: set the fetch size to what the UI shows, 20 to 100. Latency stays low and memory small.
  2. Batch and export jobs: use 1,000 to 5,000, so fewer round trips are needed.
  3. Row size: if rows carry big blobs, lower it, since one page of 5,000 large rows can be many megabytes.

Always set it explicitly per query type, so nobody relies on a default that changes. And measure the page latency at p99, not only the average, before you settle on a number.

Q77. "Why do people insist on prepared statements and a token-aware driver?"

Reveal answer

Strong answer A prepared statement is a query the server parses once and stores. You then send only the id and the values. It saves parsing and bandwidth and protects against injection.

A token-aware driver knows the token ring. With a prepared statement it computes the partition's token from your bound values and sends the request straight to a replica, saving one hop through a random coordinator.

Together they cut latency a lot at high load. An unprepared, string-built query gives neither.

Picture it A hot read at 20,000 requests per second.

The setup: Each saves 0.3 ms of parsing and one network hop (illustrative).

Relational · PostgreSQL

Postgres also has prepared statements and a connection pool.

pg-prep.sqlruns offline
PREPARE get_order (bigint) AS
  SELECT * FROM orders WHERE id = $1;
EXECUTE get_order(42);
-- a pooler (PgBouncer) in front

Cassandra · CQL

Prepare once; bind per call.

prep.javaruns offline
PreparedStatement ps = session.prepare(
 "SELECT * FROM orders_by_id WHERE id = ?");
BoundStatement b = ps.bind(orderId);
Row row = session.execute(b).one();
// ✅ token-aware: sends to a replica

The shift: Both worlds prepare; in Cassandra the prepared bound key also steers the request to the right node.

Make the invisible visible: Network hops per read.

hops.txtruns offline
# illustrative output
unprepared, no token awareness:
 client -> random node -> replica -> back   (2 hops)
prepared + token-aware:
 client -> replica (also coordinator) -> back (1 hop)
 20,000 req/s x 0.3 ms saved per request

Why: The driver can only compute the token if it knows which bound values form the partition key. That information comes from the prepared statement's metadata.

Land it I prepare every repeated query once at start-up and keep the driver's token-aware policy on.

Likely follow-ups
"What is a common prepared-statement bug?"

The classic one is calling prepare() inside a loop or on every request, because the code looks harmless. Each call sends the query text to the server, which parses it and returns an id. Done thousands of times, that wastes round trips and floods the server's prepared-statement cache, which logs a warning when it overflows.

A second version of the bug is building the query string with the value inside it, such as "... WHERE id = " + id. Every different id becomes a different statement, so the cache fills with one-off entries, and you also open the door to injection.

  1. Prepare once: at start-up, store the prepared object in a field.
  2. Bind many times: call bind(...) with new values for each request.

The driver can re-prepare silently if a node forgets an id, so the cost is hidden. I check the driver metrics and logs for a high prepare count.

"What about null values in a bound statement?"

Binding null to a column writes a delete marker, called a tombstone, for that cell. It does not mean "leave it alone". That is the surprise: a harmless-looking insert with several optional fields quietly creates tombstones, and many of them slow reads.

The fix is to leave the column unset. Since protocol v4 (Cassandra 2.2 and later) a bound statement can keep a value unset, which means the column is not written at all.

null vs unsetruns offline
// illustrative
BoundStatement b = ps.bind(id, name, email);          // email == null  -> tombstone
BoundStatement b2 = ps.bind().setString("id", id)
                             .setString("name", name); // email left unset -> no write

PostgreSQL has no such trap: a NULL is just a value. My habit is to build the statement only with the columns that actually changed.

I also review code for the habit of binding every optional field, because that is where hidden tombstones come from in practice.

"Does the Java driver 4.x do this by default?"

Yes, with one condition. The Apache Cassandra Java driver 4.x uses a default load-balancing policy that is token-aware and datacentre-aware. Token-aware means it computes which replicas own the partition and sends the request to one of them. Datacentre-aware means it prefers nodes in your own datacentre.

The condition is that you must name the local datacentre. In driver 4.x, basic.load-balancing-policy.local-datacenter in the config file (or the builder method) is required, and the driver refuses to start without it. Check the driver's docs for the current setting names.

Token awareness only works when the driver can compute the token. That needs a prepared statement, or a statement whose routing key you set by hand. A string-built query goes to a random coordinator.

I set the datacentre name explicitly and test that the metrics show requests landing on replicas.

"Why does a pool matter?"

The pool matters because opening a connection is slow, and the native protocol lets one connection carry many requests at once. Each connection can have up to a few thousand requests in flight, tagged by a stream id, so they do not wait for each other.

That is why one or two connections per node are enough for most services. A modest service might send a few thousand requests per second and never fill them.

In relational land the pool works the other way. A PostgreSQL connection runs one query at a time, so you need a pool of, say, 10 to 50 connections, and each one costs a server process. Cassandra connections are cheap, but they are multiplexed.

More connections add file handles and memory on each node, not speed. If you see queue waits, first cap the in-flight requests (Q78) before you raise the pool size.

Q78 · Scenario. "Your service fires 50,000 async writes at once during a job, and the app falls over with timeouts. What is missing?"

Reveal answer

Strong answer Backpressure. The driver and cluster have limits on how many requests can be in flight. If you submit 50,000 at once, the queue fills, latencies climb, and clients time out and retry, making it worse.

Limit the number of in-flight requests with a semaphore or a reactive flow control, for example 256 per connection pool. Measure and tune.

Make each write idempotent (an upsert by key) so retries are safe, and use a retry policy that backs off.

Picture it A thundering herd of writes.

The setup: A nightly job loads 2 million rows by launching them all as futures.

Relational · PostgreSQL

A Postgres client uses a pool of 20 connections, so the pool is the backpressure.

pool.sqlruns offline
-- HikariCP maximumPoolSize = 20
-- the 21st caller waits for a free connection
-- natural limit: 20 in flight

Cassandra · CQL

The driver allows thousands in flight; you set the limit.

limit.javaruns offline
Semaphore gate = new Semaphore(256);
for (Row r : rows) {
  gate.acquire();     // wait if 256 busy
  session.executeAsync(bind(r))
    .whenComplete((rs, e) -> gate.release());
}

The shift: A relational pool limits you for free; Cassandra's async driver lets you flood it, so you add the limit.

Make the invisible visible: Latency with and without a limit.

backpressure.txtruns offline
# illustrative output
no limit:   50,000 in flight -> p99 9 s, 8% timeouts, retries
limit 256:  256 in flight    -> p99 40 ms, 0 timeouts
total time: 38 s vs 41 s (about the same, far safer)

Why: More in flight than the cluster can serve only builds a queue. The same total work finishes in about the same time with the limit, without the failures.

Land it I put a hard cap on in-flight requests and make every write idempotent, so a retry cannot hurt.

Likely follow-ups
"What is a safe retry policy?"

Retry only when the request is idempotent, only a few times, and with a short back-off that grows. Idempotent means running it twice gives the same final result. An upsert by full primary key qualifies. A counter increment does not, so a retry could count twice (Q60).

  1. Which errors: read timeout, write timeout and unavailable. For a write timeout the write may have succeeded, so retry only if it is safe to repeat.
  2. How many times: two or three attempts, not unlimited.
  3. How long to wait: start near 10 to 50 ms and double each time, with a little random jitter so clients do not retry together.

The Java driver 4.x lets you mark statements idempotent, and its default retry policy honours that flag. A retry storm turns a slow cluster into a dead one, so I also cap the total time with a deadline.

"What is a speculative execution?"

Speculative execution means the driver starts a second attempt on another replica when the first is slow, and uses whichever answers first. It targets tail latency: the rare slow request caused by a GC pause or a busy node.

Take a table where p50 is 3 ms but p99 is 120 ms. If the driver waits 20 ms and then asks a second replica, most slow requests finish near 25 ms instead of 120 ms. The price is extra load: any request slower than the 20 ms threshold now costs two reads, say 2 to 5 percent more reads (illustrative).

It needs idempotent requests, since two copies may both run. That makes it natural for reads and risky for non-idempotent writes.

I would turn it on for read paths only after measuring, set the delay near the p99 of normal latency, and watch the extra load. Left on blindly during an overload, it adds to the problem.

"How do I see a client overload?"

I would watch both sides, because they show the same story from different ends. The aim is to see overload before users do.

  1. Client: driver metrics for in-flight requests, request timeouts, retries, speculative executions and connection pool saturation. A growing queue of waiting requests is the early warning.
  2. Server: nodetool tpstats shows pending and blocked thread pools, including native-transport requests, and a count of dropped messages such as MUTATION.
  3. Latency shape: p99 climbing while p50 stays flat points to a few overloaded nodes, not the whole cluster.

I set alerts on the trend, for example timeouts above 0.1 percent of requests (illustrative), not on a single failure. And I load-test the job beforehand to find the in-flight cap where latency starts to bend.

"Is reactive programming required?"

No. A plain semaphore is enough: before each write, acquire a permit; release it when the future completes. If you allow 256 permits, no more than 256 writes are ever in flight, and extra tasks wait in your own code, not inside the driver queue.

semaphore capruns offline
// illustrative
Semaphore permits = new Semaphore(256);
permits.acquire();
session.executeAsync(stmt).whenComplete((rs, err) -> permits.release());

Reactive streams, such as Reactor with Spring Data Cassandra's reactive support, give you the same thing built in: the consumer asks for N items and the source sends no more.

So the choice is about your team, not the database. If you already run a reactive stack, use it. If you run plain threads, the semaphore is simpler to read, test and debug.

Whichever you pick, the cap itself is what matters, and you should tune it from a load test, not guess it.

Q79 · Design. "The team wants to put Redis in front of Cassandra 'for speed'. Do we need it?"

Reveal answer

Strong answer Often not. A well-modelled Cassandra read is one partition read, a few milliseconds, with the operating system caching hot files in memory. Cassandra already has a key cache and a chunk cache.

A cache helps for extremely hot, rarely changing data, or when you need sub-millisecond answers. It also adds cost, stale data, and a second system to run.

Fix the model first: a slow Cassandra read usually has a modelling cause (wide partition, tombstones), and a cache hides it until the key is cold.

Picture it Is the cache hiding a problem?

The setup: A product page reads one menu partition at 8 ms. The team suggests Redis.

Relational · PostgreSQL

Postgres teams add a cache to protect one primary from reads.

cache.sqlruns offline
-- the primary is the bottleneck
-- add Redis in front: read-through cache
-- invalidate on every write
-- one copy, one writer to protect

Cassandra · CQL

Reads already spread over many replicas.

scale.cqlruns offline
-- RF 3: any replica can serve a read
-- add nodes: more read capacity
-- add RF: more copies to read from
-- one partition read about 3 ms

The shift: A relational cache protects a single bottleneck; Cassandra spreads reads across replicas, so first check the model.

Make the invisible visible: Compare the options.

cache-options.txtruns offline
# illustrative output
option            latency   catch
Cassandra alone   2-8 ms    fine for most paths
+ row cache       < 1 ms    memory heavy, off by default
+ Redis           < 1 ms    stale data, extra system
+ CDN / app cache  0 ms     only for public, static data

Why: A cache is a trade of freshness and complexity for latency. Make that trade for the few data sets that need it, not by default.

Land it I measure first, fix the model, and cache only the few hot read-mostly objects.

Likely follow-ups
"What would justify Redis?"

Redis earns its place when the job is something Cassandra cannot do well, not when it is only "faster reads". Three examples:

  1. Leaderboards: Redis sorted sets give the exact rank of any player quickly (Q88). Cassandra is awkward at ranks.
  2. Rate limiters: an atomic increment with a short expiry, with sub-millisecond latency (Q90).
  3. A tiny, very hot set: a few thousand keys read at huge rates, where even a few milliseconds is too slow.

Notice that these are different jobs. In each case Redis is its own store with its own rules, not a copy of Cassandra that you must keep fresh.

The test I use: if I can describe what Redis does without the words "in front of Cassandra", it may be justified. If the only reason is "reads are slow", I go back and measure first. A slow Cassandra read nearly always has a modelling cause that a cache would only hide.

"Is the Cassandra row cache useful?"

Rarely. The row cache keeps whole rows in memory inside the JVM heap, and any write to the partition throws away the cached rows for it. So it helps only when a partition is read very often and almost never written, such as a small reference table.

It also has a cost. It lives in the heap, or an off-heap area you must size, so it competes with memtables and adds garbage collection pressure. It is off by default for good reason.

The other two caches give most of the gain. The key cache remembers where in each SSTable a partition starts, saving a disk seek. The operating system's page cache holds recently read file blocks in the RAM you left free. That is why I keep the Java heap at a moderate size and let the machine's memory do the rest.

I would enable the row cache only per table, after a test shows a hit rate that pays for it.

"How do I cache safely if I must?"

The honest answer is: a cache is never the source of truth, so design it so that a wrong answer is harmless and short-lived.

  1. Short expiry: a TTL of a few seconds, so any stale entry heals itself quickly.
  2. Versioned keys: put a version or last-updated time in the cache key, so a new version is a new entry, and old ones just age out.
  3. Delete after write: the writer removes the cache entry only after the Cassandra write succeeds. Deleting before it lets a reader refill the cache with the old value.

There is still a small window where a reader sees old data, so use this only for data where that is acceptable, such as a restaurant menu or a profile page. Never use it for stock levels or payment status. If the cache is down, the system must keep working, only slower.

"What does the relational world do here?"

In the relational world one primary server takes all writes, so teams relieve it in steps. First they add read replicas, copies that serve reads. Then they add a cache such as Redis in front. Both aim at one problem: a single writer and a single hot machine that cannot grow.

where reads goruns offline
illustrative
PostgreSQL: app -> cache -> read replica(s) -> primary (all writes)
Cassandra:  app -> any node (token-aware) -> replicas that own the key

Cassandra has no primary. Each node owns slices of the key space, so adding nodes adds both read and write capacity, and a well-keyed read touches one partition.

That does not make a cache always wrong, but it removes the main reason the relational world needs one. In an interview I say it plainly: the cache solves a PostgreSQL problem that Cassandra's design avoids at the source.

Q80 · Scenario. "Writes time out during a big import, nodes show 'dropped mutations' and GC pauses. Where do you look?"

Reveal answer

Strong answer Write timeouts under load mean a node cannot keep up. Look for four things: JVM garbage collection pauses, flush and compaction falling behind, a slow commit-log disk, and a hot or wide partition.

Dropped mutations are writes the node discarded because they waited too long in its queue. They are repaired later, but they show overload.

Slow the client down (backpressure, Q78), check nodetool tpstats for blocked pools, check GC logs for pauses over 500 ms, and give the commit log its own fast disk.

Picture it The node log tells the story.

The setup: A 3-node dev cluster takes a 10-million-row import.

Relational · PostgreSQL

A Postgres bulk load strains WAL and checkpoints.

wal.sqlruns offline
-- bulk COPY: WAL grows, checkpoint spikes
-- tune max_wal_size, checkpoint_timeout
-- lock waits and vacuum lag are the signs

Cassandra · CQL

Look at the thread pools and GC.

tpstats.txtruns offline
$ nodetool tpstats
$ nodetool compactionstats
$ grep 'GC' system.log | tail
-- MutationStage pending?  dropped?
-- FlushWriter blocked?  GC > 500 ms?

The shift: Relational overload shows up as lock waits and WAL pressure; Cassandra overload shows up as queued stages and dropped mutations.

What you see: Overload signs in the tools.

tpstats-out.txtruns offline
# illustrative output
Pool Name        Active Pending Completed Blocked
MutationStage    32     8112    5201934   0
Message type     Dropped
MUTATION         214
INFO  G1 Young Pause 640 ms   heap 7.8G/8G

Why: Eight thousand pending mutations and a 640 ms GC pause: the node pauses, the queue grows, and writes expire in the queue. Reduce the incoming rate and look at heap sizing.

Land it I check tpstats, compaction and GC, then slow the producer, rather than raising timeouts.

Likely follow-ups
"Should I raise the write timeout?"

No. A longer timeout does not give the node more capacity. It only makes each request wait longer, so more requests pile up in the queues, memory grows, and the node falls further behind. Clients also hold their own threads longer, so the problem spreads to your application.

The timeout is a signal, and the useful response is to read it. Look at nodetool tpstats for blocked pools, GC logs for long pauses, and nodetool compactionstats for a growing backlog.

  1. Slow the producer: cap the in-flight writes (Q78), so the import matches what the cluster can absorb.
  2. Add capacity: if normal load is already high, add nodes.

The write timeout default in cassandra.yaml is about 2 seconds (check your version). Raising it to 20 seconds would let a failing node look healthy for ten times longer. I only touch it with evidence.

"What heap size is typical?"

A common starting point is 8 to 16 GB of Java heap on a node with much more RAM. The rest is left for the operating system's page cache, which serves most reads from memory.

Why not give it all to the heap? The garbage collector has to scan the heap, and bigger heaps mean longer pauses. A pause stops the node from answering, so peers mark it down and writes time out. With G1, or the newer collectors on Java 17, a moderate heap keeps pauses short. Check the current docs for the recommended settings for your version.

What raises heap pressure is not the data volume itself but the shape of the data: very large partitions, many tombstones in a read, large batches, and big result sets all create short-lived garbage.

So the first fix for GC trouble is usually the model or the query, not a bigger heap.

"What is a dropped mutation's effect?"

A dropped mutation is a write that sat in a node's queue too long and was thrown away before it was applied. The client is usually not told. If the other replicas acknowledged it, the write succeeded at its consistency level, so the application sees success.

The effect is that this one replica now misses the data. Three things can heal it:

  1. Hinted handoff: a coordinator may have stored a hint and replays it later, if hints are enabled and the window has not passed.
  2. Read repair: a read that sees different copies fixes them.
  3. Repair: the scheduled repair compares and fixes everything.

One drop is noise. Frequent drops mean the node is overloaded and replicas are drifting, which is repair debt. I check the dropped-message counts in nodetool tpstats and treat a steady rise as an alarm.

"When do I add nodes?"

I add nodes when the cluster is tight at normal load, not only during a one-hour peak. The signals are pending compactions that keep growing, disk usage above roughly 50 to 60 percent on size-tiered tables (compaction needs free space), and CPU that stays high on every node.

The reason it helps: a new node takes over some token ranges, so each node owns and serves less data and traffic. Adding one node to six reduces each node's share from one sixth to one seventh, about 14 percent less (illustrative arithmetic).

It will not fix a hot partition. One partition lives on its replicas only, so ten extra nodes do nothing for a single key that gets all the traffic. That needs a model fix (Q72).

Add nodes one at a time, let the data stream and settle, and run cleanup on the old nodes afterwards.

Drill · Real-time design: chat, orders and sensors

Design questions. For each one, name the queries first, then the tables, then a partition-size number, as you would in an interview.

Q81 · Design. "Here is our PostgreSQL schema for a chat app (users, conversations, messages). Model it in Cassandra."

Reveal answer

The real test Whether you start from the two screens or from the three relational tables.

Strong answer Start from the screens, not the tables. Two reads dominate: Q1 open a conversation and show the newest 50 messages, Q2 show a user's conversation list, newest activity first, with a last-message preview.

So two tables. messages_by_conversation is partitioned by (conversation_id, bucket) and ordered newest-first by a timeuuid. conversations_by_user is partitioned by user_id and ordered by last activity.

Sending one message writes the message row and, for each member, one row in conversations_by_user, in a logged batch.

Picture it Count the partition.

The setup: A busy group chat: 2,000 messages a day at 300 bytes. A weekly bucket holds 14,000 rows, about 4 MB.

Relational · PostgreSQL

Normalised: messages joined to users and conversations.

chat.sqlruns offline
SELECT m.body, u.name
  FROM messages m JOIN users u
    ON u.id = m.sender
 WHERE m.conversation_id = 9
 ORDER BY m.sent_at DESC LIMIT 50;
-- index (conversation_id, sent_at)

Cassandra · CQL

One table per question, no join.

chat.cqlruns offline
CREATE TABLE messages_by_conversation (
  conversation_id uuid, bucket text,
  msg_id timeuuid, sender_id uuid,
  sender_name text, body text,
  PRIMARY KEY (
    (conversation_id, bucket), msg_id)
) WITH CLUSTERING ORDER BY (msg_id DESC);

The shift: The join is gone: the sender's name is copied into every message row, so the read is one partition.

Make the invisible visible: Q1 as one partition read.

chat-read.txtruns offline
# illustrative output
SELECT * FROM messages_by_conversation
 WHERE conversation_id = 9 AND bucket = '2026-W47'
 LIMIT 50;
-- 1 partition, rows already newest-first, 4 ms
-- if fewer than 50 rows, read bucket '2026-W46'

Why: The newest message is physically first in the partition, so LIMIT 50 reads exactly 50 rows with no sort and no join.

Land it I model chat as one table for the message list and one for the conversation list, and I copy the sender name into the message.

Likely follow-ups
"What happens when a user renames themselves?"

Old messages keep the old name, and for chat that is usually right. It is like a printed receipt: it shows what was true at the time. The name was copied into each message row when it was sent, so a rename changes nothing already written.

In PostgreSQL the same question has a different answer. Messages would store only sender_id, and a join to users would always show the current name:

name lookupruns offline
-- illustrative
-- PostgreSQL: always the live name
SELECT m.body, u.display_name FROM messages m JOIN users u ON u.id = m.sender_id;
-- CQL: no join; the name is stored in the row
SELECT body, sender_name FROM messages_by_conversation WHERE conversation_id = ? AND bucket = ?;

If the product wants the live name, store only the sender id and look names up in a cached users table in the app. Rewriting millions of old rows for a rename would be the wrong move. I choose per product and state the trade-off.

"How do I write the conversation list?"

The list is one row per member per conversation, so each new message upserts a row for every member. Every row carries the preview text, so the home screen needs no second query.

The trouble is ordering. If the clustering key includes last_activity, a new message must move the row, and a clustering column cannot be updated. So you delete the old row and insert a new one with the new time, and each delete leaves a tombstone.

  1. Option one: delete plus insert, in a logged batch for that user, accepting the tombstones. Fine at modest rates.
  2. Option two: partition by user_id, cluster by conversation_id, and store last_activity as a plain column. Read up to about 200 rows and sort in the app.

I prefer option two when users have a bounded number of conversations. It writes one overwrite per member and creates no tombstones.

"Which bucket size?"

Pick the bucket from arithmetic, not taste. The bucket is a time label in the partition key, such as the ISO week or month, derived from the message time so the app can always compute it.

bucket sizingruns offline
illustrative assumptions: 300 messages/day, 200 bytes each
per day  : 300 x 200 B = 60 KB
per month: 60 KB x 30  = 1.8 MB   -> well under 100 MB
busy group, 20,000 msgs/day: 4 MB/day -> 28 MB/week, 120 MB/month (too big)

So a busy group needs weekly buckets or smaller, while a typical chat can use monthly ones. The guideline is under about 100 MB and 100,000 rows per partition, and aiming much lower is safer.

A bucket too small costs extra queries when scrolling back. I take the smallest number of buckets that keeps the busiest group under the guideline, and I revisit it with real traffic.

Revisit the choice after a month of real traffic, since a few very chatty groups usually set the limit for everyone.

"How do I load older messages?"

Page backwards through buckets. You read the newest bucket first. When its rows run out, the app computes the previous bucket's name and reads that one next. Because the bucket comes from the date, no lookup table is needed.

  1. Inside one bucket: use paging state with a fetch size of about 50. The clustering order is newest-first, so each page continues further into the past.
  2. Across buckets: when a page comes back short or empty, switch to the previous bucket and start a fresh query.
  3. Stop rule: stop at the conversation's creation date, so you never query endless empty buckets.

The cursor you hand to the client combines the bucket and the paging state. In PostgreSQL you would write WHERE id < ? ORDER BY id DESC LIMIT 50, which looks similar, but the database walks one big index, not buckets.

Q82 · Design. "Add unread-message badges to the chat. How do you count unread per conversation per user?"

Reveal answer

Strong answer A counter per (user, conversation) is the obvious idea, but counters can drift (Q60) and need careful resets. A common alternative stores a last-read pointer per user and conversation and computes unread from message ids.

For the badge number, either keep a counter in a counter table and accept approximate numbers, or store the last-read timeuuid and count messages newer than it, capped at a limit ("99+").

I would choose the pointer plus a capped count. It is exact enough, retry-safe, and costs one small read.

Picture it The badge shows 99+ at most.

The setup: User 7 last read message T100 in conversation 9. Messages T101 to T130 arrived.

Relational · PostgreSQL

A COUNT with a join on a read-state table.

unread.sqlruns offline
SELECT count(*) FROM messages m
  JOIN read_state r
    ON r.conversation_id = m.conversation_id
 WHERE r.user_id = 7
   AND m.sent_at > r.last_read_at;

Cassandra · CQL

A pointer row; count a bounded slice.

unread.cqlruns offline
-- pointer
UPDATE read_state_by_user SET last_read = T100
 WHERE user_id = 7 AND conversation_id = 9;
-- capped count
SELECT msg_id FROM messages_by_conversation
 WHERE conversation_id = 9 AND bucket = 'W47'
   AND msg_id > T100 LIMIT 100;

The shift: A relational COUNT scans and joins; Cassandra stores the pointer and reads a limited slice of one partition.

Make the invisible visible: Badge computation.

unread.txtruns offline
# illustrative output
last_read = T100
rows with msg_id > T100, LIMIT 100 -> 30 rows
badge = 30
if 100 rows returned -> show "99+" (stop counting)

Why: The slice is clustering order, so msg_id greater than the pointer is a contiguous range at the front of the partition. The cap keeps cost fixed.

Land it I store a read pointer and count at most 100 newer rows, so the cost is bounded and retries are safe.

Likely follow-ups
"Why not a counter?"

A counter is the natural first idea, but it is the wrong fit for a number the user sees. Cassandra counters are not idempotent. If an increment times out, you cannot know whether it applied. Retry and you may count twice, do not retry and you may miss one.

Resets are also awkward. To mark everything read you must write a negative delta equal to the current value, which means reading it first and racing with new messages. A missed decrement leaves a wrong badge that stays wrong.

The pointer approach avoids all this. Store last_read (a timeuuid) per user and conversation. Writing it is an overwrite, so writing it twice gives the same result. The unread number is derived by counting messages newer than the pointer, so it can never drift from the real data.

Counters suit things like page views, where being off by a few does not matter. Badges are user-visible, so I choose the pointer.

"How many reads is that for the home screen?"

It is one small read per conversation on screen. For 20 conversations that is 20 reads. Because each is a single-partition read, they run in parallel, and the screen waits only for the slowest, a few milliseconds each (illustrative).

  1. Compute on read: for each conversation, read the user's pointer, then count messages in that conversation newer than it, with a LIMIT of 100. Two tiny reads per conversation, bounded.
  2. Cache in the list: keep an unread_hint column in conversations_by_user, updated when a message arrives, so the home screen needs only one query.

The second option moves cost to the write path: each new message touches every member's row. The first keeps writes cheap and reads more numerous.

I decide by the ratio. If users open the app far more often than messages arrive per person, the cached value wins. Otherwise compute on read.

"How do you mark all as read?"

You update the pointer to the newest message id. That is one small write, whether the conversation has five unread messages or five thousand. Nothing else changes, because the unread count is computed from the pointer.

mark all readruns offline
-- illustrative
-- PostgreSQL: touch every unread row
UPDATE messages SET read = true WHERE conversation_id = 9 AND user_id = 3 AND read = false;
-- CQL: one overwrite of the pointer
INSERT INTO read_pointer_by_user (user_id, conversation_id, last_read) VALUES (3, 9, now());

In the relational design with a per-message read flag, the update can touch thousands of rows and take row locks. Here it is constant work.

A subtle point: set the pointer to the newest id you actually showed the user, not the newest in the database. A message that arrived while they were reading should still count as unread.

That constant cost is also why the pointer design copes with huge backlogs, such as a user returning after a holiday.

"What if messages are deleted?"

Deleting a message in Cassandra writes a tombstone: a marker that hides the row until compaction can drop it. A deleted message above the read pointer simply drops out of the count, which is the correct result. The cost is that reads of that slice must skip the tombstone.

A few deletes are harmless. The warning threshold is 1,000 tombstones scanned in one read, and the failure threshold is 100,000. A chat where users delete a handful of messages never gets near that.

The risk is a conversation where many messages are deleted and the unread count scans a long range of tombstones. The capped count helps, because it stops after 100 live rows.

For rare, bulk cases I would use a deleted flag in the row and filter in the app, accepting that the row stays. Tombstones are tidied up only after gc_grace_seconds (10 days by default) and a compaction, so deletion is not instant.

Q83 · Design. "QuickBite needs: orders by customer, a restaurant's live orders today, and the status timeline of one order. Design it."

Reveal answer

Strong answer List the queries first. Q1: customer's last 20 orders. Q2: restaurant's open orders today. Q3: full status history of one order.

Three tables. orders_by_customer partitioned by customer, clustered by time descending. orders_by_restaurant_day partitioned by (restaurant_id, day). order_events_by_order partitioned by order_id and clustered by event time, one row per status change.

Status changes are inserts into the event table plus an update of the current status in the other two. History is the event table, so nothing is lost by overwriting.

Picture it One order's life.

The setup: Order 42 goes PLACED, ACCEPTED, PREPARING, PICKED_UP, DELIVERED across 35 minutes.

Relational · PostgreSQL

Orders and order_events tables joined by order id.

orders.sqlruns offline
SELECT o.*, e.status, e.at
  FROM orders o
  JOIN order_events e ON e.order_id = o.id
 WHERE o.id = 42 ORDER BY e.at;
CREATE INDEX ON orders (restaurant_id, day);

Cassandra · CQL

Three tables, three questions.

orders.cqlruns offline
CREATE TABLE order_events_by_order (
  order_id uuid, at timestamp,
  status text, actor text,
  PRIMARY KEY (order_id, at)
);
-- plus orders_by_customer
-- plus orders_by_restaurant_day

The shift: Relational reads join one set of tables for each screen; Cassandra gives each screen its own pre-joined table.

Make the invisible visible: The timeline read and the live list read.

orders-read.txtruns offline
# illustrative output
SELECT * FROM order_events_by_order WHERE order_id = 42;
 PLACED    10:00:02 | ACCEPTED 10:00:40 | PREPARING 10:03:10
SELECT * FROM orders_by_restaurant_day
 WHERE restaurant_id = 3 AND day = '2026-11-23'
   AND status IN ('PLACED','ACCEPTED','PREPARING');

Why: Each read hits one partition. The restaurant partition holds one day of orders, perhaps 600 rows, a small and bounded size.

Land it I list the three queries, then give each its own table, with the event table as the source of history.

Likely follow-ups
"How do I list only open orders in the restaurant table?"

There are two ways, and both rely on keeping a small, bounded set of rows to read.

  1. Status in the clustering key: cluster by (status, placed_at, order_id) inside the (restaurant, day) partition, then query each open status in turn (status = 'PLACED', 'PREPARING'). A status change then means delete plus insert, because a clustering column cannot be updated.
  2. A second small table: open_orders_by_restaurant, partitioned by restaurant, holding only open orders. Insert when the order is placed and delete when it closes.

The second is my pick for a live kitchen screen. The partition holds a few dozen rows, and the screen needs one read.

The trap is tombstones: every closed order leaves one. With a few hundred orders a day per restaurant that is fine, but I keep the table bounded, and I would never use this pattern as a global queue (Q56). In PostgreSQL this is simply WHERE status IN ('PLACED','PREPARING') on an index.

"What stops the three tables drifting apart?"

Cassandra does not enforce this, so you do. Three layers work together.

  1. One logged batch for the creation: the order row, the event row and the restaurant row go in a single logged batch. A logged batch guarantees that all the writes eventually apply, even if the coordinator fails midway. It is not isolated, so a reader may briefly see some of them.
  2. The same set of writes on every change: a status update writes the new event and updates the current status in both copies, in one batch each time, from one code path.
  3. A reconciliation job: each night, sample orders and compare the three tables.

The batch spans three partitions, so it costs more than a single-partition write, but with three small rows it stays far below the 5 KiB warning size. I also make every write an upsert, so a retry is harmless.

Drift is rare with this discipline, and the nightly job tells me when it is not.

"Why a day in the restaurant partition key?"

Because without it one restaurant's orders pile into one partition forever. A busy restaurant with 400 orders a day creates 146,000 rows a year, past the guideline of about 100,000 rows per partition, and a single partition lives on only three replicas, so it also becomes a hot spot.

partition arithmeticruns offline
illustrative: 400 orders/day, about 300 bytes each
(restaurant_id)          : 146,000 rows/year  -> grows without limit
(restaurant_id, day)     : 400 rows, about 120 KB -> fixed ceiling
SELECT ... WHERE restaurant_id = 5 AND day = '2026-11-25';   -- one partition

The day caps the size, and today's screen touches exactly one partition. Yesterday's report uses yesterday's key, and a week's report is seven small reads.

The cost is that "all time for this restaurant" now needs many queries, so I only choose it if no screen asks for that.

I write the arithmetic into the design page, so the next reader sees why the day is there and can re-check it.

"Could I use a status column and overwrite?"

Yes for current state, but I would not rely on overwriting alone. If status is a single column that is overwritten, the history is gone. When a customer disputes "my order was never marked delivered", you cannot show who changed what and when.

Event rows fix that. Each change is an insert, (order_id, event_time, status, actor). Inserts with different clustering keys never conflict, so two services recording events at nearly the same time both survive. With an overwritten column, last-write-wins would silently drop one of them.

The cost is small: a status change writes one extra row.

So I keep both. The event table is the truth and the audit trail. The status column in the other two tables is a fast copy for the screens. If the copy ever looks wrong, I can rebuild it by taking the latest event per order.

Q84 · Design. "Design storage for IoT: 50,000 sensors, one reading per second, kept 30 days, queried by sensor and time range."

Reveal answer

Strong answer Do the arithmetic first. 50,000 readings per second is 4.3 billion per day. At 50 bytes that is about 216 GB per day (before replication), and about 6.5 TB for 30 days.

Partition by (sensor_id, day). That is 86,400 rows, about 4 MB, per partition. Cluster by ts ascending. Use TWCS with a one-day window and default_time_to_live of 30 days, so whole files are dropped on expiry.

Queries are always sensor_id + day + time range, which is one partition read.

Picture it One sensor, one day.

The setup: Sensor 5, 2026-11-23: 86,400 rows.

Relational · PostgreSQL

A big table with a BRIN or B-tree index, partitioned monthly.

iot.sqlruns offline
CREATE TABLE readings (
  sensor_id int, ts timestamptz, temp real
) PARTITION BY RANGE (ts);
CREATE INDEX ON readings (sensor_id, ts);
-- drop old monthly tables by hand

Cassandra · CQL

Bucket by day, TWCS, TTL.

iot.cqlruns offline
CREATE TABLE readings_by_sensor_day (
  sensor_id int, day date,
  ts timestamp, temp float,
  PRIMARY KEY ((sensor_id, day), ts)
) WITH default_time_to_live = 2592000
  AND compaction = {
   'class': 'TimeWindowCompactionStrategy',
   'compaction_window_unit': 'DAYS',
   'compaction_window_size': 1};

The shift: Relationally you partition by table and index; in Cassandra the partition key and TWCS give the same effect with expiry for free.

Make the invisible visible: Sizing in numbers.

iot-size.txtruns offline
# illustrative output
rows/day     = 50,000 x 86,400    = 4.32 billion
bytes/row    = about 50           = 216 GB/day raw
30 days x RF 3                    = about 19 TB total
per partition (sensor, day)       = 86,400 rows, about 4 MB
query: WHERE sensor_id=5 AND day='2026-11-23' AND ts >= '10:00'

Why: A 4 MB partition is comfortably small. Expired days leave as whole SSTables, so no delete job and no per-row tombstones.

Land it I size from sensors times rate times bytes, bucket by sensor and day, and use TWCS with a table TTL.

Likely follow-ups
"Why not bucket by hour?"

Because the bucket size trades partition size against the number of queries, and the dashboard asks for days.

hour vs day bucketruns offline
illustrative: 1 reading/s, 50 bytes
hour bucket: 3,600 rows,  about 180 KB   -> a day chart = 24 partition reads
day bucket : 86,400 rows, about 4.3 MB   -> a day chart = 1 partition read

Both are far below the guideline of about 100 MB, so the smaller hour partitions bring no benefit here. They only add reads. The day bucket matches the most common screen, so I choose it.

The rule is to choose the bucket from the most common query range. If the main screen showed the last 10 minutes, hours would be fine. If a sensor sent a reading every 10 ms, the day would grow to 8.6 million rows and I would go smaller. In PostgreSQL you would not bucket at all; you would add an index on (sensor_id, ts) or use native partitioning.

"What if a sensor reports ten times a second?"

Recompute, and the numbers still fit but with less room. Ten readings a second is 864,000 rows a day. At 50 bytes that is 43 MB per partition, below the guideline of about 100 MB but far above the row count of about 100,000 that the guideline also suggests.

  1. Check both limits: 43 MB passes the size test, but 864,000 rows fails the row-count test, and large partitions slow reads and repair.
  2. Choose a smaller bucket: use hour buckets, 36,000 rows and about 1.8 MB each.
  3. Cost to the reader: a day chart now needs 24 reads, which the app sends in parallel.

Always recompute with the real rate, because sensor firmware changes. I also check the largest partition with nodetool tablehistograms a few weeks after launch, so the estimate meets reality.

"How do I query across all sensors?"

Not in Cassandra. A question like "the average temperature of all sensors in the north region last week" would have to read 50,000 partitions across the cluster. Cassandra is built to serve one partition at a time, and a scan like that is slow and hurts normal traffic.

The answer is to calculate it as the data arrives. A stream job reads the readings from Kafka, groups them by site and hour, and writes the result into a small table such as hourly_avg_by_site, keyed by (site, day). The dashboard then reads one partition.

For ad-hoc questions, copy the data to a column store or a warehouse, which is designed for scans over many rows.

In PostgreSQL one SELECT avg(value) ... GROUP BY site over an indexed range might be fine at a smaller scale. Here the scale is why you picked Cassandra, so analytics has to live elsewhere.

"What if data arrives late?"

Late data lands in an old time window, which can cause trouble for TWCS. TWCS (time-window compaction) groups SSTables by the time of their data and drops a whole file when everything in it has expired. A reading with a two-day-old timestamp goes into the old day's partition, but the write itself arrives in a new memtable and SSTable.

That new SSTable contains old data. TWCS places it in the window that matches the data, so a small amount is fine. A large backfill, however, can reopen old windows, trigger compaction in them, and delay dropping expired files.

  1. Small lateness: seconds or minutes of delay costs nothing special.
  2. Large backfill: load it in time order and expect extra compaction.

The TTL is also computed from the write time unless you set it per row. I limit lateness upstream, for example by rejecting readings older than a day, and I keep the real timestamp as ts.

Q85 · Design. "On the same IoT system: show the latest reading for every sensor on a map, refreshed every few seconds."

Reveal answer

Strong answer The time-series table is wrong for this, since 'latest per sensor' would scan one partition per sensor. Add a second table latest_by_sensor with one row per sensor, overwritten on every reading.

Overwriting is cheap in Cassandra: an upsert with the same key. The newest timestamp wins, so only the latest value is visible.

To show a region on a map, group sensors in a partition by region, so one query returns a few thousand rows.

Picture it One row per sensor.

The setup: Region 'north' has 4,000 sensors, each row 60 bytes, so 240 KB.

Relational · PostgreSQL

A query with DISTINCT ON picks the last row per sensor.

latest.sqlruns offline
SELECT DISTINCT ON (sensor_id)
       sensor_id, ts, temp
  FROM readings
 ORDER BY sensor_id, ts DESC;
-- heavy: scans each sensor's newest rows

Cassandra · CQL

A table that only holds the latest.

latest.cqlruns offline
CREATE TABLE latest_by_region (
  region text, sensor_id int,
  ts timestamp, temp float,
  PRIMARY KEY (region, sensor_id)
);
INSERT INTO latest_by_region (...) VALUES (...)
USING TTL 300;  -- vanishes if sensor dies

The shift: The relational query finds the latest at read time; Cassandra keeps the latest ready at write time.

Make the invisible visible: What the map query sees.

latest.txtruns offline
# illustrative output
SELECT * FROM latest_by_region WHERE region = 'north';
 4,000 rows, one partition, about 20 ms
sensor 17 silent for 5 min -> its row expired by TTL
 -> the map shows it as offline

Why: The TTL turns 'no data' into a visible fact: a missing row means silent sensor, with no extra job.

Land it I keep a tiny 'latest' table overwritten on each write, with a short TTL to show silent devices.

Likely follow-ups
"Does overwriting create tombstones?"

No. An overwrite is just a newer version of the same cell, and no delete marker is written. Cassandra keeps the version with the highest timestamp, and compaction later discards the older versions. Only deletes, nulls and expired TTL cells create tombstones.

The TTL on the latest table does create one tombstone-like marker per expired cell, once, when the sensor goes silent for the full period. That is a single marker per quiet sensor, not one per update.

latest readingruns offline
-- illustrative
INSERT INTO latest_by_sensor (region, sensor_id, ts, value)
VALUES ('north', 'S-17', '2026-11-25 10:00:03', 21.4) USING TTL 60;
-- PostgreSQL: INSERT ... ON CONFLICT (sensor_id) DO UPDATE rewrites a row and leaves a dead tuple

In PostgreSQL an update also leaves a dead row version until vacuum cleans it, so both systems clean up later. Cassandra's cleanup is part of compaction.

So the latest table stays small and clean, and I would not worry about overwrites, only about the hot-partition risk below.

"What about the write rate on one partition?"

The numbers matter here. If one region has 4,000 sensors reporting once per second, the partition north receives 4,000 writes per second. All of them land on the same three replicas. That may be hot, because a single partition cannot be spread over more nodes.

Whether it is a problem depends on the hardware. A node can often handle thousands of simple writes a second, but I would test it, not assume.

  1. Split the region: use smaller cells, such as a grid of map tiles, so each partition holds a few hundred sensors.
  2. Add a shard number: (region, shard) with shard = hash(sensor_id) mod 4, and the map reads four partitions in parallel (Q72).

The map needs only the sensors in view, so tiles also match the screen. I choose tiles when the product shows a map, and a shard when it does not.

"How to push updates to the browser?"

Cassandra cannot push changes to a browser. It only answers requests. Making a screen "live" by polling every second means every open map sends one query a second, which wastes capacity and still lags.

  1. Publish: each sensor reading goes to a Kafka topic as well as to Cassandra.
  2. Fan out: a WebSocket service consumes the topic and sends the updates to the browsers that are watching that region.
  3. Load and reconnect: when a page opens, or a connection drops, the browser reads the current state from latest_by_sensor, then continues with the pushed stream.

So Cassandra serves the first picture and history, and Kafka plus WebSockets carry the live changes. This keeps the read rate on Cassandra flat as viewers increase. A rule I use is never to poll Cassandra on sub-second timers for a live screen. See the Kafka chapter (E17) for the stream side.

"Why not read the last row of each time-series partition?"

Because it multiplies the work by the number of sensors. The time-series table is keyed by (sensor_id, day). Finding the newest reading of a sensor means one query to that partition, ordered newest-first with LIMIT 1. For a map of all 50,000 sensors that is 50,000 queries each time it refreshes.

query countruns offline
illustrative
time-series table : 50,000 sensors = 50,000 queries per refresh
latest_by_sensor  : 1 query per region, about 4,000 rows each, 13 regions = 13 queries
extra write cost  : 1 more write per reading (50,000 writes/s on top of 50,000)

The latest table costs one extra write for each reading. That doubles the write count, but it replaces tens of thousands of reads on every refresh, and writes in Cassandra are cheap. So I write once more to save fifty thousand reads. In PostgreSQL you would use DISTINCT ON over an index instead.

I would also note that these 50,000 reads would arrive together, so the burst itself could hurt other traffic.

Drill · Feeds, rankings, locations and sessions

Four more designs where the right answer includes saying which part Cassandra should not do.

Q86 · Design. "Design a social activity feed. Fan-out on write or fan-out on read?"

Reveal answer

Strong answer Fan-out on read means the feed is built when you open it: find everyone you follow, fetch each one's newest posts, merge. It is cheap to write and expensive to read.

Fan-out on write means each new post is copied into a feed_by_user row for every follower. Reading is one partition read. Writing costs one row per follower.

Cassandra likes the second: reads are one partition, and writes are cheap. A post by someone with 200 followers writes 200 small rows.

Picture it One post, 200 followers.

The setup: Asha has 200 followers and posts a photo.

Relational · PostgreSQL

Join followers with posts at read time.

feed.sqlruns offline
SELECT p.* FROM posts p
  JOIN follows f ON f.followee = p.author
 WHERE f.follower = 7
 ORDER BY p.created DESC LIMIT 30;
-- reads from many authors, then sorts

Cassandra · CQL

Copy the post into each follower's feed.

feed.cqlruns offline
CREATE TABLE feed_by_user (
  user_id uuid, post_id timeuuid,
  author_id uuid, preview text,
  PRIMARY KEY (user_id, post_id)
) WITH CLUSTERING ORDER BY (post_id DESC);
-- fan-out: 200 INSERTs, one per follower

The shift: Relational joins at read time; Cassandra pays at write time so the read is one partition.

Make the invisible visible: Work done per action.

fanout.txtruns offline
# illustrative output
                    posting         opening feed
fan-out on read     1 write         merge 200 authors, slow
fan-out on write    200 writes      1 partition read, 4 ms
post_id is a timeuuid so rows arrive newest-first

Why: Most people read their feed far more often than they post, so moving work to the post side makes the whole system cheaper.

Land it I choose fan-out on write for ordinary users, because reads outnumber writes by a wide margin.

Likely follow-ups
"How long should the feed be kept?"

Keep a bounded window, not the whole history. I would keep the newest 1,000 to 5,000 items per user, with a TTL of about 30 days on each row. Older items are rarely scrolled to, and the app can load them from the authors' own timelines on demand.

The arithmetic shows why. If each feed row is about 200 bytes, 5,000 rows is 1 MB per user, well inside the guideline of about 100 MB and 100,000 rows per partition. An unbounded feed would grow for years for active users and eventually become a wide, slow partition.

  1. Bound by time: a table-level default_time_to_live of 30 days lets old rows expire without extra code.
  2. Bound by count: a trim job, or the app on write, removes rows beyond the newest 5,000.

Expiry makes tombstones, but with newest-first reads the first page never touches the old end. I choose bounded feeds because the cost then stays predictable for every user.

"What if a follower is deleted?"

Nothing needs to change for the old feed rows. If a follower deletes their account, their feed partition is just deleted or left to expire by TTL, and no other user's data is affected. The fan-out wrote copies into that follower's partition only.

The harder case is unfollowing. The follower's feed already holds copies of the author's recent posts. You have two choices:

  1. Filter in the app: when reading the feed, drop posts whose author is no longer followed. Cheap, and old rows expire on their own.
  2. Delete the rows: remove that author's rows from the feed partition. This needs a lookup of which rows, and writes tombstones.

Unfollowing happens far less often than posting, so I would filter in the app and delete only if privacy or policy demands it. In PostgreSQL a feed is a live join, so an unfollow takes effect immediately with no cleanup. Here you pay a little at unfollow time to keep reads simple.

"Do the 200 writes have to be atomic?"

No, they should not be atomic, and forcing it would hurt. A logged batch across 200 different partitions makes the coordinator send writes to many nodes and wait for the batch log. Batches over 5 KiB raise a warning and over 50 KiB fail, so it would also be fragile.

The better pattern is 200 independent upserts, sent asynchronously with a cap on in-flight requests. Each write is idempotent: the key is (follower_id, post_time, post_id), so writing it twice gives the same row.

fan-out writesruns offline
illustrative
for follower in followers(author):          # 200 followers
    async upsert feed_by_user(follower, post_time, post_id, ...)
on failure: retry that one write; the others are not affected

If one write fails, you retry it alone. A follower seeing the post a second later is fine for a feed, so atomicity buys nothing here.

The same reasoning is why a bulk loader using unlogged batches across many partitions is a known anti-pattern for speed.

"Where does the fan-out run?"

The fan-out runs in a background worker, not in the request that creates the post. The poster's request does one thing: write the post and publish a PostCreated event to Kafka. It then returns in a few milliseconds.

  1. Consume: a worker group reads the events. Partitioning the topic by author keeps one author's posts in order.
  2. Fan out: the worker looks up the author's followers and upserts a row into each follower's feed.
  3. Commit: it commits the Kafka offset only after the writes succeed.

If the worker crashes midway, Kafka delivers the event again, and the worker repeats the writes. Because each is an idempotent upsert, the repeat is harmless.

It also protects the poster from slowness: a post by a user with 200,000 followers takes longer to fan out, but the poster is not waiting. I size the worker count from the write rate (Q97). See the Kafka chapter, E17, for consumer groups.

Q87 · Design. "One user has 20 million followers. Fan-out on write now means 20 million writes per post. What do you do?"

Reveal answer

Strong answer This is the celebrity problem. Use a hybrid: fan out on write for normal users, but for celebrities do not copy; mark them as 'pull'.

When you open your feed, read your feed_by_user partition (the pushed posts) and, for the few celebrities you follow, read their own posts_by_author partition. Merge the two sorted lists in the app.

The merge is cheap because both inputs are already sorted and you only need the top 30.

Picture it Count the writes.

The setup: 20 million rows at 100 bytes is 2 GB of writes for one post, in about a minute with 50,000 writes per second (illustrative).

Relational · PostgreSQL

One query handles all, at the cost of a join and a sort.

celeb.sqlruns offline
SELECT * FROM posts p
  JOIN follows f ON f.followee = p.author
 WHERE f.follower = 7
 ORDER BY p.created DESC LIMIT 30;
-- slow but needs no extra copies

Cassandra · CQL

Push for most, pull for the few big ones.

hybrid.cqlruns offline
-- pushed posts
SELECT * FROM feed_by_user
 WHERE user_id = 7 LIMIT 30;
-- pulled celebrity posts (per celebrity)
SELECT * FROM posts_by_author
 WHERE author_id = ? LIMIT 30;
-- merge the lists in the app

The shift: Relational joins always; Cassandra picks push or pull per author size.

Make the invisible visible: Which path each author takes.

hybrid.txtruns offline
# illustrative output
author          followers   path
Asha            200         push (200 writes)
local cafe      5,000       push (5,000 writes)
big star        20,000,000  PULL (0 writes, read on open)
rule: followers > 100,000 -> pull   (illustrative threshold)

Why: Push cost grows with followers, pull cost grows with the number of celebrities you follow, which is small. Choose per author.

Land it I use a hybrid with a follower-count threshold, pushing for ordinary users and pulling for celebrities.

Likely follow-ups
"How do I pick the threshold?"

The threshold balances two costs: write cost for pushing, and read cost for pulling. Pushing a post costs one write per follower. Pulling costs one extra partition read per celebrity every time someone opens their feed.

threshold arithmeticruns offline
illustrative: user with 100,000 followers posts 5 times a day
push cost: 100,000 x 5 = 500,000 writes/day
pull cost: each follower who opens the app (say 40,000 opens, 3 times) = 120,000 extra reads/day
200,000 followers: push 1,000,000 writes/day, pull still bounded by opens

Start near 100,000 followers, measure, and adjust. A cluster with spare write capacity can push for more users, and a cluster with tight writes should pull earlier.

The right number depends on your hardware, your post rate and how often people open the app. I would also make the threshold a config value, not a code constant, and re-evaluate when traffic changes.

Whatever number you start with, record how you chose it, so the next person can tell when the reasoning no longer holds.

"What if a user follows 500 celebrities?"

You cap the pull list, because otherwise one feed open could cost 500 extra reads. Reads are done in parallel, but the merge, the network and the latency all grow with the number of sources.

  1. Limit the sources: read only the 20 to 50 celebrities this user interacts with most, ranked by likes, replies or recent views.
  2. Limit the rows: take only the newest 30 posts from each, since only the top 30 of the merge will be shown.
  3. Merge: combine the sorted lists in the app and keep the top 30.

The rest of the celebrities can appear in a separate "following" tab, or through a slower refresh. This is a product decision as much as an engineering one, and it protects the system from users with unusual behaviour.

A bound like this turns an open-ended cost into a number I can put in the capacity plan.

"Is there a Cassandra-specific hazard?"

Yes: the celebrity's own posts partition becomes a hot partition. Millions of followers all read the same posts_by_author partition, so the same three replica nodes serve a huge read rate, and more nodes would not help (Q72).

The fix is that every follower reads identical data, which makes it ideal to cache. Keep the newest posts of each celebrity in the application's memory, or at a CDN, for a few seconds.

cache effectruns offline
illustrative: 1,000,000 reads per minute of one celebrity's page
with a 5 second cache and 20 app servers: 20 servers x 12 refreshes/min = 240 reads/min to Cassandra

That turns a million reads into a few hundred. The cost is up to 5 seconds of staleness on a celebrity's newest post, which is fine for a feed. For celebrities I accept a cache happily, because the data is shared and read-mostly.

Also keep that cache small: a few hundred celebrity entries fit easily in memory on each application server.

"How does this compare to how Postgres teams do it?"

Postgres teams start with the simple design and arrive at the same hybrid when it breaks. The simple design is a join: SELECT p.* FROM posts p JOIN follows f ON f.followee_id = p.author_id WHERE f.follower_id = ? ORDER BY p.created_at DESC LIMIT 30. It works well while the data is small.

As traffic grows, they add read replicas, then a cache, then a precomputed feed table for ordinary users. When celebrities appear, they notice that pushing a post to millions of rows is too much, and they pull for those users. That is exactly the hybrid.

So the difference is the starting point. A PostgreSQL system takes years to get there, evolving as it hurts. A Cassandra design starts at the end of that path, because it cannot do the join in the first place.

In an interview I add that for most products the join is fine. I would not start a small app on Cassandra for this reason alone.

Q88 · Design. "Build a live leaderboard: top 100 players, and the rank of any single player."

Reveal answer

Strong answer Cassandra can store scores but is awkward for ranks. Sorting by a changing score means deleting and re-inserting a row, which creates tombstones.

For the top 100, keep a score_by_board table partitioned by (board, bucket) with a clustering order on score descending, or compute the top 100 in a stream job and write the result. For one player's rank you need ordering over everything, which a sorted set in Redis does well.

A common answer is to say Cassandra stores durable scores and Redis (or a stream job) serves the ranks.

Picture it Updates change the sort order.

The setup: A player's score goes from 900 to 950. Their place changes.

Relational · PostgreSQL

An ORDER BY score DESC with an index.

board.sqlruns offline
SELECT player, score FROM scores
 ORDER BY score DESC LIMIT 100;
SELECT count(*) + 1 FROM scores
 WHERE score > (SELECT score FROM scores
                WHERE player = 'asha');

Cassandra · CQL

Store scores by player; serve the top from a derived table.

board.cqlruns offline
CREATE TABLE score_by_player (
  player text PRIMARY KEY, score int);
CREATE TABLE top_by_board (
  board text, rank int, player text, score int,
  PRIMARY KEY (board, rank));
-- a job rewrites top_by_board every 5 s

The shift: A relational ORDER BY re-sorts at read time; Cassandra stores a ready-made top list and cannot rank an arbitrary player cheaply.

Make the invisible visible: Who answers which question.

board.txtruns offline
# illustrative output
question               store
top 100 right now      top_by_board (1 partition read)
my score               score_by_player (key lookup)
my rank among 5M       Redis sorted set ZREVRANK, or approximate:
                       "top 1%" from percentile buckets

Why: An exact rank over millions needs a structure ordered by score. Cassandra's order is by clustering key inside one partition, not across a table.

Land it I keep scores in Cassandra, publish the top 100 as a derived table, and put exact ranks in a sorted set, or settle for percentiles.

Likely follow-ups
"Can I put all players in one partition ordered by score?"

It would work badly, and I would not do it. Three problems stack up.

  1. A giant partition: millions of rows in one partition breaks the guideline of about 100 MB and 100,000 rows, and slows reads, compaction and repair.
  2. A hot spot: every score update goes to the same three replicas, so one machine pair takes the whole write load.
  3. Score is a clustering column: a clustering column cannot be updated. A score change means delete the old row and insert a new one, which leaves a tombstone for every change.

A player with 500 score changes a day would create 500 tombstones in that partition. Reads of the top 100 would then wade through tombstones.

A safer layout is to bucket players by score range, so each partition is small, and to read from the highest bucket down until you have 100 rows. But even that churns tombstones when scores change often. That is why I compute the top list elsewhere, in a stream job, and store only the result.

"What is the percentile trick?"

The percentile trick gives an approximate rank cheaply. Instead of ordering every player, you group players into score buckets, such as 0-99, 100-199, and so on, and keep a counter per bucket for the number of players inside it.

percentile rankruns offline
illustrative: 1,000,000 players; player score 840
players in buckets above 800-899:  900-999 = 40,000; 800-899 = 80,000
rank is about 40,000 + (share of the 800-899 bucket above 840), roughly 40,000 to 120,000
message: "you are in the top 12 percent"

Reading the counts is a small query: one partition with a few dozen bucket rows. A player moving between buckets decrements one counter and increments another.

It is good for a message like "you are in the top 8 percent". It is not good for "you are exactly number 4,382". The counters can drift (Q60), which is fine for percentiles. If product insists on exact ranks, I move that part to Redis.

The accuracy is also tunable: narrower buckets give a finer rank but more rows to read and more counters to keep correct.

"How do I update the top list?"

I use one writer: a stream job. It reads score-change events from Kafka, keeps the current scores in its own state, and every few seconds writes the top 100 to a table such as top_by_board, with the board and rank as the key.

  1. Key by rank: (board, rank) is the primary key, with player and score as values.
  2. Overwrite: each refresh writes 100 rows over the previous 100. Overwrites by the same key create no tombstones.
  3. Read: the screen reads one partition of 100 rows.

A single writer also means no write conflicts and no last-write-wins surprises. If the job restarts, it replays Kafka from its last checkpoint and writes the same rows again, which is harmless.

The result may be a few seconds stale. For a leaderboard that is fine, and I would say so on the screen with a timestamp.

"When is Cassandra the wrong choice entirely?"

When an exact, live rank for millions of users is the core feature. If every player must see "you are number 4,382" the instant they score, you need ordering over the whole set. Cassandra orders only inside one partition, so it cannot do that for a changing score.

Better tools exist. Redis sorted sets keep members ordered by score and answer "rank of this player" in logarithmic time, with a command such as ZREVRANK. A relational database with an index on score can do the same with a count of higher scores, using an ordered index, at a size a single machine can hold.

rank, SQLruns offline
-- illustrative
-- PostgreSQL: rank is a count over an ordered index
SELECT count(*) + 1 FROM scores WHERE score > (SELECT score FROM scores WHERE player = 42);

Saying so in an interview shows judgement. Knowing the limits of a tool is a stronger signal than defending it everywhere.

Q89 · Design. "Show a rider's live location to the customer while they wait, with 10,000 riders updating every 3 seconds."

Reveal answer

Strong answer Two stores. Live location is a tiny table rider_location with one row per rider, overwritten each update, with a short TTL (say 60 seconds). History (for dispute or analytics) is a time-series table by (rider_id, day).

The customer's screen asks for one rider's row every few seconds, or better, gets pushed updates from Kafka through a WebSocket gateway. Cassandra serves the 'where is the rider now' read; it does not push.

Write rate: 10,000 riders every 3 seconds is about 3,300 writes per second, light for Cassandra.

Picture it One rider, one row.

The setup: Rider 9 at (12.9716, 77.5946), updated every 3 seconds.

Relational · PostgreSQL

An UPDATE in place, with an index on rider.

rider.sqlruns offline
UPDATE rider_location
   SET lat = 12.9716, lon = 77.5946,
       updated_at = now()
 WHERE rider_id = 9;
-- row rewrite and index maintenance
-- MVCC bloat for each update

Cassandra · CQL

An overwrite with a TTL, plus history.

rider.cqlruns offline
INSERT INTO rider_location
  (rider_id, lat, lon, updated_at)
VALUES (9, 12.9716, 77.5946, toTimestamp(now()))
USING TTL 60;
-- 3,300 writes/s across the cluster
-- history: readings keyed (rider_id, day)

The shift: Relational updates rewrite a row and bloat; Cassandra overwrites cheaply and the TTL cleans offline riders.

Make the invisible visible: What the app sees.

rider.txtruns offline
# illustrative output
SELECT lat, lon FROM rider_location WHERE rider_id = 9;
 12.9716 | 77.5946     (updated 2 s ago)
rider goes offline -> row expires after 60 s
 -> "location unavailable" without a cleanup job

Why: The row is overwritten in place logically, but physically each write is a new cell. Compaction cleans old versions, and the TTL removes dead riders.

Land it I overwrite a tiny live table with a short TTL, keep history separately, and push updates through Kafka, not through polling Cassandra.

Likely follow-ups
"Is overwriting 3,300 times per second a problem?"

It is fine, because the writes are spread over many keys. 10,000 riders each send one update every 3 seconds, which is about 3,300 writes per second in total. Each rider is its own partition, and each key gets one write per 3 seconds. The load is divided across the cluster by the token ring.

The dangerous pattern would be many writers hitting one key, such as a counter of "riders online" updated by every rider. That one partition would see 3,300 writes a second and could become hot (Q72).

write rateruns offline
illustrative
10,000 riders / 3 s = 3,333 writes/s overall
per key: 1 write per 3 s
on a 6-node cluster: about 560 writes/s per node (before replication x3 = 1,700)

Even tripled by replication, that is light. Overwrites need no read first, and old versions disappear at compaction, so no tombstones appear. In PostgreSQL the same rate of updates to 10,000 rows would create many dead tuples and need vacuum tuning.

"How do I find riders near a restaurant?"

Cassandra is weak at geographic queries, because it can only look up by key and order inside a partition. "Riders within 2 km" is a range in two dimensions, which a partition key cannot express.

  1. Cut the map into cells: use a geohash or a grid cell id as the partition key, so each cell covers an area of a few hundred metres to a few kilometres.
  2. Store riders by cell: a table riders_by_cell with cell_id as the partition key and rider_id as the clustering column. A move across a cell border means delete from the old cell and insert into the new one.
  3. Query the neighbours: read the restaurant's cell and the eight cells around it, in parallel, then filter by exact distance in the app.

That works for approximate matching. For heavy geospatial work, such as polygons or routing, I would use a geospatial database like PostGIS, not stretch Cassandra.

"Should the customer app poll?"

No, polling is the wrong tool at this size. If 100,000 customers have the tracking screen open and each asks every 3 seconds, that is about 33,000 reads per second just to learn that most riders moved a little. It is also slow: an update can wait nearly 3 seconds to be noticed.

  1. Publish: each rider update also goes to a Kafka topic.
  2. Push: a consumer feeds a WebSocket gateway, which sends each update only to the customer watching that rider.
  3. Catch up: when the screen opens or the connection drops, it reads the current row from rider_location once.

The push path does about 3,300 messages per second, one per update, which is a tenth of the polling load, and the screen updates the moment data arrives.

Cassandra still has a job: it answers the first load and any reconnect, and it holds the history. Kafka carries the live changes. See the Kafka chapter, E17.

"What about privacy?"

Location is personal data, so I plan for retention and deletion from the start. The rules depend on the country and the product, so check local data rules and involve the people responsible for privacy.

  1. Short TTL on history: put a default_time_to_live on the history table, such as 7 days, so the rows expire without any job. This matches a TWCS design.
  2. Deletion on request: keys are (rider_id, day), so a rider's data is easy to find. Delete those partitions, remembering that deletes write tombstones and that the data is physically removed only after gc_grace_seconds and compaction.
  3. Separate table: keep location in its own table with its own retention, access rules and backups, not mixed with order data.

Also encrypt in transit and at rest, and limit who can query it. Copies in Kafka topics and backups need the same retention, which people often forget.

Q90 · Design. "Where would you keep user sessions and rate-limit counters, and would you pick Cassandra?"

Reveal answer

Strong answer Sessions fit Cassandra well: one key, a small value, a TTL that refreshes. Writes are cheap, the data is replicated, and survival of a node loss is built in.

Rate limiting needs an atomic increment with a short window and exact decisions. Counters are approximate and slow for this. A sub-millisecond in-memory store such as Redis is a better fit.

I would use Cassandra for sessions if I already run it, and Redis for the limiter.

Picture it Compare the two jobs.

The setup: Session: read on each request, write on login and renewals. Limiter: increment on every request.

Relational · PostgreSQL

Sessions in a table with a cleanup cron.

session.sqlruns offline
CREATE TABLE sessions (
  token text PRIMARY KEY, user_id bigint,
  expires_at timestamptz);
DELETE FROM sessions WHERE expires_at < now();

Cassandra · CQL

The TTL is the expiry.

session.cqlruns offline
CREATE TABLE sessions (
  token text PRIMARY KEY, user_id bigint
) WITH default_time_to_live = 1800;
INSERT INTO sessions (token, user_id)
VALUES ('a9f...', 7);   -- gone in 30 min

The shift: Relational expiry needs a cleanup job; Cassandra's TTL expires the session by itself.

Make the invisible visible: Which store for which job.

session-choice.txtruns offline
# illustrative output
job                     fits Cassandra?   better
session by token        yes (key + TTL)   Redis also fine
rate limit per user     poor              Redis INCR + EXPIRE
login audit trail       yes (append)      -
idempotency keys        yes (LWT or key)  -

Why: Cassandra is strong at keyed lookups and appends with a lifetime. It is weak at tight atomic arithmetic.

Land it I put sessions and idempotency keys in Cassandra when it is already there, and rate limiters in an in-memory store.

Likely follow-ups
"Why not a counter for the limiter?"

A counter-based limiter would be both inexact and slow, and a limiter needs the opposite. Four problems:

  1. Retries double-count: a counter update is not idempotent (Q60), so a timeout followed by a retry may count a request twice and block a legitimate user.
  2. Latency: a counter update reads and writes on replicas and is slower than a normal write. A limiter sits on every request, so the latency adds up.
  3. No clean windows: a counter has no built-in expiry for "5 requests per minute". You would have to reset it, which means a racy read followed by a write.
  4. Weak consistency: two nodes may allow a request the limiter should have rejected.

A limiter wants an atomic increment with a short expiry in a single place, with sub-millisecond response. Redis does this with INCR plus EXPIRE (or a script). In an interview I would say that using Cassandra here is possible but it is the wrong shape.

"Does a refreshed session rewrite the row?"

Yes. Each refresh is an update with USING TTL, which writes a new version of the cell with a fresh expiry. In Cassandra every write is an upsert, so there is no read first; the cost is one small write replicated to three nodes.

session refreshruns offline
-- illustrative
UPDATE sessions USING TTL 1800 SET last_seen = toTimestamp(now()) WHERE token_hash = ?;
-- PostgreSQL: UPDATE sessions SET expires_at = now() + interval '30 minutes' WHERE id = ?
-- then a cleanup job deletes expired rows

The difference: in PostgreSQL expiry is a column plus a cleanup job, and each update creates a new row version. In Cassandra the TTL makes the data disappear on its own.

But do not refresh on every request. A user making 20 requests a minute would create 20 writes a minute for no benefit. I refresh at most once every few minutes, since a sliding window of 5 minutes is plenty.

"Is eventual consistency a problem for sessions?"

It can be, so choose the consistency levels to avoid it. The risk is a user who logs in on one request and is sent to the login page by the next, because the second request reaches a replica that has not yet received the session.

The cure is overlapping quorums. With replication factor 3 in the local datacentre, a LOCAL_QUORUM write is acknowledged by 2 replicas, and a LOCAL_QUORUM read asks 2. Since 2 + 2 is more than 3 (R + W > RF), at least one replica in the read has the new session, so the read sees it.

overlapruns offline
illustrative, RF = 3
write LOCAL_QUORUM = 2 acks, read LOCAL_QUORUM = 2 replicas
2 + 2 = 4 > 3, so a read always meets a replica that has the write

Pay for this only on the session table. The cost is slightly higher latency than ONE. Across regions, I would pin a user to their home region (Q93).

"What about security?"

Treat session tokens like passwords, because anyone who holds a live token acts as that user.

  1. Hash before storing: store a SHA-256 hash of the token as the key, not the token itself. If the database leaks, the hashes cannot be replayed as sessions. The app hashes the cookie value on each request.
  2. Encrypt the transport and the disk: enable client-to-node TLS and, where required, encryption at rest through the disk or volume.
  3. Limit the exposure window: a short TTL means a stolen but unused token dies on its own, and logout deletes the row.

Use random, long tokens (at least 128 bits of randomness) so they cannot be guessed. Also limit who can read the sessions table with Cassandra's role-based permissions, since a small service account should not read everything.

None of this is specific to Cassandra, but a senior answer names the details.

Drill · Operations, migration and choosing

The last ten questions are what a senior is asked after the schema is right: how it behaves when things fail, how to move to it and when to pick something else.

Q91 · Design. "Should inventory counts and payments live in Cassandra?"

Reveal answer

Strong answer No, not as the source of truth. Both need exact, isolated, multi-row transactions: 'decrease stock only if at least 1 is left' and 'move money from A to B or do nothing'.

Cassandra 5.0 gives last-write-wins, no isolation across partitions, and LWT only inside one partition. A relational database with real transactions is the right home for these records.

Use polyglot persistence: PostgreSQL for money and stock, Cassandra for the high-volume read models (order history, timelines, feeds), connected by Kafka and an outbox.

Picture it Two buyers, one last burger.

The setup: Stock is 1. Two orders arrive in the same millisecond.

Relational · PostgreSQL

A row lock and a conditional update decide it.

stock.sqlruns offline
BEGIN;
UPDATE stock SET qty = qty - 1
 WHERE item_id = 5 AND qty >= 1;
-- 1 row updated -> buyer 1 gets it
-- 0 rows        -> buyer 2 told: sold out
COMMIT;

Cassandra · CQL

Only a single-partition LWT can guard it.

stock.cqlruns offline
UPDATE stock_by_item SET qty = 0
 WHERE item_id = 5 IF qty = 1;
-- [applied] true for one buyer only
-- ok for one counter; fails for
-- multi-item carts and payments

The shift: Relational databases guard invariants across rows; Cassandra guards at most one partition, so put the invariants elsewhere.

Make the invisible visible: The split architecture.

polyglot.txtruns offline
# illustrative output
PostgreSQL : orders, payments, stock   (ACID, source of truth)
   | outbox table -> Kafka topic "order-events"
   v
Cassandra  : orders_by_customer, order_events_by_order,
             restaurant_live  (fast read models)

Why: Writers that must be exact use the transactional store. Readers that must be fast use the denormalised store, fed by events and tolerant of a short delay.

Land it I keep money and stock in PostgreSQL and project the events into Cassandra read models through an outbox and Kafka.

Likely follow-ups
"Can LWT guard stock for a single item?"

Yes, for exactly one item, and that is the limit. A lightweight transaction (LWT) such as UPDATE stock SET qty = 4 WHERE item = 'pizza' IF qty = 5 is a compare-and-set on one partition. It uses Paxos, roughly four round trips, so it is correct but several times slower than a normal write.

A real checkout is bigger than that. One order has several items, each in its own partition, plus a payment, plus the order row. LWT is linearizable only inside one partition, so you cannot make "reserve all three items and charge the card" succeed or fail as a whole.

stock guardruns offline
-- illustrative
-- PostgreSQL: one transaction, many rows
BEGIN; UPDATE stock SET qty = qty - 1 WHERE item = 'pizza' AND qty > 0; INSERT INTO orders ...; COMMIT;
-- CQL: single-partition compare-and-set only
UPDATE stock SET qty = 4 WHERE item = 'pizza' IF qty = 5;

That is where a relational transaction is simpler and safer.

So stock for a single flash-sale item may use LWT, but the order as a whole stays in the relational database.

"What about Cassandra 6.0 Accord?"

Accord is the new transaction protocol in the Cassandra 6.0 line, which is only an alpha at the time of writing (6.0-alpha1, March 2026). It aims to give general ACID transactions across partitions, written as BEGIN TRANSACTION ... COMMIT TRANSACTION, and it is off by default and enabled per table.

If it matures, it may change this answer for some cases: a stock decrement and an order insert in two partitions could commit together inside Cassandra. That would reduce the need to split money and stock into a second database.

  1. Today: design for 5.0, which has no multi-partition transactions.
  2. Later: test Accord on a copy of the workload when it reaches general availability.

I would not design a payment system on an alpha. Details may change before release, so I check the release notes and the docs, and I keep PostgreSQL as the source of truth until I have my own load and failure tests.

"How does the outbox work again?"

The outbox pattern removes the dual write. A dual write means the service updates PostgreSQL and then sends a message, and a crash between the two leaves them different.

  1. One transaction: the service inserts the order row and an event row in an outbox table, in the same PostgreSQL transaction. Both commit or neither does.
  2. Relay: a separate process, either Debezium reading the write-ahead log or a small poller, reads new outbox rows and publishes them to a Kafka topic.
  3. Consume: a consumer reads the topic and upserts into the Cassandra tables.

Kafka may deliver an event more than once, so the upserts must be idempotent: the same event written twice gives the same row.

The result is that PostgreSQL is the single place where truth is decided, and Cassandra follows. Q92 covers ordering and rebuilds. See the Kafka chapter (E17) and the microservices chapter (E7) for the pattern in full.

"What if the Cassandra copy lags?"

The Cassandra copy is eventually consistent with PostgreSQL, so for a short time a read may be behind. Usually the lag is under a second: PostgreSQL commit, relay, Kafka, consumer, Cassandra write. A backed-up consumer can make it minutes (illustrative figures).

The product must handle the gap on purpose. The clearest case is a customer who places an order and lands on "my orders", where it is missing. Three remedies:

  1. Read your own write: for the order just placed, read from PostgreSQL by id, and use Cassandra for the older list.
  2. Show a pending state: add the new order to the screen from the response, or show "updating...".
  3. Watch the lag: alert on consumer lag in Kafka, so a slow pipeline is noticed before users notice it.

Say it out loud as a known trade: you gain cheap, scalable reads and give up instant visibility. For the money itself, the user always sees the PostgreSQL value.

Q92 · Design. "How do you keep a Cassandra read model in sync with a PostgreSQL source of truth?"

Reveal answer

Strong answer Do not dual-write from the app: a crash between the two writes leaves them different. Use the outbox pattern: write the business row and an event row in one PostgreSQL transaction, then relay the event to Kafka.

A consumer reads the topic and upserts into each Cassandra table. Upserts are idempotent, so a replayed event does no harm.

To add a new table later, replay the topic from the start, or backfill from PostgreSQL, then switch the reads.

Picture it One order placed, three tables updated.

The setup: Order 42 is committed in PostgreSQL at 10:00:00.000.

Relational · PostgreSQL

One database, one transaction, indexes follow.

outbox.sqlruns offline
BEGIN;
INSERT INTO orders (...) VALUES (...);
INSERT INTO outbox (aggregate, type, payload)
VALUES ('order', 'OrderPlaced', '{...}');
COMMIT;   -- both or neither

Cassandra · CQL

A consumer applies the event to every table.

consumer.cqlruns offline
-- on OrderPlaced event (idempotent)
BEGIN BATCH
 INSERT INTO orders_by_customer (...) ...;
 INSERT INTO orders_by_restaurant_day (...) ...;
 INSERT INTO order_events_by_order (...) ...;
APPLY BATCH;

The shift: One transaction keeps relational data consistent; an event stream with idempotent upserts keeps Cassandra consistent later.

Make the invisible visible: The flow with lag.

sync.txtruns offline
# illustrative output
10:00:00.000 PostgreSQL commit (order + outbox)
10:00:00.040 relay publishes OrderPlaced to Kafka
10:00:00.120 consumer upserts 3 Cassandra tables
read-your-own-write: show the order from PostgreSQL
for the first few seconds, then switch to Cassandra

Why: The Cassandra tables are always a little behind. Upserts make a duplicate event harmless, and replay makes the pipeline repairable.

Land it I use an outbox, Kafka and idempotent upserts, never a dual write from the application.

Likely follow-ups
"What if events arrive out of order?"

Include a version or the source event time in the event, and write with USING TIMESTAMP set to that time. Cassandra resolves conflicts by keeping the cell with the highest timestamp. So if event 2 (newer) arrives before event 1 (older), the older event cannot overwrite it, because its timestamp is lower.

ordered upsertruns offline
-- illustrative: timestamps in microseconds taken from the PostgreSQL commit time
UPDATE orders_by_id USING TIMESTAMP 1764057600000000 SET status = 'SHIPPED' WHERE order_id = 42;
UPDATE orders_by_id USING TIMESTAMP 1764057500000000 SET status = 'PACKED'  WHERE order_id = 42;  -- arrives late, loses

Last-write-wins then works in your favour, since "last" now means last in the source, not last to arrive.

Two cautions. Use one clock for the timestamps, the source database, not each app server's clock. And in Kafka, key the topic by order id, so events for one order stay in order within a partition. That alone solves most cases.

I add a short test for this: replay the same events in shuffled order and check that the final rows match.

"How do I rebuild a table?"

You rebuild from the log. This is a major advantage of putting Kafka in the middle: the events are a history you can replay, so a new or broken table can be filled again.

  1. Create the new table: new keys, new name, in the same keyspace.
  2. Replay: start a new consumer group on the topic from the earliest offset. For a compacted topic, which keeps the latest event per key, that is enough to rebuild the current state.
  3. Verify and switch: compare counts and samples with PostgreSQL, then move reads to the new table and drop the old one.

If the topic has been trimmed by retention, it no longer holds the full history. In that case I backfill from PostgreSQL in slices (Q96), then let the consumer take over from a known offset.

The replay writes every event again, so it is slower and heavier than normal traffic. Throttle it so live reads are not hurt. In a plain relational design, adding a read model usually means a new view or an index build.

"Why not Cassandra CDC?"

Cassandra's change data capture (CDC) reads changes out of Cassandra's commit log, so it is useful for sending Cassandra's changes to other systems. That is the opposite direction from this design, where PostgreSQL is the source and Cassandra is the destination.

Using CDC would mean treating Cassandra as the source of truth for the order, which is the wrong place for transactions (Q91). Also, CDC works per node, and reading it correctly across replicas takes extra tooling to deduplicate changes.

The equivalent on the PostgreSQL side is change data capture from its write-ahead log, which is what Debezium does. It publishes row changes to Kafka without any change to the application code. That is the same idea pointed the right way.

So I use an outbox or Debezium on PostgreSQL, not Cassandra CDC. If I did need CDC from Cassandra, for example to feed a search index, I would check the current docs for the supported tools and their limits.

"How do I check for drift?"

I run a reconciliation job, because a pipeline with several steps can lose or duplicate data without anyone noticing. The job compares the two stores cheaply and then looks closer where they differ.

  1. Count per day: for each day, count orders in PostgreSQL and rows in the matching Cassandra table, and compare. A count in Cassandra over one bounded partition-day is affordable.
  2. Compare a sample: pick random order ids, load both versions, and compare the fields that matter, such as status and total.
  3. Alert and repair: raise an alert when the mismatch passes a threshold, such as 0.01 percent (illustrative), and re-publish the missing events.

Run it at night, off peak, and limit its rate.

It catches bugs the pipeline hides, such as a consumer that skips a malformed event, a retention setting that dropped events, or a schema change that nulls a field. Trusting a pipeline without checking it is a common failure.

Q93 · Design. "We run in two regions and want users to read and write locally. How does Cassandra do that, and what do we give up?"

Reveal answer

Strong answer Create the keyspace with NetworkTopologyStrategy, RF 3 in each datacentre. Each region's clients talk to local nodes with LOCAL_QUORUM. Cassandra replicates to the other region in the background.

You get low latency and survive losing a whole region. You give up instant global consistency: a write in one region appears in the other after the replication delay, and two regions writing the same row at once resolve by last-write-wins.

Design so a given row is mostly written from one region (for example, by the user's home region), or make writes append-only.

Picture it One user, two regions.

The setup: A user on the Mumbai app updates their profile; a colleague in Frankfurt reads it a moment later.

Relational · PostgreSQL

A primary in one region; replicas elsewhere.

multi.sqlruns offline
-- writes go to the primary (Frankfurt)
-- Mumbai reads a replica, lag about 200 ms
-- failover to Mumbai needs promotion
-- one writer, no conflicts

Cassandra · CQL

Both sites write; the keyspace says how many copies.

multi.cqlruns offline
CREATE KEYSPACE quickbite WITH replication = {
  'class': 'NetworkTopologyStrategy',
  'fra': 3, 'mum': 3};
-- each region: LOCAL_QUORUM reads and writes
-- cross-region copy happens in the background

The shift: Relational multi-region has one writer and a failover; Cassandra has many writers and last-write-wins.

Make the invisible visible: What happens in a region outage.

region-down.txtruns offline
# illustrative output
Frankfurt datacentre unreachable
 Mumbai clients: LOCAL_QUORUM still works (2 of 3 local)
 writes made in Frankfurt but not yet copied: delivered
   when the link returns (hints and repair)
 conflicts resolved by timestamp

Why: Each region is a full copy and a full write path, so one region failing leaves the other serving. The price is eventual agreement between regions.

Land it I use NetworkTopologyStrategy with LOCAL_QUORUM, and assign each row a home region to avoid conflicts.

Likely follow-ups
"How long is the cross-region delay?"

Replication to the other region is asynchronous, so the delay is roughly the network round trip between the regions plus a little queueing. For two regions on different continents that is tens to a couple of hundred milliseconds (illustrative). Under normal load it is usually well under a second.

During trouble it can grow: a network partition, a slow node, or a burst of writes makes the coordinators store hints, which are saved copies of writes to deliver later. Hints are kept for a limited time (the default window is three hours, check your version). If a node or region is away longer, hints stop and only repair can reconcile.

So monitor three things: the hint backlog, the dropped messages, and a canary value you write in one region and read in the other, to measure real lag.

I design screens to tolerate seconds of lag, and I do not promise "instant everywhere". Alert when the lag passes the number the product can accept.

"Can I get strong consistency across regions?"

Yes, but you pay for it on every request. Two ways to get it:

  1. QUORUM across both regions: with RF 3 in each of two datacentres there are 6 replicas, so QUORUM needs 4. Every read and write must reach the other region, so each request waits for the cross-region round trip, perhaps 100 ms or more.
  2. EACH_QUORUM for writes: a write must get a local quorum in every datacentre. It is strict, but if one region is down, the write fails.

Both trade the latency and availability you came for. Local reads and writes with a survivable region were the point of the design.

In the future, Accord in the 6.0 line may offer stronger guarantees, but it is only a preview in the alpha and off by default, so I do not plan around it.

Most teams accept eventual agreement between regions and avoid conflicts by giving each row a home region (Q93). I would use the strict levels only for the few records that need them.

"How does the driver pick the region?"

You tell the driver which datacentre is local, and it prefers nodes there. In the Java driver 4.x, basic.load-balancing-policy.local-datacenter is a required setting, and the datacentre name must match the one in the cluster's topology config (check the driver docs for current names).

With the default policy, the driver builds its query plan from local replicas first. It will not use the remote region unless you configure remote fallback, which I would avoid: a failover that quietly sends traffic across the ocean can raise latency and surprise the other region with load.

driver configruns offline
# illustrative
datastax-java-driver:
  basic.load-balancing-policy.local-datacenter: eu-west
  basic.request.consistency: LOCAL_QUORUM

I prefer to fail over at the DNS or load balancer layer, sending users to the other region's application servers, which then talk to their own local nodes. That keeps each request local.

"What does the relational world offer instead?"

Relational systems have two main routes, and both have costs. The first is logical replication between two PostgreSQL clusters, often with one writer, or two writers with conflict handling that you write yourself. Conflicts mean the same row changed in both places, and PostgreSQL does not pick a winner for you.

The second is a distributed SQL database, such as CockroachDB or Spanner-style systems, which gives strong consistency across regions. The price is that each write waits for a consensus between regions, so write latency is higher, and the system is a different product to run.

conflict ruleruns offline
illustrative
PostgreSQL logical replication: you decide the conflict rule in code or avoid two writers
Distributed SQL: consensus per write, cross-region latency, strong consistency
Cassandra: last-write-wins per cell, local latency, eventual agreement

Cassandra is the lightest option if you accept last-write-wins. I choose by the conflict rules the business can live with.

Q94 · Scenario. "At peak a node dies. What happens to traffic, and what do you do?"

Reveal answer

Strong answer With RF 3 and LOCAL_QUORUM, the cluster keeps serving. Each token range this node owned has two other copies, so reads and writes still reach two replicas and succeed.

The driver notices the dead node and stops routing to it. Other coordinators store hints for the dead node. Latency may rise a little because fewer nodes do the work.

You then replace the node (not just restart it if it was down longer than gc_grace_seconds), let it stream data from its neighbours, and run repair.

Picture it Six nodes, one gone.

The setup: Node 4 loses its disk at 20:15, the dinner peak.

Relational · PostgreSQL

A primary crash needs failover.

failover.sqlruns offline
-- primary dies
-- 1 detect (30 s)  2 promote standby
-- 3 repoint apps    4 old writes lost?
-- writes unavailable during failover

Cassandra · CQL

Peers keep serving; replace the node later.

replace.shruns offline
# nodes 1,2,3,5,6 still own all ranges
# on the new machine:
#   -Dcassandra.replace_address_first_boot=
#   10.0.0.4
$ nodetool status    # UN = up, DN = down
$ nodetool repair -pr   # after the node joins

The shift: A relational primary failing is an event to manage; a Cassandra node failing is a background change.

What you see: Status before and during.

status.txtruns offline
# illustrative output
$ nodetool status
UN 10.0.0.1  UN 10.0.0.2  UN 10.0.0.3
DN 10.0.0.4   <- down
UN 10.0.0.5  UN 10.0.0.6
LOCAL_QUORUM ok (2 of 3 for every range)

Why: No range lost more than one of its three replicas. Two simultaneous failures in the same range would make QUORUM unavailable for that range.

Land it I explain that RF 3 and LOCAL_QUORUM survive one node loss with no downtime, and that I replace the node and repair afterwards.

Likely follow-ups
"What if two nodes in the same rack die?"

It depends on whether the replicas share a rack, so the placement must be designed first. If two nodes die in the same rack, and Cassandra knows the racks, the damage is small. With NetworkTopologyStrategy and rack names set in the snitch configuration, Cassandra tries to put the three replicas of a token range in different racks.

So one rack going down removes at most one replica of each range. With RF 3 and LOCAL_QUORUM, two replicas remain, and reads and writes continue.

If the racks are not configured, all nodes look like one rack, and the three replicas of a range could sit in the same physical rack. Losing it would then make that data unavailable.

That is why I configure rack names to match failure domains, such as availability zones in a cloud region. I also use at least three racks for RF 3, so that each replica can live in its own rack.

"Should I restart the dead node?"

It depends on how long the node was down and whether its disk is intact. The deciding number is gc_grace_seconds, 10 days by default.

  1. Short outage, healthy disk: restart it. Coordinators kept hints for the writes it missed, usually for up to three hours (check the setting), and they replay on return. Then run a repair to catch what hints missed.
  2. Down for longer than hints last: it has missed writes that nobody stored. Repair is mandatory before it serves reads you trust.
  3. Down longer than gc_grace_seconds, or disk lost: do not just bring it back. Deletes it missed may already have been purged elsewhere, so it could revive deleted data (Q63). Replace the node and let it stream data from its neighbours.

Never bring a very old node back untouched. A rule I write in the runbook: past 10 days, rebuild, do not restart.

"What about the extra load on others?"

The surviving nodes take over the dead node's share, and the arithmetic is simple. Their share of the work rises by about 1/(N-1), where N is the original node count.

load after one node lossruns offline
illustrative: 6 nodes, evenly loaded
before: each node carries 1/6 = 16.7 percent of the traffic
after : each of 5 carries 1/5 = 20 percent, so 20 percent more than before
12 nodes: 1/11 vs 1/12, about 9 percent more

While the node is replaced, streaming data to the new one also uses disk and network on its neighbours, and repair adds more.

So plan capacity for a node loss at peak: keep headroom of at least 30 percent on CPU and disk throughput, so that losing one node still leaves each of the others below a safe level. A cluster that runs at 85 percent at peak is one failure from trouble. Bigger clusters absorb a loss more gently.

Capacity planning for one failure is cheap compared with the outage that follows a cluster running at its limit.

"Does the client see errors?"

A few requests that were in flight to the dead node when it failed will time out or get a connection error. After that the client stops seeing it. The driver notices the node is down, marks it, and routes new requests to the other replicas.

  1. In-flight requests: they fail within the request timeout. For idempotent requests, the driver's retry policy tries the next replica, and the user sees nothing.
  2. New requests: the token-aware policy picks among the live replicas, and LOCAL_QUORUM needs just 2 of 3.
  3. Non-idempotent writes: a counter update or a write not marked idempotent is not retried automatically, so the app must decide.

The number of failures is small, a few seconds' worth of requests to one of six nodes, perhaps 1 in 6 requests during the detection window (illustrative). That is why I mark statements idempotent where it is true.

After detection, latency rises a little because the others carry more load, as described above, but errors should return to near zero.

Q95 · Scenario. "Someone says 'we never run repair, it's too heavy'. What's your response?"

Reveal answer

Strong answer Repair is what guarantees replicas agree on everything that was missed: dropped mutations, hints that expired, and deletes. Without it, entries drift and zombie data returns (Q63).

Run repair on every table at least once within gc_grace_seconds, by splitting it into small sub-range repairs spread over days with a scheduler such as Cassandra Reaper, and use incremental repair where your version supports it.

Heavy repair means it has been neglected. Regular, small repairs cost much less than a huge one after a year.

Picture it A repair calendar.

The setup: 10-day gc_grace and a 6-node cluster. Repair each range every 7 days.

Relational · PostgreSQL

Postgres replicas follow one log, so no equivalent routine exists.

maintenance.sqlruns offline
-- routine instead: VACUUM, ANALYZE
-- REINDEX when bloated
-- pg_basebackup for new standbys

Cassandra · CQL

A scheduled maintenance cycle.

repair.shruns offline
$ nodetool repair -pr qb orders_by_customer
# -pr = only this node's primary ranges
# Reaper runs small slices on a calendar
# goal: every range repaired within 7 days
# (gc_grace_seconds is 10 days)

The shift: Relational maintenance is about space; Cassandra maintenance is about agreement between copies.

Make the invisible visible: The risk if skipped.

no-repair.txtruns offline
# illustrative output
day 0   node C misses a delete (down 2 h, hints dropped)
day 10  tombstone purged on A,B
day 40  C is read at LOCAL_ONE -> returns the deleted order
repair within 10 days would have copied the marker to C

Why: The cost of repair is predictable and small if you do it often. The cost of skipping it is silent data resurrection.

Land it I schedule continuous sub-range repair so each range is repaired inside gc_grace_seconds.

Likely follow-ups
"Full repair or incremental?"

Both modes exist, and in recent versions incremental repair is the default for the repair command (check your version's docs). It only compares data that is not yet marked repaired, so each run looks at a small, recent slice and finishes faster. Full repair compares everything, which is slower and heavier.

Incremental repair splits SSTables into a repaired set and an unrepaired set, and compaction keeps them apart. That needs care: if you skip incremental runs for a long time, the unrepaired set grows, and an interrupted run can leave data in an odd state.

Many teams use a scheduler such as Cassandra Reaper, which runs repair in small sub-ranges, tracks progress, and retries failures. Newer versions also have built-in repair scheduling work, so check the docs.

My rule: incremental repair on a regular schedule, finishing every range inside gc_grace_seconds (10 days), and an occasional full repair, for example after a disk failure or a bug.

"Does repair affect latency?"

Yes, repair uses disk and network, and it competes with normal traffic. That is why a plan matters.

  1. Small slices: repair a sub-range at a time, not the whole ring. A short run causes a short blip.
  2. Throttle: limit the stream throughput and the number of parallel repairs, and run in off-peak hours, such as 02:00 to 05:00 local time.
  3. Watch p99: compare read latency at the 99th percentile during a run against a normal day, and pause the scheduler if it climbs.

Repair builds a hash tree of each range on each replica, which costs disk reads, then streams only the differences. If replicas mostly agree, the traffic is small. If they have drifted for a year, the first repair can be heavy, as the answer says.

Small and frequent costs far less than rare and huge, so I schedule it continuously and keep the per-run effect low.

"What if the cluster is single-datacentre RF 1?"

With a single replica there is nothing to compare, so repair has no work. That is not a safe setup, just a different one: replication factor 1 means each piece of data lives on one node. If that node's disk fails, the data is gone, and while it is down, those partitions are unavailable.

It also changes what you rely on. Hints and read repair need other replicas, so none of them help. The cluster is only as available as its single worst node.

replication factorruns offline
-- illustrative
CREATE KEYSPACE quickbite WITH replication =
  {'class': 'NetworkTopologyStrategy', 'dc1': 3};   -- production: RF 3 per datacentre
-- RF 1 is acceptable for a laptop or a test cluster only

I accept RF 1 for local development and disposable test data. Production should be RF 3, with LOCAL_QUORUM, and then repair is the routine that keeps the three copies agreeing.

I also check the replication settings in every environment, because a staging cluster at RF 1 hides problems that production will show.

"Is there a managed alternative?"

Yes. Managed services run the cluster for you, and repair is one of the chores they take over. Amazon Keyspaces, for example, is a managed service that speaks CQL and does not ask you to run repair, compaction or node replacement, because it does not expose nodes at all.

The trade-offs are real, so compare them before choosing:

  1. What you gain: no repair scheduling, no node replacement, no JVM tuning, and capacity that scales by setting.
  2. What you give up: some CQL features and tuning knobs are limited or missing, you pay per request or per capacity, and you accept lock-in to the provider. Check the service's current feature list.
  3. Other options: managed Cassandra from several vendors, or DynamoDB, which uses the same query-first thinking with its own API.

The stack table in the chapter lays these side by side with a "switch when" for each.

For a team with no one to own operations, managed is often the better answer. The data model rules stay the same.

Drill · Migration, transactions and choosing

The closing questions: changing a live system, migrating, the next version, choosing a database and reviewing a schema.

Q96 · Scenario. "Product wants a new screen: 'orders by status across a restaurant'. The table is live with 2 billion rows. How do you add it?"

Reveal answer

Strong answer You cannot change the primary key of a table, and a plain ALTER TABLE cannot add a new access path. The Cassandra answer is a new table keyed for the new query, plus a backfill.

Steps: create the table, start writing to both old and new tables, backfill history in slices (by partition, throttled), verify counts, switch reads to the new table, then drop the old path if unused.

In relational land you would just create an index and wait. Here you build the new copy deliberately.

Picture it Add a table next to the old one.

The setup: Query: open orders of restaurant 3 by status for today.

Relational · PostgreSQL

Add an index; the engine builds it.

newidx.sqlruns offline
CREATE INDEX CONCURRENTLY orders_rest_status
  ON orders (restaurant_id, status);
-- table keeps serving during the build
-- planner starts using it

Cassandra · CQL

A new table and a backfill.

newtable.cqlruns offline
CREATE TABLE orders_by_rest_status (
  restaurant_id int, day date, status text,
  order_id timeuuid, total decimal,
  PRIMARY KEY ((restaurant_id, day),
    status, order_id)
);
-- 1 dual-write  2 backfill  3 switch reads

The shift: Relational schema change adds an index to the same data; Cassandra schema change adds a new copy of the data.

Make the invisible visible: The migration plan with checks.

backfill.txtruns offline
# illustrative output
step 1 create table, deploy dual-write           (day 0)
step 2 backfill by partition, 5,000 rows/s       (day 1-3)
step 3 compare counts per day, sample 1,000 rows
step 4 switch the screen to the new table        (day 4)
step 5 keep old table 7 days, then DROP

Why: Dual-write first means no gap while the history is copied. Verification before the switch means you can roll back by changing one read.

Land it I add a new table, dual-write, backfill in throttled slices, verify, switch reads, then drop the old one.

Likely follow-ups
"Can I ALTER the primary key?"

No. The primary key, meaning the partition key and the clustering columns, is fixed when the table is created. Cassandra stores rows by the token of the partition key and in clustering order on disk, so changing the key would mean rewriting and moving every row in the cluster. There is no command for that.

You can change other things:

  1. Allowed: add a regular column, drop a regular column, rename a clustering column in some cases, and change table options such as TTL, compaction and compression.
  2. Not allowed: change a column's place in the key, or change the clustering order.
alter limitsruns offline
-- illustrative
ALTER TABLE orders_by_customer ADD note text;      -- fine
ALTER TABLE orders_by_customer WITH default_time_to_live = 0;   -- fine
-- changing PRIMARY KEY: not possible, create a new table

In PostgreSQL you can add a primary key or build a new index, at the cost of a long lock or rewrite. Here, a new key means a new table, which is why I get the design right first.

"How do I backfill 2 billion rows safely?"

Carefully, in slices, with a rate limit and a checkpoint. A single SELECT * over 2 billion rows would overload the cluster and could not be resumed.

  1. Slice by token range: split the ring into many ranges and read each range from the old table with paging. Each slice is a bounded, independent job.
  2. Throttle: write to the new table at a limited rate, such as a few thousand rows per second, so live traffic is not hurt. Watch p99 latency and slow down if it rises.
  3. Checkpoint: store the last finished range in a small table, so a failure restarts from there, not from zero.
backfill timeruns offline
illustrative: 2,000,000,000 rows at 5,000 rows/s
2,000,000,000 / 5,000 = 400,000 s, about 4.6 days
at 20,000 rows/s: about 28 hours

A Spark job or a small custom program runs this well. I plan for days, not hours, and verify counts at the end.

"What about writes during the backfill?"

Dual-write covers new changes, and the backfill covers history. The danger is the overlap: the backfill reads an old row and writes it, while a live write has already put a newer value in the new table. A naive backfill could overwrite the newer value with a stale one.

The fix is to write the backfilled rows with USING TIMESTAMP set to the original write time of the row, not the current time. Cassandra keeps the cell with the highest timestamp, so the newer live write wins, whichever arrives first.

backfill writeruns offline
-- illustrative: WRITETIME(status) read from the old table
INSERT INTO orders_by_status (restaurant_id, status, order_id)
VALUES (?, ?, ?) USING TIMESTAMP 1764057600000000;

Last-write-wins then helps you. Read WRITETIME(col) from the old table for each column you copy. One caution: if a column was deleted in the live path, a tombstone has its own timestamp, so the same rule protects against bringing back deleted data.

"Does adding a column need a backfill?"

No, adding a regular column is cheap. Cassandra stores each row as a set of cells, and a row simply has no cell for a column it never wrote. The schema change is metadata only, so it finishes in moments, whatever the table size, with nothing rewritten.

Old rows read as null for the new column. Be careful with the word null: in a read it means "no value", and no tombstone exists for it. Only an explicit write of null creates one.

Fill the value in one of two ways. Write it as rows change, and treat null as "not yet set" in the app. Or run a background job that fills history in slices, as in the backfill above, if the screens need it everywhere.

add columnruns offline
-- illustrative
ALTER TABLE orders_by_id ADD delivery_note text;   -- instant
-- PostgreSQL: ADD COLUMN with no default is also fast; a volatile default may rewrite the table

Adding a column is cheap, and adding a key is not.

Q97 · Scenario. "We want to migrate our PostgreSQL orders system to Cassandra. How do you plan it?"

Reveal answer

Strong answer First ask whether to move at all (Q99). If the pain is read scale or write volume with known queries, plan a gradual move of the read models, not the transactional core.

Plan: list the queries, design the tables, build a pipeline from PostgreSQL (outbox or CDC with Debezium) into Cassandra, backfill, run both side by side, compare results, then move readers one screen at a time.

Keep PostgreSQL as the source of truth for writes that need transactions. The Cassandra tables become the serving layer.

Picture it Strangler-style migration.

The setup: Screen by screen, over three months (illustrative).

Relational · PostgreSQL

One schema, one codebase, JPA repositories.

jpa.javaruns offline
public interface OrderRepo
  extends JpaRepository<Order, Long> {
  List<Order> findByCustomerIdOrderByCreatedDesc(
    Long customerId, Pageable p);
}

Cassandra · CQL

A Cassandra repository per query table.

cassandra.javaruns offline
public interface OrdersByCustomerRepo
  extends CassandraRepository<OrderByCustomer,
      OrderByCustomerKey> {
  Slice<OrderByCustomer> findByKeyCustomerId(
      UUID customerId, Pageable p);
}

The shift: A relational repository serves many queries from one table; each Cassandra repository serves the one query its table was built for.

Make the invisible visible: A staged plan.

migrate.txtruns offline
# illustrative output
phase 1  outbox + Kafka + Cassandra read model, no traffic
phase 2  shadow reads: compare Cassandra vs PostgreSQL
phase 3  switch 'my orders' screen to Cassandra
phase 4  switch the restaurant live screen
phase 5  PostgreSQL keeps orders/payments (writes)

Why: Shadow reads prove the new tables give the same answers before any user depends on them.

Land it I move read models gradually behind an outbox, compare results in shadow, and keep transactions in PostgreSQL.

Likely follow-ups
"Should I dual-write from the app?"

I prefer the outbox, because an app-level dual write has a hole. The code writes to PostgreSQL, then writes to Cassandra. If the process crashes between the two, or the second write fails, the stores differ, and nothing records that fact.

The outbox closes the hole. The service writes the order and an event row in one PostgreSQL transaction, so they succeed or fail together. A relay publishes the event, and a consumer upserts into Cassandra. A failure at any step is retried from the log (Q92).

  1. If you must dual-write: make the second write an idempotent upsert, and retry it from a persisted queue, not from memory.
  2. Reconcile: add the nightly count and sample comparison, because dual writes will drift.

A dual write is acceptable for a short bridge, for example while an outbox is being built, or for data where a brief mismatch does not matter. For the migration of a real orders system, I would build the outbox first, since every later step depends on a reliable stream of changes.

"What do I do about joins in reports?"

Joins in reports belong somewhere else. Cassandra has no joins, and a report that joins orders, customers, restaurants and payments is a scan across many partitions, which it is not built for.

  1. Keep the reports on PostgreSQL: it remains the source of truth, so a read replica can serve finance and operations queries with full SQL.
  2. Or send the data to a warehouse: stream events from Kafka into a column store or a warehouse built for scans and joins, and run the BI tools there.
  3. Precompute what screens need: where a serving screen needs a joined view, such as "orders with restaurant name", store it denormalised in a Cassandra table.

Do not rebuild business intelligence inside Cassandra. People who try it end up with ALLOW FILTERING, full scans and timeouts.

The split is simple: Cassandra answers known, key-based questions at speed; PostgreSQL and the warehouse answer open questions. I confirm with the report owners which is which before moving anything.

"How do I handle the entity ids?"

Cassandra has no auto-increment, because two nodes would have to agree on the next number, which would need coordination on every insert. Instead you generate ids where you create the row.

The options:

  1. uuid: a random 128-bit id, generated in the app. Unique without coordination, but not ordered by time.
  2. timeuuid: a UUID that embeds a timestamp, so it sorts by time. Good as a clustering column, such as an order id inside a customer's partition.
  3. Keep PostgreSQL's bigint: if PostgreSQL stays the source of truth, copy its id into Cassandra as a bigint key. The id is then the same in both stores, which makes comparison easy.

The last option is the simplest in a gradual migration, because the outbox events already carry the id.

Map the ids in one place, so nobody invents a second scheme. Also remember that Cassandra has no UNIQUE constraint, so uniqueness comes from the key itself or from a lightweight transaction on a lookup table.

"What is the biggest risk?"

The biggest risk is underestimating how many tables the queries need and how many writes each business event causes. Each access pattern becomes its own table, and each event writes to all of them. That is write amplification.

write amplificationruns offline
illustrative: 5 tables per order, 2,000 orders/s at peak
5 tables x 2,000 = 10,000 row writes/s, before replication
x RF 3 = 30,000 replica writes/s across the cluster
status changes: 3 per order x 3 tables = 9 more writes per order

A relational order writes a few rows in one transaction. The Cassandra design might write ten times as many rows, and the sizing, the batches and the repair load all follow from that.

Before starting, I list every screen and query, count the tables, and count the writes per business event. If the count surprises the team, that is the moment to find out, not after the first month of production.

If the number looks too large, that is a reason to cut screens or merge queries, not to skip the sum.

Q98. "What is Accord in Cassandra 6.0, and does it change how you model data?"

Reveal answer

Strong answer Accord is the new transaction protocol in the Cassandra 6.0 line. It aims to give general-purpose ACID transactions across partitions, written as BEGIN TRANSACTION ... COMMIT TRANSACTION, instead of today's single-partition LWT.

As of this writing 6.0 is only an alpha (6.0-alpha1, March 2026), and Accord is off by default and enabled per table. It is a preview, not for production.

It would let some multi-table invariants (stock plus order) live in Cassandra, but it does not remove query-first modelling. You still design one table per question.

Picture it Today versus the preview.

The setup: A transfer between two partitions.

Relational · PostgreSQL

Standard SQL transaction.

txn.sqlruns offline
BEGIN;
UPDATE accounts SET bal = bal - 50 WHERE id = 1;
UPDATE accounts SET bal = bal + 50 WHERE id = 2;
COMMIT;

Cassandra · CQL

Preview syntax; enabled per table, not in 5.0.

accord.cqlruns offline
-- Cassandra 6.0 alpha (preview only)
BEGIN TRANSACTION
  UPDATE accounts SET bal = bal - 50 WHERE id = 1;
  UPDATE accounts SET bal = bal + 50 WHERE id = 2;
COMMIT TRANSACTION;

The shift: Relational databases always had this; Cassandra is adding it, but the modelling method stays.

Make the invisible visible: What changes and what stays.

accord-vs.txtruns offline
# illustrative output
feature                5.0 (today)       6.0 alpha (preview)
single-partition LWT   yes (Paxos)       yes
multi-partition ACID   no                Accord (per table)
query-first modelling  required          still required
production use        yes               no, preview

Why: Transactions fix correctness across partitions. They do not make a wide partition cheap, or a join exist.

Land it I teach and design for 5.0, and mention Accord as a coming option I would test, not rely on.

Likely follow-ups
"Does Accord replace LWT?"

Accord is intended to be the general-purpose successor to lightweight transactions, but it is not a drop-in replacement today. LWT uses the Paxos protocol and works inside a single partition. Accord aims to give ACID transactions across partitions.

The two will probably live side by side for a while. Today's LWT, with IF NOT EXISTS or IF col = x, stays for single-partition compare-and-set, and I would not expect old code to change its behaviour overnight. Moving from LWT to Accord may be a deliberate migration, per table, since Accord is enabled per table and is off by default in the alpha.

LWT vs Accordruns offline
-- illustrative
UPDATE stock SET qty = 4 WHERE item = 'pizza' IF qty = 5;     -- LWT, one partition
BEGIN TRANSACTION ... COMMIT TRANSACTION;                    -- Accord, several partitions (6.0 alpha)

Check the release notes when 6.0 reaches general availability. Do not assume the migration is automatic.

"Would you use it for payments?"

Not until it is released, has run in production elsewhere, and my team has load-tested and failure-tested it with our own workload. Payments are the worst place to be an early adopter, because a bug there costs money and trust.

My checklist before I would consider it:

  1. General availability: a stable 6.x release, not an alpha, with release notes that call the feature production-ready.
  2. Our tests: concurrent transfers, node failures in the middle of a transaction, network partitions, and checks that total money never changes.
  3. The numbers: latency and throughput of Accord transactions on our hardware, which will cost more than single-partition writes.

For now, payments and stock stay in PostgreSQL, with Cassandra holding read models (Q91). That position is easy to defend: it uses the tool whose transaction guarantees are mature and well known.

I would be glad to try Accord on a low-risk table first, in a staging environment.

"What other 6.0 changes matter?"

Transactional Cluster Metadata, known as CEP-21, is the other big change in the 6.0 line. It changes how the cluster agrees on its own structure: schema changes and topology changes, such as nodes joining or leaving, go through a consistent log, instead of spreading by gossip and hoping every node catches up.

The practical benefit is operational. Today, a schema change can briefly leave nodes disagreeing about a table, and a bootstrap can race with another. With a consistent metadata log, there is one agreed order of changes, so such races should go away and operations should be safer and easier to reason about.

It does not change how you model data. You still design a table per query.

It is also an alpha feature set, and details may change before release. I would read the release notes and test it in staging before relying on any behaviour, and I would mention it in an interview as an operations improvement, not as a modelling one.

"How do you stay current?"

I read the sources that change, not my memory. The release notes of each Cassandra version, the project's blog, and the CEP list (Cassandra Enhancement Proposals) show what is planned and what has shipped.

  1. Stamp the facts: dates and versions in this chapter are stamped November 2026: Cassandra 5.0 is the current stable line, and 6.0 is alpha only.
  2. Check before relying: before I recommend a feature, I check its status in the docs for my exact version, since materialized views, SAI behaviour and repair defaults have all changed between releases.
  3. Test on a copy: I try new features on a staging cluster with realistic data.

I also keep upgrade notes for my own cluster: a rolling upgrade, one node at a time, with a rollback plan.

In an interview, saying "this is true as of 5.0, and I would verify it for the version in front of me" is a better answer than a confident claim that may be a year old.

Q99 · Design. "When would you choose Cassandra over PostgreSQL, ScyllaDB, DynamoDB or MongoDB?"

Reveal answer

Strong answer Choose Cassandra when you need very high write throughput, data that spans datacentres, no single point of failure, and your queries are known and key-based. Think messages, events, time series and activity feeds.

Choose PostgreSQL when you need joins, ad-hoc queries, transactions and a data size one node (or Citus) can handle. This is most systems.

ScyllaDB is CQL-compatible with a C++ engine, good when you want the Cassandra model with fewer nodes. DynamoDB uses the same query-first idea as a managed service. MongoDB suits flexible documents with richer queries.

Picture it Pick by the questions, not the brand.

The setup: A product with 2 million writes per second and four known queries.

Relational · PostgreSQL

The ER model fits when questions change often.

adhoc.sqlruns offline
SELECT r.name, count(*)
  FROM orders o JOIN restaurants r
    ON r.id = o.restaurant_id
 WHERE o.created > now() - interval '7 days'
 GROUP BY r.name ORDER BY 2 DESC;

Cassandra · CQL

Fits when questions are fixed and the scale is large.

fixed.cqlruns offline
-- the four known queries:
-- Q1 orders by customer
-- Q2 live orders by restaurant today
-- Q3 timeline of one order
-- Q4 rider location now
-- each is one partition read

The shift: Choose a relational engine for flexibility; choose Cassandra for predictable speed at scale on known queries.

Make the invisible visible: The stack table in words.

choose.txtruns offline
# illustrative output
option          pick it when                  catch
PostgreSQL      joins, ad hoc, transactions   one writer scale
Cassandra       huge writes, multi-DC, known  no joins, no ACID*
ScyllaDB        Cassandra model, fewer nodes  vendor/licence choice
DynamoDB        managed, AWS-only             single-table design
MongoDB         flexible documents            different consistency
* 6.0 Accord preview

Why: Every option trades flexibility for scale somewhere. Say which of your requirements is hardest and choose for that one.

Land it I choose by query shape and scale, and I say plainly that most systems should start on PostgreSQL.

Likely follow-ups
"When do you switch from PostgreSQL to Cassandra?"

I switch when measured limits are reached and the queries are known, not when a blog post says so. PostgreSQL goes a long way: one well-tuned primary on good hardware can handle a lot of writes, and read replicas, partitioning and Citus extend it further.

  1. Write rate: one primary cannot absorb the writes even after tuning, batching, partitioning and sharding with Citus.
  2. Active-active regions: users in several regions must write locally, and you can live with last-write-wins conflicts.
  3. Known queries: you can list the access patterns and none needs joins or ad-hoc filters.

All three together are a strong signal. One alone usually is not.

Even then I would move gradually: keep PostgreSQL for the transactional core and move high-volume read models, such as timelines or events, to Cassandra through an outbox (Q97).

The cost of switching is high: denormalised tables, write amplification, repair, and a team that must learn new habits. I would be sure that the problem is real first.

"Why ScyllaDB over Cassandra?"

ScyllaDB speaks the same CQL and the same data model as Cassandra, but it is rewritten in C++ with a design that pins work to CPU cores and avoids the JVM. The usual claim is that it needs fewer machines for the same load and has steadier latency, with no garbage-collection pauses.

I would not take that on trust. The gain depends on workload and hardware, so test your own queries on both, with your data sizes and your failure drills.

  1. Licence and support: check the current licence terms and what is in the open-source and commercial editions.
  2. Tooling: compare drivers, operations tools, monitoring and your team's experience.
  3. Feature gaps: check feature parity for the things you use, such as SAI-style indexes or the 5.0 vector type, since the two projects evolve separately.

The data model lessons in this chapter apply to both. I pick Scylla when cost per node matters and a test shows it fits.

"Why not DynamoDB?"

DynamoDB is a good choice if you are fully committed to AWS and want no operations at all. It uses the same query-first thinking: you choose a partition key and a sort key, and design around known access patterns. Its common style is single-table design, where several entity types share one table, distinguished by key prefixes.

same idea, two APIsruns offline
illustrative
Cassandra : PRIMARY KEY ((customer_id), placed_at, order_id)   -- CQL, you run the cluster
DynamoDB  : PK = CUSTOMER#7, SK = ORDER#2026-11-25#42           -- AWS API, fully managed

The costs are different. You pay per request or for provisioned capacity, and you accept vendor lock-in, so moving away later means a rewrite. Some limits, such as the item size, are fixed by the service (check the current limits).

If you want CQL without running nodes, Amazon Keyspaces is the CQL-compatible managed option. I choose DynamoDB when the team is AWS-only and wants zero operations.

"Is Cassandra good for analytics?"

No. Cassandra is a serving store: it answers known questions about one partition at speed. Analytics asks open questions over many partitions, such as "average basket by city by week", and that means scanning huge amounts of data, which Cassandra handles poorly and which would hurt your live traffic.

  1. Serve in Cassandra: the screens and APIs the users touch.
  2. Export for analysis: stream events from Kafka, or take snapshots, into a warehouse or a column store, where scans over many rows are the normal case.
  3. Precompute small answers: for a dashboard that must live in Cassandra, a stream job can write rollup tables (Q84).

Spark can read Cassandra for batch work, but I run it against a copy or a dedicated analytics datacentre, so it does not compete with the serving load.

Say this plainly in an interview. It shows that you have run it and know where it stops, which is as valuable as knowing what it does well.

Q100 · Design. "Review time: a junior shows a Cassandra schema. What is your checklist for finding the problems?"

Reveal answer

Strong answer I check seven things in order. (1) Is every table named after a query? (2) Does every query give the full partition key with equality? (3) Is every partition bounded, with a number worked out? (4) Is the clustering order the one the screen wants?

(5) Are there joins, ALLOW FILTERING, unbounded IN or secondary indexes without a partition key? (6) How are the copies kept in sync, and what are the consistency levels? (7) How do deletes, TTLs and tombstones behave, and is repair planned?

Each failure maps to a section in this chapter, so I can name the fix and not only the fault.

Picture it Run the checklist on one schema.

The setup: A junior's table orders (id uuid PRIMARY KEY, customer_id uuid, status text) with a secondary index on customer_id.

Relational · PostgreSQL

A normalised table is fine relationally.

review.sqlruns offline
CREATE TABLE orders (
  id uuid PRIMARY KEY, customer_id uuid,
  status text);
CREATE INDEX ON orders (customer_id);
-- query by customer uses the index

Cassandra · CQL

Same shape fails the checklist.

review.cqlruns offline
-- ❌ TRAP: no query-shaped key
CREATE TABLE orders (id uuid PRIMARY KEY, ...);
CREATE INDEX ON orders (customer_id);
-- ✅ one table per question
CREATE TABLE orders_by_customer (...
  PRIMARY KEY (customer_id, created, id));

The shift: A relational reviewer asks about normal form; a Cassandra reviewer asks which query each table answers.

Make the invisible visible: The review result.

review.txtruns offline
# illustrative output
1 table named after a query?      FAIL  (orders)
2 full partition key in WHERE?    FAIL  (by customer: index)
3 partition size worked out?      n/a
4 clustering order for the screen? FAIL (no created)
5 anti-patterns?                  FAIL  (2i, no key)
fix: orders_by_customer (customer_id, created desc, id)

Why: The failures are visible in minutes with the list. The fix is one new table, not a bigger cluster.

Land it I review by walking seven questions from query to repair, and I tie each finding to its fix.

Likely follow-ups
"What is the most common mistake?"

The most common mistake is copying the relational schema one to one: a table per entity, foreign keys turned into plain columns, and then secondary indexes or ALLOW FILTERING to make the queries work. It looks familiar, which is why it is so common, and it fails at scale.

The symptoms are easy to spot in a review:

  1. Tables named after things: orders, customers, items, not after queries such as orders_by_customer.
  2. Queries that need many tables: the app joins in code, in loops of single-key reads.
  3. Indexes without a partition key: a query that touches every node.

The fix is to throw the table list away and start from the queries (Q1 to Q10 in the first drill): list every screen and API call, write each as a WHERE clause, and give each its own table.

I look for this first because it is the root of most other problems. Wide partitions, timeouts and filtering are usually its consequences.

"What do you ask about sizes?"

I ask for numbers, not adjectives. "Small partitions" is not an answer. Three numbers per table:

  1. Rows per partition: the average and the maximum for one partition key value. For a time bucket, rows per bucket at peak.
  2. Bytes per row: add up the column sizes, including text and collections, and add some overhead.
  3. The largest key in practice: the busiest customer, restaurant or sensor, not the average one.
measure sizesruns offline
# illustrative: ask the cluster for the real p99 and max
nodetool tablehistograms quickbite orders_by_restaurant_day
# read "Partition Size" and "Cell Count" at the 99th percentile and Max

The guideline is under about 100 MB and 100,000 rows per partition. If the author has no measured figure, the size is a guess, and I ask them to compute it from the real rates before the review ends. A design with unmeasured sizes is not ready.

"What do you ask about writes?"

I ask about write amplification and the failure rules. Denormalised designs write one business event to several tables, so the cost of a write is the number of tables, not one.

  1. How many writes per event: an order that updates five tables is five writes, times the replication factor of 3.
  2. How the copies stay in step: a logged batch, an outbox, or a reconciliation job. Which one, and what happens if it fails halfway?
  3. Consistency and retries: the level for each read and write, whether the writes are idempotent, and the retry rule.

I also ask about batch sizes, since the warning is at 5 KiB and the failure at 50 KiB, and whether any batch spans many partitions.

This is easy to forget, because the schema looks fine on paper: five small tables. The load only shows up when someone multiplies. A junior who has not done that sum has not finished the design.

"How do you end the review?"

I end by getting the design onto one page: an access-pattern list with one row per table. Each row has the query, the table name, the partition key, the clustering columns and order, the bucket, the expected partition size and the TTL.

design pageruns offline
illustrative
Q3  orders_by_customer  PK ((customer_id), placed_at DESC, order_id)  bucket none  ~40 rows/cust  TTL none
Q7  rider_track         PK ((rider_id, day), at)  bucket day  ~28,800 rows (about 1.4 MB)  TTL 7 days

If the author cannot fill a row, that table is not designed yet. The empty cell tells us exactly what to work out next: usually a size, a bucket, or a delete rule.

The page then becomes the design document. It is short, reviewable and easy to keep in step with the CQL, and it gives future readers the reason each table exists. I also add the consistency level and the repair plan at the bottom, so the checklist, from query to repair, is visibly complete.

11 · RecapWhat You Can Do Now

  • You can explain the core flip in one breath: relational models the data and asks any question later, Cassandra lists the questions first and builds one table per question
  • You can design a primary key from a query: partition key for where it lives, clustering columns for how it is sorted, and a bucket so each partition stays small
  • You can translate each relational tool (JOIN, foreign key, UNIQUE, GROUP BY, OFFSET, secondary index) into its Cassandra replacement and name its trap
  • You can choose a consistency level pair with R + W above RF, and say what LOCAL_QUORUM, hints, read repair and repair each do
  • You can explain tombstones, gc_grace_seconds, TTL and why a queue in one partition fails
  • You can read nodetool numbers (SSTables per read, partition size, pending compactions) and find a wide or hot partition
  • You can design chat, order timelines, sensor data, feeds and live locations with partition-size arithmetic
  • You can say where Cassandra is the wrong tool, and keep money and stock in PostgreSQL with an outbox to Cassandra read models
🧠 Flex your memory

Close the page and write down, from memory: the seven questions you ask when turning a relational schema into Cassandra tables. Then take any table from your own work and answer the first three for it. Finally, reach back to the outbox in the Kafka chapter: why is an outbox with idempotent upserts safer than writing to PostgreSQL and Cassandra from the same request?

12 · Mental mapThe Mental Map on One Page

Everything in this chapter as one picture and seven short tables. Each row names the relational habit, the Cassandra replacement, and why the thinking changes. Click an id to jump to its full breakdown.

Same app, two ways of thinkingRelational: model data, ask laterCassandra: list questions, build tablesFind a rowB-tree index, then heap pagebecomesFind a rowtoken, then partition, rows in orderPrimary keyone column names one rowbecomesPrimary keypartition key + clustering = designDesign orderentities, normalise, ask laterbecomesDesign orderqueries first, one table eachRelationsJOIN and foreign keysbecomesRelationsdenormalise, write N copiesFiltersindex + planner pick a pathbecomesFilterskey matches WHERE; SAI on topConsistencyACID, UNIQUE, locksbecomesConsistencylevel per request, batch, LWTDelete, expireDELETE, vacuum, cronbecomesDelete, expiretombstone, gc_grace, TTL, bucketsEvery read is: go to one partition, read rows already sortedThe price: the same fact is written into several tables
Fig. 18.30 — The whole mental map in seven rows: each relational habit on the left becomes the Cassandra replacement on the right, and every read ends as one partition.

02 · How each database stores and finds a row

3 translations.
Relational habitCassandra replacementWhy the thinking changes
The primary key is one column that names a row.
map-primary-key
The primary key is partition key plus clustering columns, and it is the whole design.The partition key decides which nodes hold the row and the clustering columns decide the order inside it.
INSERT fails if the key exists; UPDATE needs the row to exist.
map-upsert
Every write is an upsert; last timestamp wins; there is no read before write.Replicas cannot cooperate on a check cheaply, so writes are plain appends.
A B-tree index leads to a heap page.
map-row-lookup
A token leads to replicas, then memtable and SSTables are merged.The data is spread by hash, so a lookup by key must name the partition.

03 · The primary key is the whole design

3 translations.
Relational habitCassandra replacementWhy the thinking changes
Any column can appear in WHERE; the planner finds a path.
map-where-clause
Equality on every partition key column, then a clustering prefix.Only a key-shaped question is a cheap question.
ORDER BY sorts at read time.
map-order-by
Clustering order stores rows already sorted.Sorting is moved from read time to write time.
A big table is sliced by an index.
map-bucketing
A time or hash bucket in the partition key keeps each partition small.One partition is one unit; it must stay small and bounded.

04 · The modelling method

3 translations.
Relational habitCassandra replacementWhy the thinking changes
Model the entities, then ask any question later.
map-design-order
List the questions first, then build one table per question.The queries are part of the schema, not an afterthought.
Normalise so each fact is stored once.
map-normalise
Denormalise on purpose and write each fact into several tables.Storage is cheap and reads must touch one partition.
An ERD is the main design drawing.
map-chebotko
A Chebotko diagram shows tables, keys and the query each serves.The picture must show access paths, not just entities.

05 · Translating every relational tool

9 translations.
Relational habitCassandra replacementWhy the thinking changes
JOIN tables at read time.
map-join
Copy the joined columns into one table at write time.Joins across nodes are too slow, so the join happens ahead of time.
A child table with a foreign key.
map-one-to-many
A table partitioned by the parent key, children as clustered rows.The parent key puts all children in one partition.
A junction table and two joins.
map-many-to-many
Two tables, one per direction, both written together.Each direction is a different question and gets its own table.
A normalised child table.
map-collections
A collection or user-defined type inside the row.Small, bounded lists can sit in the row and read together.
The database enforces references.
map-foreign-key
The application keeps ids consistent; there is no constraint.No cross-partition check exists, so writers take over the job.
A UNIQUE constraint.
map-unique
A claim table with IF NOT EXISTS (lightweight transaction).Uniqueness needs agreement, and Paxos gives it for one partition.
COUNT, SUM, GROUP BY at read time.
map-aggregate
Precomputed rollup tables or counters, maintained at write time.A scan across partitions does not scale.
LIMIT with OFFSET.
map-pagination
The driver's paging state as a cursor.Skipping rows still reads them, so use a bookmark.
CREATE INDEX on any column.
map-secondary-index
A table for the query; SAI only as a filter inside a partition key.Indexes are per node, so an index query without a key asks every node.

06 · Transactions, consistency and deletes

5 translations.
Relational habitCassandra replacementWhy the thinking changes
BEGIN ... COMMIT across tables and rows.
map-transaction
A logged batch to keep copies aligned; LWT for compare-and-set in one partition.Cross-partition atomic transactions are not in 5.0 (Accord is a 6.0 preview).
One primary, one truth, plus replica lag.
map-consistency
Per-request consistency level; R + W above RF for strong reads.With many equal replicas you choose how many must agree.
DELETE removes a row; vacuum cleans.
map-delete
A tombstone marker lives for gc_grace_seconds and needs repair.Replicas must all learn about a delete before the marker goes.
A cron job deletes old rows.
map-ttl
TTL on the write or default_time_to_live on the table.Expiry becomes a property of the data.
UPDATE x = x + 1 under a lock.
map-counter
A counter table, approximate; or event rows counted later.Increments are not idempotent, so retries can double-count.

08 · Running it and choosing it

2 translations.
Relational habitCassandra replacementWhy the thinking changes
Scale up the primary, add read replicas.
map-scaling
Add nodes; each takes a share of the token ring; RF and datacentres.Capacity grows by adding equal peers, not by a bigger single node.
ALTER TABLE and CREATE INDEX on the same data.
map-schema-change
A new table for the new query, dual-write and backfill.The key cannot change, so a new access path is a new copy.

The decision path: seven questions

Ask these in order whenever you turn a relational schema into Cassandra tables.

  1. What are the queries? List every screen and API call, with its filters, sort order and expected size. No query list, no design.
  2. What is the partition key for each? Choose the columns the query always gives with equality, so one request goes to one partition.
  3. What is the clustering order? Store rows in the order the screen wants them, so the read is a slice with no sorting.
  4. How big does one partition get? Work out rows times bytes. If it grows without bound, add a time or hash bucket to the key.
  5. What gets copied, and how are the copies kept in step? Name each table written per business event, then use a logged batch, an outbox or an event stream.
  6. Which consistency level pair, and what about conflicts? Pick reads and writes so R + W exceeds RF, and decide who wins when two writers collide.
  7. How does data leave, and who repairs it? Choose TTL or whole-partition deletes, avoid queue patterns, and plan repair inside gc_grace_seconds.