Design a key-value store: partitioning, replication, consistency
Day 6 told you which server owns a key. This lesson keeps three copies of it instead of one — and then has to answer the question that creates: when three machines hold a value and the network splits them, which one is telling the truth?
N = 3Replicas per key. The standard starting point (§3)
W + R > NThe one inequality that guarantees a read sees the latest write (§4)
< 10 KBMax size of one value. Small enough that the interesting problems are not about size
log nComparisons to find a divergent range with a Merkle tree (§6)
Key points
Once data lives on more than one machine, a network partition forces a choice. CP refuses writes to stay correct; AP keeps serving and reconciles later. You cannot have both, and pretending otherwise is the classic interview failure.
W + R > N forces the write set and the read set to overlap on at least one node, and that node has the newest value. Every consistency level you have seen in Cassandra or DynamoDB is a choice of W and R against this one inequality.
Failures are routine, not exceptional. The design assumes nodes die mid-write: gossip detects it, sloppy quorum and hinted handoff cover short outages, Merkle trees resync long ones.
Outcomes
01State the CAP trade-off with a concrete three-replica scenario, and pick a side for a given product.
02Place replicas on a hash ring and say why they must be in distinct failure domains.
03Size N, W and R for a stated requirement and prove the overlap.
04Describe detection, temporary cover, and permanent repair as three separate mechanisms.
01
What we are building, and why one machine will not do
The interface is two operations: put(key, value) and get(key), with values under 10 KB. On one machine that is a hash table, and you are done in an afternoon. The design problem begins when the data no longer fits, because every answer to “use more machines” creates a new question:
Which machine holds this key?
That is partitioning — the hash ring from Day 6.
What happens when that machine dies?
That is replication. Keep N copies.
What happens when the copies disagree?
That is consistency, and it is the hard one. The rest of this lesson.
CAP: the choice you make before writing any code
Three properties, and a network partition lets you keep only two:
Consistency — every read returns the most recent write, or an error.
Availability — every request gets a non-error response, even if it is stale.
Partition tolerance — the system keeps working when messages between nodes are lost.
Partitions are not optional. Cables get cut, switches reboot, data centres lose links. So P is not a choice — the real decision is what you do during a partition, and that is a choice between C and A.
How to read: Three replicas, and the network splits n3 away from the others. The same event, two different policies, two different outcomes.
Amazon's shopping cart is the canonical AP case: refusing an “add to cart” costs real money, and two carts merging later is a solvable problem. A bank ledger is the canonical CP case for the opposite reason.
CAP is incomplete: PACELC
CAP only describes behaviour during a partition — which is rare. It says nothing about the other 99.9% of the time, and that silence is where most real design effort goes. PACELC fills it:
if Partition → choose Availability or Consistency · Else → choose Latency or Consistency
The second half is the useful half. Even with a perfectly healthy network, keeping replicas in agreement costs round trips — so every store is also making a latency-versus-consistency choice during normal operation, every single day.
System
Classification
Meaning
DynamoDB, Cassandra
PA / EL
Stay available under partition; prefer low latency normally. Both are tuneable per request, which is why quorum settings exist.
MongoDB, HBase
PC / EC
Refuse rather than diverge, and pay coordination latency even when healthy.
Google Spanner
PC / EC
Consistency at both ends — bought with atomic clocks and GPS, so the uncertainty window is small enough to simply wait it out on every commit. The latency is real; they pay it deliberately.
Saying “it's AP” describes a store's behaviour on its worst day. Saying “PA/EL” describes what it costs you on an ordinary one.
The consistency ladder
“Strong” and “eventual” are the two ends of a ladder with useful rungs in between. The skill being tested is picking the weakest model that is still correct for the feature — because every rung up costs coordination.
Model
Guarantee
Cost
strongest
Linearizable
Every operation appears to happen instantaneously, in real-time order. The system behaves as if there were one copy.
Coordination on every operation. Unavailable during a partition by definition.
Sequential
All nodes see operations in the same order — but that order need not match real time.
Still requires global agreement on ordering.
Causal
If A caused B, everyone sees A before B. Unrelated operations may be seen in any order.
Metadata to track causality, but no global coordination. The sweet spot for social and messaging features: you never see a reply before its parent.
Session guarantees
Read-your-writes, monotonic reads — promises to one client, not globally.
Almost free: sticky routing or a version token the client carries.
weakest
Eventual
Replicas converge if writes stop. No promise about when, or what you see meanwhile.
Nothing. And correspondingly, it promises nothing.
What to say out loud
“A like counter is fine eventual — nobody can tell. The comment thread needs causal, or people see replies before the posts they answer. The account balance needs linearizable, and I'll pay for that on one small set of operations rather than making the whole store strong.” Per-operation consistency, justified per feature, is the answer — which is exactly why real stores expose it as a per-request setting rather than a global mode.
Interview line
“Partitions aren't optional, so I'm really choosing between C and A during one. For this product I'd pick availability — a stale cart beats a failed add — which means I need a conflict resolution story, and I'd use last-write-wins with a caveat, or vector clocks if I can't tolerate silently dropping a write.” State the choice early, then make every later decision consistent with it.
02
Partition and replicate
Servers go on the Day 6 ring. A key hashes onto the ring, walks clockwise to its owner — and then keeps walking, copying to the next N−1 distinct servers. With N = 3, key0 lives on s1, s2 and s3.
How to read: One clockwise walk does both jobs. The first server met is the owner; the walk simply does not stop there.
Replication reuses the ring's property: adding or removing a server shifts replica sets only for the keys in one arc, not for everything.
Interview tip
More virtual nodes per server evens out the slices, and larger machines can be given more of them to earn a bigger share. This is why Dynamo and Cassandra run heterogeneous hardware comfortably — capacity is a dial, not a redesign.
03
The read and write paths
Any node can take a request. The node that receives it becomes the coordinator for that request: it works out which N nodes own the key, talks to them, and answers the client. There is no special master — which is why losing any one node is survivable.
Write arrives at a coordinator
It hashes the key, finds the N replicas, and forwards the write to all of them.
It waits for W acknowledgements
Not all N — just W. As soon as W replicas confirm, it returns success to the client. The remaining replicas are still being written in the background.
Read arrives at a coordinator
Same hashing, same N replicas, request sent to all of them.
It waits for R responses
If they disagree, it returns the newest and (in most implementations) quietly repairs the stale replicas in the background — read repair.
Durability on each individual node is the unglamorous part: an append-only commit log on disk so an in-flight write survives a crash, a memtable in memory for recent writes, and immutable sorted files (SSTables) on disk. A Bloom filter per file keeps reads from touching files that cannot contain the key.
04
Quorums: the one inequality
N is how many copies exist. W is how many must acknowledge a write before you call it done. R is how many must answer a read before you return it. These are per-request knobs, not fixed properties of the database — and the relationship between them is the whole story.
How to read: The green bracket is the set of nodes the write waited for. The blue bracket is the set the read waited for. The question is whether those two sets are forced to share a node.
This is the entire theory of tuneable consistency. Everything below is just picking numbers against it.
Try it: drag N, W and R. Green nodes are in both sets — the overlap that makes a read see the newest write. Watch what happens to fault tolerance when you push W all the way to N.
read sees latest write
guaranteed
writes survive
1 node
down, before writes fail
reads survive
1 node
down, before reads fail
Every consistency level you have met in Cassandra or DynamoDB — ONE, QUORUM, ALL, LOCAL_QUORUM — is a named position on these three sliders.
Setting
W + R
Behaviour
Use when
W=1, R=1
2 ≤ 3
Fastest possible both ways. No overlap guarantee — reads may be stale
Metrics, logs, anything where a lost or late value costs nothing
W=1, R=N
4 > 3
Very fast writes, slow reads. Strong
Write-heavy with rare, important reads
W=N, R=1
4 > 3
Slow writes, very fast reads. Strong
Read-heavy with rare writes — a config store
W=2, R=2
4 > 3
Balanced and strong. Survives one node down on each path
The default. Pick this unless you have a reason
Note what W=N costs you beyond latency: if any single replica is down, writes fail entirely. W=2 of 3 keeps working through one failure, which is usually the point of having three copies.
GotchaW + R > N gives you read-after-write consistency, not serialisability. Two clients writing the same key concurrently can both satisfy the quorum and still produce a conflict — the overlap guarantees a reader sees a latest write, not that there was only one. That is what §5 is for.
05
When copies disagree: resolving conflicts
Under AP, or under concurrent writes, two replicas can hold different values with no inherent ordering between them. Somebody has to choose.
Option A
Last write wins (LWW)
Attach a timestamp to every write; the highest timestamp wins.
Trivial to implement and requires no client involvement.
It silently discards data. Two concurrent writes, one vanishes with no record that it existed.
Depends on clocks agreeing across machines, which they do not (see Day 8).
Option B
Vector clocks
Each value carries a list of [node, counter] pairs recording who updated it and how many times.
Comparing two lists tells you whether one descends from the other, or whether they genuinely conflict.
Real conflicts are handed to the client to merge — which is how a shopping cart unions two versions.
Costs: the client must know how to merge, and the list grows. Cap its length or it drifts.
Why a vector clock can tell a conflict from an updatetext
Start: D1 [sx:1] node sx wrote once
sx updates: D2 [sx:2] D2 descends from D1 — no conflict, D2 wins
Now a partition. Two different nodes each take a write:
sy writes: D3 [sx:2, sy:1]
sz writes: D4 [sx:2, sz:1]
Compare D3 and D4:
D3 has sy:1, which D4 lacks.
D4 has sz:1, which D3 lacks.
Neither descends from the other → a genuine conflict.
Last-write-wins would pick one by timestamp and throw the other away.
A vector clock hands both to the client, which merges them:
D5 [sx:2, sy:1, sz:1] a cart containing both items
The practical answer in most systems is LWW, because most data is not concurrently written and merging is work. Know the failure mode you are accepting, and say it out loud: “I'd use last-write-wins, which means concurrent writes to the same key silently lose one. For the cart I'd use vector clocks instead, because losing an item is a visible product bug.”
06
Outages are normal: detect, detour, resync
At scale a node is always down somewhere. The design treats this as the steady state, with three separate mechanisms for three separate timescales.
Detect — gossip, and why one witness is not enough
Each node keeps a list of heartbeat counters for its peers and periodically sends it to a few random nodes, which merge it with their own. Counters propagate through the cluster without any central monitor. A counter that has not advanced past its deadline marks that node down.
The reason it takes multiple nodes to agree is that “I cannot reach n3” and “n3 is dead” are different claims — the first may just mean the link between those two is broken. Requiring independent witnesses before declaring a node down stops a single bad network path from evicting a healthy server.
Detour — sloppy quorum and hinted handoff
Strict quorum says a write needs W acks from the key's N replicas. If two of those three are down, writes fail even though the cluster is mostly healthy. Sloppy quorum relaxes it: take the first W healthy nodes on the ring, even if they are not the usual owners. The stand-in records a hint — a note saying “this really belongs to n3” — and replays it to n3 when it returns. Availability is preserved and nothing is lost.
Resync — Merkle trees for permanent repair
Hints cover minutes. A node down for hours comes back missing a large range, and comparing every key would move the whole dataset. A Merkle tree compares hashes instead of data.
How to read: Each leaf hashes one range of keys; each parent hashes its children. Compare roots: if they match, the replicas are identical and you are done in one comparison. If not, descend only into the branches that differ.
If the two roots match, the replicas are byte-identical and the whole check cost one comparison. That is the common case, which is why anti-entropy can run continuously without being expensive.
Interview tip — three timescales, three mechanisms
Say them as a sequence and you will sound like you have operated one of these: gossip notices a node is gone in seconds; hinted handoff covers the next few minutes without losing writes; Merkle trees repair the damage when it comes back hours later. Candidates who name only one of the three have usually read about it rather than thought about it.
Q&A
Check yourself
Distributed-store questions reward precision. Most candidates can say “CAP”; far fewer can say what their own choice costs on a specific Tuesday.
Q1“Design a shopping cart for an e-commerce site.” State your CAP position and defend it. Then the interviewer asks what a user actually experiences when it goes wrong.
CP — a cart must always be correct
AP, because refusing an “add to cart” costs real revenue — and the visible failure is a resurrected deleted item, not a lost one
CA, since partitions are rare in a modern data centre
✓ AP — and name the specific symptom. This is Amazon's canonical case: a failed add-to-cart is lost revenue, while two divergent carts can be merged. The part most candidates miss is what merging actually does to the user. If you reconcile by taking the union of both versions, then an item the user deleted on one side reappears, because a deletion on one replica loses to a presence on the other. Dynamo shipped with exactly this behaviour and accepted it: a resurrected item is a mild annoyance a user can fix, whereas a silently dropped item is lost revenue. The fix if you care is to make deletion an explicit tombstone that also merges, so “removed” is a value rather than an absence. Saying “AP” gets you a nod; describing the resurrected item gets you the point.
Q2A team runs N=3, W=1, R=1 for speed and reports “occasional weird reads.” They propose moving to W=3, R=1 so writes are everywhere. What do you tell them?
Good plan — W=3 gives the strongest possible guarantee
It gives overlap, but W=N means a single node being down stops all writes; W=2, R=2 gives the same guarantee and survives a failure
They should move to W=1, R=3 instead
✓ W=3 buys the guarantee at an unnecessary price. Both W=3,R=1 and W=2,R=2 satisfy W+R > N, so both make stale reads impossible. But W=N means zero fault tolerance on the write path: one node rebooting for a routine patch and every write in the system fails. That is a strange thing to accept from a design whose entire purpose was surviving node loss. W=2,R=2 tolerates one node down on either path. When W=3,R=1 is actually right: a configuration store that is written once a week and read constantly — you genuinely want reads to cost one reply, and a failed weekly write is acceptable. Drag the §4 picker to 3,3,1 and watch “writes survive” drop to zero nodes.
Q3You run W=2, R=2 on N=3. Two clients write the same key at the same instant, both succeed, and later reads return different values on different attempts. Did the quorum fail?
Yes — W+R > N should have prevented this
No. Overlap guarantees a reader sees a latest write; it says nothing about there being only one. This is a write-write conflict and needs resolution, not a bigger quorum
Yes, R needs to be 3
✓ The quorum did exactly what it promises, which is less than people assume.W + R > N gives read-after-write consistency, not serialisability. Two concurrent writers can each collect two acks from an overlapping-but-different pair, and both legitimately succeed; now two causally unrelated versions exist and a reader may see either. Raising R does not help — the problem is not visibility, it is that there is no ordering between the two writes. The fixes are conflict resolution, not quorum tuning: last-write-wins (simple, silently discards one write, and depends on clocks you cannot trust — see Day 8), vector clocks (detects the conflict honestly and hands both versions to the client to merge), or conditional writes / compare-and-set, which make the second writer fail loudly instead of silently winning. If the interviewer wants true single-key linearisability, you are leaving Dynamo-style quorums and moving to a consensus protocol like Raft, which is a different and much more expensive design.
Q4Your three replicas for a key are spread across three racks in one data centre. The business now wants to survive losing the whole data centre. What changes, and what does it cost?
Nothing — three replicas is three replicas
Replicas must span regions, which makes every quorum write pay cross-region latency; the usual answer is LOCAL_QUORUM plus async cross-region replication
Increase N to 5 within the same data centre
✓ Spread the replicas, then immediately confront the latency bill. Rack-level redundancy protects against a rack; it does nothing for a region event — this is Day 3's independence assumption again. Moving replicas into separate regions means a W=2 quorum may require an acknowledgement from across an ocean, adding Day 3's 150 ms to every write. What real systems do: require a quorum within the local region (Cassandra calls this LOCAL_QUORUM) and replicate to the remote region asynchronously. You keep local write latency and you survive the region, but you accept that a region lost abruptly may take a few seconds of unreplicated writes with it. That residual window is a product decision, not a technical one, and naming it is the strong part of the answer. Raising N inside one data centre buys nothing here: five copies in one building is still one building.
Q5A node is down for four hours, comes back, and immediately starts serving reads. Users report seeing old data for the next twenty minutes. What went wrong operationally?
Nothing — eventual consistency means this is expected
It rejoined the read path before anti-entropy had repaired it; it should serve no reads until its Merkle comparison shows it is caught up
Its clock was wrong
✓ It rejoined before it was repaired. A returning node holds a four-hour-old snapshot of its key range. Hinted handoff replays only what was buffered for it during the outage, and Merkle-tree repair takes time to run — so for a window after rejoining, the node is a confidently wrong replica. With R=1 a read landing there returns stale data; even with R=2 it drags the quorum toward stale values unless read repair happens to fire. The operational fix is a rejoin protocol: the node comes back in a bootstrapping state where it accepts writes (so it stops falling further behind) but serves no reads, runs anti-entropy against its peers, and only enters the read path once it reports caught-up. This is the kind of answer that distinguishes someone who has operated one of these from someone who has read about one — the algorithms in §6 are correct, and getting the sequencing wrong around them still produces an incident.
In practiceWhat production adds, and the questions that come next optional
This lesson covers the layer that decides an interview. Below it is the operational layer — the things that only show up once a system is running, and the questions that come if someone keeps pulling the thread. None of it is answered above.
Consistency models
Linearizability defined operationally, and the cost it imposes (coordination on every operation)
Quorums
Multi-region quorums and why a quorum spanning continents is usually a mistake
LSM vs B-tree storage
Write, read and space amplification: define each and say which engine trades which
Tombstones and range deletes: why deletion is expensive in an LSM engine
Terms used
CAP
Consistency, availability, partition tolerance. Partitions are unavoidable, so the real choice is C or A during one.
N, W, R
Replica count, write acks required, read responses required. W + R > N forces overlap.
Coordinator
Whichever node received the request. It fans out to the replicas and assembles the answer. No fixed master.
Read repair
Noticing a stale replica during a read and updating it in the background.
Last write wins
Resolving conflicts by timestamp. Simple, and silently discards one of two concurrent writes.
Vector clock
Per-value list of [node, counter] pairs. Distinguishes “newer than” from “concurrent with”.
Gossip
Nodes exchanging heartbeat lists with random peers so failure information spreads without a central monitor.
Sloppy quorum
Accepting W acks from the first healthy nodes rather than strictly the key's owners.
Hinted handoff
A stand-in storing a write plus a note of its true owner, and replaying it when that owner returns.
Merkle tree
A tree of hashes over key ranges, used to locate differences between replicas in log n comparisons.
Anti-entropy
Background repair that converges replicas without a client request triggering it.
Bloom filter
Probabilistic set membership: “definitely not present” or “possibly present”. Avoids useless disk reads.
What breaks next. Last-write-wins needs timestamps, vector clocks need per-node counters, and both assume you can generate identifiers that are unique across a fleet and ordered by time — without any node asking permission. Day 8 builds exactly that, and shows what happens when the clocks it relies on go backwards.
Source: System Design Interview, Ch. 6 — Design a key-value store (pp. 87–109). The quorum-overlap diagram, the vector-clock worked example and the Merkle-tree walkthrough are expanded here from the chapter's summaries.