Video in progress

Strong Middle 🏗️ System design

What do the N, W and R parameters mean in leaderless replication, and what does the W + R > N condition guarantee?

N is the number of copies of each key, W is the number of copies that must confirm a write before it's called successful, R is the number of copies that must answer a read. If W + R > N, the read and write sets overlap in at least one copy, and the read sees the last confirmed write.

📖 Answer

An example: N = 3. The key is stored on nodes A, B and C.

  • W = 2, R = 2 → 2 + 2 > 3. The write landed on A and B. Even if the read gets answers from B and C, B has the new value. The newest is chosen by version (a timestamp or vector clock).
  • W = 1, R = 1 → the overlap isn't guaranteed. Very fast, but you can read a stale value.
  • W = 3, R = 1 → reads are fast, but if one node goes down, writes stop.

In Cassandra this is chosen per query through the QUORUM, ONE and ALL consistency levels:

-- cqlsh
CONSISTENCY QUORUM;
SELECT balance FROM accounts WHERE id = 42;

But W + R > N doesn't mean "strong consistency". There are subtle cases:

  • a write reached 1 node, failed to reach 2 and returned an error — the write is left "half done", and later reads see it sometimes and sometimes don't;
  • if two clients write at the same time, the "last write wins" rule gives unexpected results because of clock differences;
  • with sloppy quorum and hinted handoff, a write can temporarily land on a "foreign" node.

To close the differences between copies, read repair (updating a stale copy on read) and anti-entropy (comparing in the background with Merkle trees) are used.

In practice QUORUM/QUORUM is a good balance for most: reads and writes keep working even if one node goes down.