Design a key-value store
A Dynamo-style distributed store: partitioning, replication, quorums, conflict handling and how reads and writes reach disk.
On the roadmap:Interview Ready · step 2: Building-block designs
Lesson 3 of 11 · 14 min read · quiz · exercise
The problem
A key-value store supports put(key, value) and get(key). A distributed one must also:
- Store far more than one machine can hold.
- Keep serving when machines or networks fail.
- Have low latency for both reads and writes.
- Let you tune consistency against availability.
We use a Dynamo-style design, which is the model behind several widely used stores.
Partition the data
Spread keys across nodes with consistent hashing (previous lesson). Virtual nodes keep the load even and let you add capacity gradually. Any node can act as the coordinator for a request, so there is no single leader to bottleneck on.
Replicate each key
Copy every key to N nodes: the owner and the next N-1 distinct nodes clockwise on the ring. Spread replicas across racks or zones so one failure does not take out all copies.
Figure SDA-CSD-03-1 · Replicating each key to N nodes · © forcsguy.com
Tunable consistency with quorums
Choose three numbers:
- N: number of replicas.
- W: replicas that must acknowledge a write.
- R: replicas that must answer a read.
| Setting | Behaviour |
|---|---|
W + R > N | Reads overlap the latest write: strong-ish consistency |
W = 1, R = 1 | Fastest and most available, but reads can be stale |
W = N, R = 1 | Fast reads, writes fail if any replica is down |
You pick the trade-off per use case, which is what makes this design flexible.
A quorum write, step by step
Figure SDA-CSD-03-2 · Coordinator and a write quorum (N=3, W=2) · © forcsguy.com
When replicas disagree
Replicas can hold different versions, for example after a partition.
- Versioning: attach a version (a vector clock) to each value so the system can tell whether one version supersedes another or they were concurrent.
- Reconciliation: for concurrent versions, either the application merges them (shopping cart: union the items) or the system uses a simple rule such as last-write-wins, which can silently discard data.
Two writers at once: conflicts and vector clocks
Figure SDA-CSD-03-3 · Concurrent writes create two versions · © forcsguy.com
Figure SDA-CSD-03-4 · Vector clocks across writes · © forcsguy.com
A clock A is an ancestor of B if every counter in A is less than or equal to the matching counter in B. If each has some counter larger than the other's, the versions are siblings and need merging.
Failure handling
- Detection: nodes exchange gossip messages about who is alive, so there is no central monitor to fail.
- Temporary failure: if a replica is down, another node accepts the write and stores a hint, handing it over when the replica returns (hinted handoff).
- Permanent repair: periodically compare replicas using Merkle trees (hashes of key ranges) and copy only what differs (anti-entropy).
- Data centre failure: replicate across regions for the keys that need it.
Noticing failures: gossip
Figure SDA-CSD-03-5 · Gossip failure detection · © forcsguy.com
Staying available through a short outage
Figure SDA-CSD-03-6 · Sloppy quorum and hinted handoff · © forcsguy.com
Repairing replicas for good: Merkle trees
Figure SDA-CSD-03-7 · Comparing replicas with Merkle trees · © forcsguy.com
More failure-handling detail
- Do not trust one witness. One node saying "that server is down" is not enough; require agreement from several independent sources (gossip gives this naturally: a node is marked down only after others also see its heartbeat counter stall).
- Sloppy quorum. A strict quorum can block when the usual replicas are down. Instead, take the first healthy servers on the ring for the write or read, and let a stand-in hold the data with a "hint". When the real replica returns, the stand-in hands the data back (hinted handoff). You gain availability and give up the strict overlap guarantee for a while.
- Replica placement. When walking the ring for N replicas, skip virtual nodes that belong to a server already chosen, and spread replicas across data centers, because nodes in one site often fail together.
- Bigger machines. Give a more powerful server more virtual nodes so it takes a proportionally larger share.
- Conflicting versions. Vector clocks grow as more servers touch a key; cap their length and accept that, rarely, old entries dropped make some conflicts harder to untangle.
Inside one node: how writes and reads hit disk
Figure SDA-CSD-03-8 · Write and read path on one node · © forcsguy.com
Write path
- Append to a commit log (sequential, fast, crash-safe).
- Apply to an in-memory sorted structure (the memtable).
- When the memtable is full, flush it to an immutable sorted file on disk; background compaction merges files.
Read path
- Check the memtable.
- If missing, check the files, using a Bloom filter per file to skip files that definitely do not contain the key.
- Merge results, newest wins.
This log-structured design turns random writes into sequential ones, which is why such stores handle huge write volumes.
One node, many jobs
Figure SDA-CSD-03-9 · What every node does · © forcsguy.com
Summary of the design
| Concern | Technique |
|---|---|
| Scale out | Consistent hashing with virtual nodes |
| Durability and availability | N replicas across zones |
| Consistency dial | Quorums (W, R) |
| Conflicts | Vector clocks and merge logic |
| Failure detection | Gossip |
| Temporary and permanent repair | Hinted handoff, Merkle-tree anti-entropy |
| Fast writes | Commit log, memtable, sorted files |
Worked numbers: how many nodes?
Target: 1 billion keys averaging 1 KB, with 3 replicas, serving 100,000 operations per second.
- Raw data: 1 B x 1 KB = 1 TB. With three replicas, 3 TB of storage across the cluster, before overhead for indexes and compaction (plan for about 2x headroom on disk for compaction, so around 6 TB).
- Per-node capacity: if one node comfortably holds 1 TB of data and serves about 10,000 operations per second, 12 to 15 nodes cover both storage (3 TB / 1 TB, with room) and throughput (100,000 / 10,000 x 3 for replication on writes and headroom).
- With a 20-node ring each node owns about 5% of the keys, and losing one node moves its 5% (about 150 GB of replicas) to its neighbours: repair takes minutes to hours, which is why you keep spare capacity.
When a replica is down: hinted handoff
With W = 2 of N = 3, a write must reach two replicas. Suppose node C is down.
- The coordinator sends the write to A, B and C; A and B acknowledge, so the write succeeds.
- For C, a hint ("this write was meant for C") is stored on a healthy node.
- When C returns, the holder of the hint replays the write to C.
If the node is down for too long the hints are dropped, and a slower anti-entropy repair takes over.
Figure SDA-CSD-03-10 · A write while one replica is down · © forcsguy.com
Anti-entropy with Merkle trees
Replicas can still drift apart (a hint was lost, a disk was corrupted). Comparing every key between two replicas is far too expensive. A Merkle tree summarises a key range with hashes: each leaf is a hash of a small bucket of keys, and each parent is a hash of its children. Two replicas compare root hashes; if equal, the whole range matches. If not, they compare the children and descend only into the branches that differ, until they find the few buckets that actually disagree and exchange just those keys.
Figure SDA-CSD-03-11 · Finding differences without comparing every key · © forcsguy.com
Mistakes people make
- Hot keys. One extremely popular key overloads its replicas whatever the cluster size. Cache it in front or split it into several keys.
- Large values. Multi-megabyte values hurt latency and replication; store big blobs in object storage and keep a pointer.
- Expecting joins and secondary queries. A key-value store answers "get by key". If you need other queries, add an index structure or use another database.
- Resolving conflicts with wall-clock time alone. Skewed clocks lose writes; prefer version vectors or let the application merge.
- Forgetting tombstones. Deletes leave markers that must live long enough to reach all replicas, and be compacted away later. Skipping this resurrects deleted data.
- Never running repair. Without regular anti-entropy, rarely read data can silently diverge.
Try it yourself
Build the consistent hash ring lab to see how few keys move when a node joins, the Bitcask lab for one node's storage engine, and the write-ahead log lab for crash recovery. Then read the consistency and CAP lesson for the quorum rule used above.
Related reading
- Amazon Dynamo: Highly Available Key-Value StoreWerner Vogels · AmazonCase Studies
- The Google File System (paper)Ghemawat, Gobioff and Leung · GooglePapers
- The Log-Structured Merge-Tree (paper)O'Neil et al. · UMass BostonPapers
- Time, Clocks, and the Ordering of Events in a Distributed System (paper)Leslie Lamport · Microsoft ResearchPapers
Show 6 moreShow fewer
- ZippyDB: Facebook's key-value storeMeta Engineering · MetaCase Studies
- Inside the Magic PocketDropboxCase Studies
- Spanner: Google's Globally Distributed Database (paper)Corbett et al. · GooglePapers
- Read Consistency with Database Replicas at ShopifyShopify engineers · ShopifyCase Studies
- Designing Large-Scale SystemsSomethingsimilar engineers · SomethingsimilarBlogs
- Reddit Inc Blog HomepageRedditblog engineers · RedditblogBlogs
Check your understanding
Question 1 of 4
0 correct so far
With N = 3 replicas, which setting guarantees that every read overlaps the latest successful write?
Go deeper
- Dynamo: Amazon's Highly Available Key-value Store by DeCandia et al.: the original paper; widely available online
- Designing Data-Intensive Applications, chapters 3, 5 and 6 by Martin Kleppmann
- Dynamo: Amazon's highly available key-value store by Amazon: quorums, vector clocks, hinted handoff and Merkle trees in one paper
- Bigtable: a distributed storage system for structured data by Google: the log-structured storage model behind many stores
- Cassandra architecture by Apache Cassandra: gossip, replication and the write and read paths
- SSTable and log-structured storage by Ilya Grigorik: how sorted tables and merging work
- Merkle tree by Wikipedia: the structure used for replica comparison
Try it: see a system in action
One tap in a real app already crosses a client, a server and a database. Watch it happen, then try scoping a brief a few different ways below.
The app
One key, one value, needed in under a millisecond
What just happened
Tap the button to send a real request.
One tap in the app sends a real request. Watch where it actually goes.
Go further: the Builder
Once you know what to ask, the Builder is where you turn requirements into an architecture. Come back to this once you've met a few more concepts.
Try it yourself
You run a key-value store with N = 3. For a shopping cart you want writes to always succeed even during failures; for a unique-username table you need reads to always see the latest write. Choose W and R for each and explain.
Click what a strong design here would need:
More in Design practice
© 2026 forcsguy.com. Original lesson text and diagrams. Books and sites linked above belong to their authors.