Distributed key-value store
Design partitioning, replication, quorums and failure handling for a KV store.
By Invicly Tech, , in System Design Deep Dive. About 12 minutes to read.
In short
A Dynamo-style key-value store spreads keys over nodes with consistent hashing, replicates each key to N nodes, and uses tunable quorums. Hinted handoff, anti-entropy and versioning keep it available and convergent through failures.
Explained simply
A key-value store is a giant dictionary spread over many machines. You give it a key, like cart:42, and a value, like the contents of a shopping cart, and later you ask for the value by its key. Amazon's Dynamo paper described this design, and Cassandra, Riak and DynamoDB all borrow its ideas.
Because there is too much data for one machine, the keys are spread across many nodes using consistent hashing, so adding a machine only moves a small part of the data. Each key is also copied to several nodes, usually three, so a dead machine loses nothing.
The design favours staying available. Any node can accept a request and pass it to the right replicas. A write succeeds once enough replicas confirm it, and a read asks enough replicas to be likely to see the newest value. You tune how many with three numbers: N copies, W write confirmations and R read replies.
Machines fail all the time at this scale, so repair is built in. Writes for a down node are held by a neighbour and handed over later. Background jobs compare replicas and fix differences. And when two writes clash, the store keeps version information to decide what to do.
Press Play on a diagram to walk through it one step at a time.
- 1Client API
get(key) and put(key, value)
- 2Coordinator node
Any node routes the request
- 3Consistent hash ring
Maps keys to N replica nodes
- 4Storage engine
LSM tree with commit log per node
- 5Gossip and repair
Membership, failure detection, Merkle tree sync
- Client to Coordinator: put(k, v)1put(k, v)
- Coordinator to Replica A: Write k=v, version2Write k=v, version
- Coordinator to Replica B: Write k=v, version3Write k=v, version
- Replica A to Coordinator: Ack4Ack
- Replica B to Coordinator: Ack5Ack
- Coordinator to Client: Success, W=2 reached6Success, W=2 reached
- Partitioning
- Consistent hashing
- Virtual nodes
- Replication
- N copies
- Zone-aware placement
- Consistency
- Tunable W and R
- W + R > N for overlap
- Failure handling
- Gossip detection
- Hinted handoff
- Merkle tree repair
- Storage engine
- Commit log
- LSM tree
- Tombstones
- Conflicts
- Last-write-wins
- Vector clocks
- CRDTs
In depth
Requirements and API
Clarify the shape of the data and the traffic first. Typical answers: small values (up to about 1 MB, usually a few KB), simple operations get(key), put(key, value) and delete(key), no range queries or joins, very high scale (say 100,000 operations per second and tens of terabytes), single-digit millisecond latency, and above all high availability: writes must keep working when nodes or even a zone fail.
That last point is a choice. Saying we prefer availability over strong consistency means the store is eventually consistent by default, with quorum settings to get closer to strong consistency when a use case needs it.
The Dynamo-style API adds a context: get returns the value plus an opaque version context, and put takes that context back. This lets the store know which version the client was updating, which is how it detects concurrent writes.
- get(key) returns value(s) and a version context
- put(key, value, context)
- Small values, no range queries
- Availability first, consistency tunable
Partitioning and replica placement
Keys are hashed onto a ring, and each physical node owns many virtual node positions so load stays even and a new node takes small slices from all the others. A key's coordinator is the first node clockwise from its hash, and its replicas are the next N distinct physical nodes clockwise. This ordered list is the key's preference list.
Two details matter. Skip virtual nodes that belong to a physical node already in the list, or two replicas could land on the same machine. And make placement zone-aware: pick replicas so that the N copies sit in different availability zones or racks, as Cassandra's NetworkTopologyStrategy does. Then losing a whole zone still leaves N - 1 copies.
Every node knows the ring through gossip, so any node can act as coordinator, or a smart client can send requests straight to a replica and save a hop.
- 1hash(key)
Position on the ring
- 2Walk clockwise
Visit virtual nodes in order
- 3Skip duplicates
Ignore nodes already chosen
- 4Spread across zones
One replica per zone where possible
- 5Preference list
First N distinct nodes hold the key
Inside one storage node
Each node stores its share with an LSM-tree engine, which suits the write-heavy load. A write is appended to a commit log on disk for durability, inserted into an in-memory memtable, and acknowledged. When the memtable fills, it is flushed as an immutable sorted file (SSTable). Background compaction merges files and drops overwritten values and expired tombstones.
A read checks the memtable, then SSTables from newest to oldest, using per-file Bloom filters to skip files that cannot contain the key. A row cache or page cache keeps hot keys fast.
Deletes are tombstones, not immediate removals, because a replica that was down during the delete must not bring the old value back later. Tombstones are kept for a grace period (Cassandra's gc_grace_seconds defaults to 10 days) that must be longer than the time it takes to repair a failed replica.
Failure detection, hinted handoff and repair
Nodes detect failures through gossip: each node regularly exchanges heartbeat counters with a few random peers, and a node whose counter stops rising is suspected down. Cassandra uses a phi accrual detector, which turns heartbeat delays into a suspicion level rather than a fixed timeout.
For short failures, the store uses a sloppy quorum with hinted handoff. If a replica is down, the coordinator writes to the next healthy node on the ring with a hint saying this belongs to node C. When C returns, the hint is replayed to it. Writes stay available, but during that time W + R > N no longer guarantees overlap.
For long failures or lost hints, anti-entropy repair compares replicas. Each replica builds a Merkle tree over its key ranges; comparing root hashes, then only the subtrees that differ, finds mismatched keys while transferring very little data.
- Coordinator to Replica B: Write k=v1Write k=v
- Coordinator to Replica C (down): Write k=v (no reply)2Write k=v (no reply)
- Coordinator to Node E: Write k=v with hint: for C3Write k=v with hint: for C
- Node E to Coordinator: Ack: W=2 reached4Ack: W=2 reached
- Node E to Replica C (down): C is back: replay hinted write5C is back: replay hinted write
Resolving conflicting writes
With sloppy quorums and concurrent clients, two replicas can accept different values for the same key. The store must decide which value survives.
Last-write-wins (LWW) attaches a timestamp to each write and keeps the highest. It is simple and is what Cassandra does per column, but concurrent writes silently lose one side, and clock skew between nodes can make an older write win.
Vector clocks record a counter per node that has updated the value. If one clock is greater than or equal to the other in every entry, it is a newer version and replaces the older one. If neither dominates, the writes were concurrent, and the store keeps both as siblings and returns both on the next read. The application merges them: the original Dynamo merged shopping carts by taking the union of items. Riak works this way. CRDTs, data types like counters and sets that merge automatically, avoid hand-written merge code.
- LWW: simple, can drop concurrent writes
- Vector clocks: detect concurrency, return siblings
- CRDTs: merge automatically for counters and sets
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Define requirements and API~50m
- 2Partition with consistent hashing~50m
- 3Replicate with tunable quorums~50m
- 4Handle failures with hinted handoff~50m
- 5Resolve conflicts and discuss trade-offs~50m
Key points
- Each key is stored on the next N distinct nodes clockwise on the ring.
- W + R > N gives overlapping quorums for fresher reads.
- Hinted handoff stores writes for a down node and replays them later.
- Merkle trees let replicas find and repair differences cheaply.
- Vector clocks or last-write-wins resolve conflicting versions.
Key terms
Tap a card to flip it. 0/6 known
Examples
API:
put(key, value, context?) -> ok
get(key) -> [values], context
Config: N=3, W=2, R=2 (W+R > N)
put("cart:42") -> hash -> nodes B, C, D
C down -> write to E with hint "for C"
C returns -> E hands off the write to CTunable quorums with hinted handoff.
Sizing the cluster
Requirements: 20 TB of live data, replication factor 3, 200,000 operations per second at peak. Step 1: raw storage is 20 TB x 3 = 60 TB. Step 2: LSM trees need room for compaction, so plan to fill disks only to about 50%: 120 TB of disk. Step 3: with 4 TB of SSD per node, that is 30 nodes. Step 4: check throughput: 200,000 ops/s over 30 nodes is about 6,700 per node, and because each write touches 3 replicas, about 20,000 replica writes per node at most, which a modern node handles. Step 5: place 10 nodes in each of 3 zones so every key has one copy per zone.
Detecting a conflict with vector clocks
Step 1: a client writes cart = [book] through node A: clock {A:1}. Step 2: a client reads it and adds a pen through node A: {A:2}, which dominates {A:1}, so it replaces it. Step 3: a network split happens. One client adds a mug via A: {A:3}. Another, holding the {A:2} version, adds a lamp via B: {A:2, B:1}. Step 4: compare {A:3} and {A:2, B:1}: A is higher in the first, B in the second, so neither dominates. Step 5: the next read returns both siblings. Step 6: the app merges them into [book, pen, mug, lamp] and writes back with clock {A:3, B:1}, which dominates both.
Quick reference
- API: get(key) returns value plus version context; put(key, value, context)
- Replicas: next N distinct physical nodes clockwise, spread across zones
- N=3, W=2, R=2 overlaps and survives one node down
- Hinted handoff keeps writes available; sloppy quorums weaken the overlap guarantee
- Merkle trees find differing key ranges while transferring very little data
- Tombstone grace period must exceed your repair interval (Cassandra default 10 days)
- Vector clocks detect concurrent writes; LWW silently drops one of them
Common mistakes
- Placing all N replicas in one availability zone.
- Using wall-clock last-write-wins and losing concurrent writes.
- Skipping anti-entropy so replicas drift permanently.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
With N = 3, give W and R settings for: (a) fastest writes, (b) fastest reads, (c) a balanced setting that still overlaps. Say what each tolerates.
- Exercise 2medium
Write a Python function compare(vc1, vc2) for vector clocks stored as dicts. Return 'before', 'after', 'equal' or 'concurrent'.
- Exercise 3hard
A node is replaced after its disk died. Describe, step by step, how it gets its data back, and how the cluster stays available meanwhile.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is Redis a distributed key-value store like this?
- Redis Cluster shards keys across nodes and replicates them, but it uses a leader per shard and asynchronous replication, not Dynamo-style quorums. It favours speed and simplicity over this kind of tunable availability.
- What is the difference between DynamoDB and the Dynamo paper?
- The 2007 Dynamo paper described Amazon's internal leaderless store with vector clocks and sloppy quorums. DynamoDB is a managed service that shares the key-value model but uses a different design internally, with leader-based replication per partition.
- Why not just use consistent hashing without virtual nodes?
- With one position per node, the ring slices are uneven and a new or failed node shifts load onto only one neighbour. Many virtual positions per node spread both data and rebalancing work evenly.