“Design a key-value store” (often phrased as “design DynamoDB” or “design Cassandra”) is the classic deep-dive question. Amazon, Google, Microsoft, Uber and many database companies ask it, because it tests the ideas every other design leans on: partitioning, replication, consistency trade-offs and what happens when machines fail. In earlier lessons we used a database as a box. Now we build the box.
Step 1 · Requirements
- Functional:
put(key, value),get(key),delete(key). Values are small (up to about 100 KB, typically under 1 KB). - Non-functional: highly available (a shopping cart must accept writes even when servers fail), scales to billions of keys by adding machines, low latency (single-digit milliseconds), durable, and tunable consistency.
- Out of scope (say it): queries by value, joins, multi-key transactions, secondary indexes.
Step 2 · Estimates
- Data: 1 billion keys × 1 KB ≈ 1 TB; with 3 copies ≈ 3 TB, plus room to grow.
- Traffic: 100,000 reads/s and 20,000 writes/s. Every write goes to 3 replicas, so 60,000 replica writes/s.
- Machines: if one node comfortably serves about 10,000 operations/s and holds about 200 GB, we need roughly 15–20 nodes for traffic and storage, more for headroom. Nothing fits on one machine, so we must partition.
Step 3 · API
GET /kv/{key} → { value, version } // version = vector clock or timestamp
PUT /kv/{key} { value, version? } → { version } // pass the version you read, to detect conflicts
DELETE /kv/{key} → 204 // writes a "tombstone", removed later
Client options per request: consistency = ONE | QUORUM | ALLStep 4 · Design
Start with one server: an in-memory hash map plus a file on disk. It's fast and simple, until the data or traffic outgrows one machine, or that machine dies. Every idea below fixes one of those limits.
4a. Partitioning: which node owns a key?
Use consistent hashing, exactly as in the distributed cache lesson: hash each key onto a ring, and the first node clockwise owns it. Each physical node takes many virtual nodes on the ring, so data spreads evenly, and when a node joins or leaves only its neighbours' keys move. Bigger machines simply get more virtual nodes.
4b. Replication: keep 3 copies
Store each key on the owner and the next N − 1 distinct physical nodes clockwise: its preference list. Place those copies in different racks or availability zones, so one power or network failure can't take out every copy. There's no single leader: any replica can accept reads and writes, which keeps the store available.
4c. Consistency: quorums
A coordinator (whichever node got the request) sends a write to all N replicas but replies to the client once W of them confirm. A read asks replicas and replies once R answer, returning the newest version among them. The trick: if R + W > N, the read set and write set must overlap on at least one replica.
Quorums: N = 3, you pick W and R
Every replica has v1. Write v2, then read.
R + W = 4 > N = 3: any 2 replicas you read must include at least one of the 2 that took the write, so reads see the latest value (when no writes are lost to failures).
| Setting (N = 3) | Good for | Trade-off |
|---|---|---|
| W = 2, R = 2 | The usual default: overlap with good latency | Needs 2 replicas up for both reads and writes |
| W = 1, R = 1 | Fastest, always writable (logs, likes, metrics) | Reads can be stale until replicas sync |
| W = 3, R = 1 | Read-heavy data that must be fresh | One replica down blocks all writes |
| W = 1, R = 3 | Write-heavy data, rare fresh reads | Slow reads; one replica down blocks reads |
Quorums are why these stores call it tunable consistency: Cassandra lets you choose ONE, QUORUM or ALL per query, and DynamoDB offers eventually consistent or strongly consistent reads.
4d. Conflicts: two writes at once
Without a single leader, Riya's phone and laptop can update her cart on different replicas at the same moment. Which value wins?
| Approach | How it works | Risk |
|---|---|---|
| Last-write-wins (LWW) | Keep the value with the newest timestamp | Clocks drift: a real update can be silently lost |
| Vector clocks | Each version carries a counter per node; compare them to tell "newer" from "concurrent" | Concurrent versions (siblings) come back to the app to merge |
| CRDTs | Data types that merge automatically (counters, sets) | Only for data that fits those types |
Vector clocks for cart:riya v1 [A:1] phone adds "kurta" (written via node A) v2 [A:1, B:1] laptop adds "earrings" (via B, based on v1) v3 [A:2] phone adds "dupatta" (via A, also based on v1) v2 vs v3: neither is ≥ the other in every counter → CONCURRENT → return both; the app merges: kurta + earrings + dupatta → [A:2, B:1]
This is how Amazon's Dynamo paper kept shopping carts writable: a merged cart might bring back a deleted item now and then, but an “add to cart” is never lost. For most other data, LWW is simpler and fine.
4e. Failures: detect, cover, repair
- Gossip: every second, each node swaps its membership list (with heartbeat counters) with a few random nodes. News spreads to the whole cluster in a few rounds, with no central server. A node whose heartbeat stops growing is suspected dead.
- Sloppy quorum + hinted handoff (short outages): if replica C is down, the write goes to the next healthy node D with a hint: “this belongs to C”. When C returns, D hands the writes over. Writes keep succeeding.
- Read repair: when a read sees an old version on one replica, the coordinator sends it the newest value.
- Anti-entropy with Merkle trees (long drift): each replica builds a tree of hashes over its key ranges. Two replicas compare the root hashes; if they match, they're identical. If not, they walk down only the branches that differ, finding the few out-of-sync keys without sending everything.
4f. Storage on each node: the LSM tree
WRITE put("cart:riya", ...)
1. append to the commit log (disk, sequential) → survives a crash
2. insert into the memtable (memory, sorted) → ack to coordinator
3. memtable full → flush as an SSTable (immutable, sorted file on disk)
4. compaction merges SSTables in the background, dropping old versions and tombstones
READ get("cart:riya")
memtable → newest SSTable → older SSTables
each SSTable has a Bloom filter: "definitely not here" lets us skip the fileWrites are just sequential appends and memory inserts, which is why LSM stores take huge write volumes. Deletes write a tombstone (a “deleted” marker) that compaction removes later, so a deleted value can't come back from an old replica. The Bloom filters are the same trick as in the web crawler.
Step 5 · Scale and reliability
- Adding capacity: new nodes take virtual nodes on the ring and stream just those ranges from neighbours.
- Hot keys: one celebrity key can overload its replicas. Cache it in front, or split it (for example
views:post42#0..#9) and add the parts up on read. - Multiple regions: replicate to each region; serve local quorums (Cassandra's
LOCAL_QUORUM) so a request doesn't wait on another continent. - CAP: during a network partition you choose: keep accepting writes on both sides (available, fix conflicts later, the Dynamo way) or refuse on the minority side (consistent, the Raft/etcd way). This design picks availability.
- Monitoring: per-node latency (p99), hints waiting to be delivered, compaction backlog and repair progress.
| Real system | Model | Known for |
|---|---|---|
| Amazon DynamoDB | Managed, partitioned, replicated across zones | Serverless scale; eventual or strong reads per request |
| Apache Cassandra / ScyllaDB | Dynamo-style ring, LSM storage | Huge write throughput, tunable consistency, multi-region |
| Redis | In memory, primary + replicas | Microsecond reads; caches, sessions, counters |
| etcd / ZooKeeper | Raft / ZAB consensus (CP) | Small, critical config data that must be consistent |
🧠 PATH memory card
Remember the key-value store design for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
A big railway parcel office has counters arranged in a ring. Your parcel number decides which counter takes it, and the next three counters each keep a copy, so one closed counter never loses it. Sending needs two counter stamps and collecting needs two stamps, so the collector always meets at least one clerk who saw the latest parcel. Clerks write every parcel in a logbook first, then sort them onto shelves in quiet hours. If a counter is shut, the next one keeps your parcel with a note and hands it over when it reopens.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Ring, Three copies, Two stamps, Logbook then shelves”
- Ring of counters→Consistent hashing with virtual nodes
- Three copies→Replication N = 3 on the preference list
- 2 stamps to send, 2 to collect→Quorums W = 2, R = 2 (R + W > N)
- Logbook, then shelves→Commit log → memtable → SSTables + compaction
- Note for a shut counter→Sloppy quorum + hinted handoff
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Riya adds a kurta: the request reaches node D, which hashescart:riyaand finds replicas A, B, C. D sends the write to all three; A and B confirm (W = 2), so D replies OK while C catches up. Each node appends to its commit log and memtable. C then goes down; a new write is stored on E with a hint for C, and handed over when C returns. Riya's next read asks two replicas; at least one has the latest cart. ✓ - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 8 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Follow-up questions interviewers ask
- “How do you delete a key safely?” Write a tombstone with a version, replicate it like any write, and only purge it after every replica has seen it (after a grace period); otherwise an old replica could resurrect the value.
- “Range queries (all keys from a to f)?” Hash partitioning scatters neighbours. Use range partitioning (like HBase or Bigtable) or design keys so a partition key groups rows, with a sort key inside it (DynamoDB, Cassandra).
- “Strong consistency for one key?” Use a consensus protocol (Raft or Paxos) per partition, or lightweight transactions (compare-and-set). Slower, but linearizable.
Where to go next
You've built the storage that many other designs sit on. Next, build the other piece of infrastructure every big company runs: a durable, replayable stream of events in design a message queue (Kafka).
Key takeaways
- ✓Partition with consistent hashing and virtual nodes; replicate each key to N nodes across zones.
- ✓Quorums (R + W > N) give fresh reads; lower values trade consistency for speed and availability.
- ✓Resolve concurrent writes with last-write-wins or vector clocks (and app-side merges).
- ✓Handle failures with gossip, hinted handoff, read repair and Merkle-tree anti-entropy.
- ✓Each node stores data in an LSM tree: fast sequential writes, Bloom filters and compaction for reads.
Frequently asked questions
What is a distributed key-value store?
A database that stores data as key → value pairs (like a giant dictionary) spread across many machines. You can put, get and delete a value by its key. Amazon DynamoDB, Apache Cassandra, Riak and Redis are well-known examples. They trade rich queries (joins, filters on any column) for huge scale, low latency and high availability.
What is a quorum in a key-value store?
With N copies of each key, a write waits for W replicas to confirm and a read waits for R replicas to answer. If R + W > N, every read overlaps with the latest successful write on at least one replica, so the read can return the newest value. Common setting: N = 3, W = 2, R = 2.
How do key-value stores handle conflicting writes?
Two simple options: last-write-wins (keep the value with the newest timestamp, which is simple but can silently drop a write if clocks disagree) or versioning with vector clocks (detect that two writes happened concurrently and keep both, so the application or client merges them, as Amazon's shopping cart did in the Dynamo paper).
What is an LSM tree?
A log-structured merge tree, the storage engine behind Cassandra, RocksDB, LevelDB and many others. Writes go to an append-only commit log and an in-memory sorted table (memtable); when it fills up it's written to disk as an immutable sorted file (SSTable). Background compaction merges files. It makes writes very fast; reads check memory first and use Bloom filters to skip files.
Is a key-value store AP or CP in the CAP theorem?
It depends on the design. Dynamo-style stores (Cassandra, Riak, DynamoDB's original design) choose availability during a network partition and accept temporary inconsistency, with tunable quorums. Stores built on consensus such as Raft (etcd, ZooKeeper, Consul) choose consistency: a minority side of a partition stops accepting writes.
🧠 Quick check: key-value store
1. N = 3. Which W and R guarantee a read overlaps the latest write?
2. A replica is down for 10 minutes. Which mechanism gets its missed writes to it when it returns?
3. Two replicas drifted apart over weeks. How do they find the differences without comparing every key?
4. Why are LSM trees fast for writes?
Checking your access…