Design a key-value store
A Dynamo-style store that stays writable through node failures. Partitioning, tunable quorums, conflict resolution, hinted handoff, Merkle tree repair and an LSM storage engine.
The problem
An online shop keeps shopping carts in a relational database with one primary and a standby. During a network fault between two data centres, the primary is unreachable for four minutes while failover completes. For those four minutes nobody can add anything to a cart. Nothing is lost, but the shop has decided that refusing a write costs more than occasionally having to reconcile two versions of a cart.
Amazon described this trade in the Dynamo paper in 2007. Dynamo is a key-value store with no primary: every node can accept a write for any key, data is replicated to several nodes, and the system keeps accepting writes through node failures and partitions. The price is that replicas can disagree, so the store needs ways to detect and repair that. Cassandra, Riak and Voldemort took their designs from it.
Requirements
Functional
put(key, value),get(key)anddelete(key). Values are opaque blobs, up to 1 MB.- The caller can choose, per request, how many replicas must respond.
- No range scans, secondary indexes or multi-key transactions.
Non-functional
- Availability: a write succeeds as long as W nodes can be reached, even when they are not the key’s usual replicas. This is the defining requirement, and it puts the store on the AP side of CAP.
- Durability: an acknowledged write survives the permanent loss of any one node.
- Latency: p99 under 10 ms for reads and writes inside one region.
- Consistency: eventual by default, tunable towards stronger per request.
- Scale: 100 TB of data, growing, with nodes added one at a time and no downtime.
- No node is special. There is no primary to fail over.
Capacity estimates
| Quantity | Working | Result |
|---|---|---|
| Data | 50 billion items x 2 KB | 100 TB |
| With replication | 100 TB x 3 replicas | 300 TB |
| Nodes | 300 TB / 2 TB used per node (a 4 TB disk kept half empty) | 150 |
| Peak requests | given | 100,000 writes and 200,000 reads per second |
| Replica operations | (100,000 + 200,000) x 3 replicas | 900,000 per second |
| Per node | 900,000 / 150 | 6,000 per second |
| Hardware failures | 150 nodes x an assumed 3% a year | 4 or 5 a year |
Disk, not request rate, sets the node count: 6,000 small operations a second is light work for one machine with an SSD. Half of each disk stays free because compaction and the arrival of a new node’s data both need working space.
The last row matters most. Add restarts for deploys and kernel patches, and on most days at least one of 150 nodes is down for a while. Failure handling is the normal path here, not an edge case.
API
get(key, R) returns one or more values, plus a context
put(key, value, context, W) returns ok, or a timeout if fewer than W replicas answered
delete(key, context, W) returns ok
The context is an opaque version token. A client reads a key, gets the value and its context, and passes the context back with its next write so the store knows which version that write replaces. A get can return several values when the store holds concurrent versions it cannot order. A timeout on put does not mean the write failed everywhere: it may have reached one replica and will spread later. Clients must treat it as “unknown” and make writes safe to retry (see idempotency).
Data model
Each replica stores, per key:
| Field | Notes |
|---|---|
key |
bytes; its hash is its position on the ring |
value |
opaque blob |
version |
a vector clock, or a timestamp under last-write-wins |
tombstone |
marks a delete, with the time it happened |
Cluster metadata is the ring: a map from token (a position on the ring) to node, plus each node’s state. Every node holds the whole map, so any node can find a key’s replicas without asking anyone.
High-level architecture
Partitioning. Keys are placed by consistent hashing. Each physical node owns many tokens (virtual nodes), which evens out load and means a new node takes a little data from many peers. A key’s replicas are the first N distinct physical nodes clockwise from its hash, chosen across racks or zones. Here N is 3.
Remove a node and check “Moved by last change”: only that node’s keys move, and with more virtual nodes they spread across several peers instead of one.
Write. The client sends a put to any node, through a load balancer or a client library that knows the ring. That node acts as coordinator. It sends the write to all three replicas and replies to the client once W of them have acknowledged. Each replica appends the write to its commit log and updates its memtable before acknowledging.
Read. The coordinator asks the replicas, waits for R answers and returns the newest version, or all versions it cannot order. If one replica answered with an older version, the coordinator writes the newer one back to it. That is read repair.
In the background. Nodes gossip about who is alive. A fallback node holds hints for a replica that is down. Replicas compare Merkle trees to find and fix differences.
Deep dives
Quorums and conflict resolution
N, W and R are the tuning knobs.
| N, W, R | Behaviour |
|---|---|
| 3, 2, 2 | Usual default. Tolerates one replica down for reads and for writes |
| 3, 1, 1 | Fastest and most available. Stale reads are common |
| 3, 3, 1 | Fast reads of the latest value. Any replica down blocks writes |
| 3, 1, 3 | Fast writes. Any replica down blocks reads |
When R + W is greater than N, every set of R replicas shares at least one node with every set of W replicas, so a read reaches at least one replica that has the latest acknowledged write. That is weaker than it sounds:
- With a sloppy quorum, a write can be acknowledged by fallback nodes that are not among the key’s home replicas. A read of the home replicas can miss it.
- A write that timed out may still sit on one replica and appear later.
- Two writes can be in flight at the same moment, and replicas can receive them in different orders.
So quorums give “usually the latest”, not linearizability. A store that needs compare-and-set on a key has to add consensus for that operation, as Cassandra does with its Paxos-based lightweight transactions.
Concurrent writes. Two clients update the same key through different coordinators during a partition. Both writes succeed. There are three ways to settle it.
Last-write-wins. Every write carries a timestamp and the highest wins. It is simple and needs nothing from the client, but one of the two writes disappears without an error, and a node with a fast clock wins every argument. Cassandra works this way, per column.
Vector clocks. The version is a list of (node, counter) pairs. If one version’s counters are all at least as high as another’s, it is a descendant and replaces it. If neither dominates, the writes were concurrent and the store keeps both as siblings.
Coordinator A writes the cart: [A:1]
B and C each accept an update to [A:1]
while partitioned from each other: [A:1, B:1] and [A:1, C:1]
Neither dominates, so a get returns both.
The client merges them and writes via A: [A:2, B:1, C:1]
The client must merge. For a cart, the union of items is the obvious merge, and the Dynamo paper notes its flaw: an item deleted on one side can come back.
CRDTs. Use value types with a built-in merge that always converges, such as counters and sets. The application gives up arbitrary blobs for those types.
Choose AP mode, cut the network, write a different value on each side, then heal the partition and see which write last-write-wins throws away.
Failure detection and repair
Gossip. There is no central membership service. About once a second each node exchanges its view of the cluster (who exists, their tokens, a heartbeat counter) with a few random peers, so news reaches all 150 nodes within seconds. A node judges a peer to be down from how late its heartbeats are. Cassandra uses a phi accrual detector, which outputs a suspicion level instead of a fixed timeout, so a slow network does not trigger false alarms as easily.
Hinted handoff covers short outages.
Step 1 of 8
Each key has three replicas, and a write needs two acknowledgements. The key cart:7 belongs to replicas A, B and C. Replica C has just crashed.
Read the steps as text
- Each key has three replicas, and a write needs two acknowledgements. The key cart:7 belongs to replicas A, B and C. Replica C has just crashed.
- The client sends a put for cart:7. The coordinator forwards it to all three replicas at once. It does not wait to find out which ones are healthy.
- Replicas A and B acknowledge. That makes two, so the coordinator tells the client the write succeeded. The client never learns that one replica was down.
- The coordinator also sends the write to node D, the next healthy node on the ring, marked as a hint meant for replica C. Node D keeps it apart from its own data.
- A minute later replica C restarts. Gossip spreads the news that it is alive, and node D hears it within a few seconds.
- Node D replays the hint to replica C and then deletes its own copy. All three replicas now hold the write, and no client request was needed to make that happen.
- Hints are a shortcut and can fail. If node D dies first, or replica C stays down past the hint window, the hint is lost. Read repair and Merkle tree comparison then find and fix the gap.
- Hinted handoff keeps writes fast and available through short outages. It is an optimisation. Background anti-entropy is what guarantees that replicas converge.
The animation follows the Dynamo paper, where a neighbouring node holds the hint. Cassandra keeps the hint on the coordinator instead. Either way hints are kept for a limited window, three hours by default in Cassandra, and a longer outage needs something else.
Read repair fixes a stale replica whenever a read happens to notice it. Keys that are never read are never repaired this way.
Anti-entropy is the backstop. Each replica builds a Merkle tree over a key range: leaves are hashes of small sub-ranges and each parent is the hash of its children. Two replicas compare roots. If they match, the range is identical. If not, they descend into the differing branches and exchange only those sub-ranges. The cost follows the amount of difference, not the amount of data.
Deletes interact badly with repair. If a delete simply removed the key from two replicas while the third was down, repair would later see one replica with a value and two without, and copy the value back. So a delete writes a tombstone, which is a version like any other, and compaction drops it only after a grace period that is longer than the repair cycle. Cassandra’s default is 10 days.
The storage engine
Each node needs a local store that absorbs heavy writes. A log-structured merge tree fits, as LSM trees explains in detail.
- A write is appended to the commit log on disk and inserted into the memtable, a sorted structure in memory. Both are cheap, sequential operations.
- A full memtable is flushed to an immutable sorted file, an SSTable.
- A read checks the memtable, then SSTables from newest to oldest. A Bloom filter per file lets it skip files that cannot contain the key.
- Compaction merges SSTables in the background, dropping overwritten values and expired tombstones.
The trade is fast writes for slower reads and for background I/O. If compaction falls behind, reads touch more files and latency climbs.
Bottlenecks and failure modes
- Adding a node. It must receive about 2 TB from its peers, which takes hours and competes with live traffic. Throttle the streams and add one node at a time.
- Compaction debt. Sustained writes above what compaction can merge pile up SSTables and fill the disk. Watch pending compactions and apply backpressure to writers before the disk is full.
- Hot keys. A key lives on N nodes however large the cluster is. A very hot key needs a cache in front, or splitting in the application.
- Clock skew. Under last-write-wins, a node whose clock runs ahead wins conflicts it should lose. Run NTP everywhere and alert on drift.
- Flapping membership. A node that is slow, not dead, can be marked down and up repeatedly, causing hint storms. Tune the failure detector conservatively, and make permanent removal of a node an explicit operator action.
- Correlated failure. If all three replicas of a key share a rack, one switch takes the key offline. Place replicas in different racks or zones.
Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Replication | Leaderless, quorum | Leader per partition with consensus | Writes survive partitions; costs conflicts and weaker reads |
| Default quorum | N=3, W=2, R=2 | W=1 or W=3 | One node down blocks nothing; overlap in the normal case |
| Conflicts | Vector clocks, siblings | Last-write-wins | No silent loss; clients must merge |
| Membership | Gossip | Coordination service | No central dependency; views converge in seconds, not instantly |
| Storage engine | LSM tree | B-tree | Cheap sequential writes; compaction cost and slower reads |
45-minute interview script
A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.
- 0:00 to 5:00
Requirements 5 min
Establish the interface (get, put, delete by key, no queries) and ask the question that decides everything, which is whether writes must succeed during a partition or reads must never be stale. Agree value sizes, latency and durability.
- 5:00 to 8:00
Capacity estimates 3 min
Data size times replication factor gives the node count. Then point out that with 150 nodes some node is down most days, so failure handling is the design.
- 8:00 to 11:00
API 3 min
Get, put and delete with a per-request consistency level and a version context. Explain why a get can return more than one value.
- 11:00 to 14:00
Data model 3 min
Key, opaque value, version and tombstone. The ring map that every node holds.
- 14:00 to 22:00
High-level design 8 min
Draw a client, a coordinator and three replicas on the ring. Walk through a write and a read with N=3, W=2, R=2. Add the fallback node and the storage engine under one replica.
- 22:00 to 30:00
Deep dive: quorums and conflicts 8 min
R + W > N and what it does not guarantee. Then how two concurrent writes are detected and resolved, comparing last-write-wins, vector clocks with siblings, and CRDTs.
- 30:00 to 38:00
Deep dive: failure handling 8 min
Gossip and failure detection, hinted handoff for short outages, read repair, Merkle tree anti-entropy for long ones, and why deletes need tombstones.
- 38:00 to 42:00
Deep dive: storage engine 4 min
Commit log, memtable, SSTables, Bloom filters and compaction. Say why an LSM tree suits a write-heavy store.
- 42:00 to 45:00
Wrap-up 3 min
Restate the choice of availability over consistency and where you would not use this design. Mention what you would add next, such as multi-region replication.
Key takeaways
- Decide first whether the store favours availability or consistency under a partition. A Dynamo-style store chooses availability and pays with conflicts.
- Each key is stored on the N distinct nodes clockwise from its position on the ring, and any node can coordinate a request.
- R + W > N makes read and write sets overlap. It does not make the store linearizable, especially with sloppy quorums or last-write-wins.
- Concurrent writes must be either detected (vector clocks, siblings) or silently resolved (last-write-wins). Choose per use case.
- Hinted handoff heals short outages, read repair heals what is read, and Merkle tree anti-entropy heals everything else.
- Deletes are tombstones that must outlive the repair interval, or deleted data comes back.
Try it
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What do N, W and R mean in a Dynamo-style store?
N is the number of replicas of each key. W is how many must acknowledge a write and R how many must answer a read before the coordinator replies. R + W > N makes the read and write sets overlap.
What is a sloppy quorum?
When some of a key's N home replicas are unreachable, the write is accepted by the next healthy nodes on the ring, with a hint. Writes stay available, but a read of the home replicas may miss the newest value.
Last-write-wins against vector clocks?
Last-write-wins keeps the value with the highest timestamp and silently drops concurrent writes. Vector clocks detect that two writes were concurrent and keep both for the client to merge.
Three repair mechanisms and when each acts?
Hinted handoff replays missed writes after a short outage. Read repair fixes stale replicas noticed during a read. Anti-entropy compares Merkle trees in the background to fix everything else.
Why is a delete stored as a tombstone?
So the delete has a version and can beat the old value during repair. Without it, a replica that missed the delete would copy the old value back to the others.
What is the write path inside one node of an LSM-based store?
Append to the commit log for durability, insert into the in-memory memtable, acknowledge. Full memtables are flushed as immutable sorted files (SSTables), which compaction later merges.