Design a Key-Value Store
How to design a distributed key-value store: partitioning, quorum replication, conflict resolution, repair, and what interviewers ask.
On this page
A key-value store supports put(key, value) and get(key). On one machine it is a hash map backed by a log. A distributed key-value store spreads the data over many machines that can fail, so the design has to decide where each key lives, how many copies to keep, what a read returns while the copies disagree, and how the copies are repaired.
Interviewers ask this question to see whether you can state precisely what the system guarantees; "eventually consistent" alone is not an answer. The approach follows A Framework for Any Design and builds on Consistent Hashing and Replication.
Clarify the problem
Design a distributed key-value store.
How large are keys and values, do we need anything beyond get, put and delete, and how much data and traffic should it handle?
Keys are up to 256 bytes and values up to 1 MB, usually around 10 KB. You only need get, put and delete. Assume 2 billion keys, and at peak 150,000 reads and 50,000 writes a second.
If a node or a network link fails, should the store reject writes, or accept them and resolve conflicts afterwards? Think of a shopping cart.
Accept them, because a lost "add to cart" costs money. Some callers will want stronger reads, though.
Then I will favour availability, let each request choose its consistency level, and never lose an acknowledged write. I will assume one region with three zones.
- Functional:
get,putanddeleteby key, where the caller chooses how many replicas must answer. - Non-functional: writes are accepted while some replicas are down, p99 latency is under 10 ms within the region, an acknowledged write survives the loss of any one node at the default setting, and the cluster grows without downtime.
- Out of scope: range scans, secondary indexes, transactions and multiple regions.
Estimate the scale
How much disk do the replicated values need in total?
- 2 billion keys, about 10 KB each
- 3 copies of every key
- Ignore index and compaction overhead
Show the working
- Raw: 2 × 109 × 104 B = 2 × 1013 B = 20 TB
- Replicated: 20 TB × 3 = 60 TB
Estimate 60 TB (anything from 20 TB to 200 TB is a good answer)
Keep each 4 TB node half full so there is room for compaction and growth: 60 TB ÷ 2 TB per node = 30 nodes.
About how many replica operations does each node handle at peak?
- 150,000 reads and 50,000 writes a second at peak
- Each write goes to 3 replicas and each read asks 2
- 30 nodes, load spread evenly
Show the working
- Replica reads: 150,000 × 2 = 300,000 a second
- Replica writes: 50,000 × 3 = 150,000 a second
- (300,000 + 150,000) ÷ 30 = 15,000 a second per node
Estimate 15 thousand/s (anything from 5 thousand/s to 50 thousand/s is a good answer)
The 30 nodes needed for disk space can already handle this traffic, so disk size, not traffic, sets the node count.
Write the three operations. What should get return when replicas disagree, and what must the caller send back with put?
Compare with a model answer
get can return several values, called siblings, together with an opaque context that describes their versions. The caller sends that context back with its next put.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
get(key, read = "quorum")
-> { values: [v1, ...], context } one value normally; several after a conflict
-> NOT_FOUND
-> UNAVAILABLE fewer than R replicas answered in time
put(key, value, context?, write = "quorum")
-> OK W replicas have it in their commit logs
-> UNAVAILABLE fewer than W confirmed in time (it may
still be stored on some replicas)
-> TOO_LARGE key over 256 B or value over 1 MB
delete(key, context?, write = "quorum") writes a tombstone
read / write levels: "one" | "quorum" | "all" (R or W out of N = 3)The API decision worth arguing is the context. Without it, the write with the newest timestamp wins and one of two concurrent writes silently disappears. With it, the store can tell the difference between a write that replaces what the client read and two writes made in parallel, and it can hand both back to be merged. The context is optional, and a put without one uses last-write-wins.
What does a stored record contain besides the key and value? What does each node need to know about the cluster?
Compare with a model answer
A record also holds a version vector, a timestamp and a tombstone flag. Each node knows the hash ring and, through gossip, which nodes are alive.
Model the data
record (on disk, sorted by key)
key up to 256 B
value up to 1 MB, about 10 KB on average
version version vector, e.g. {B: 3, C: 1}, about 16 B per entry
timestamp 8 B, used only for last-write-wins and tombstone expiry
tombstone 1 bit: this key was deleted
cluster metadata (same on every node, a few MB)
ring node -> its virtual-node positions on the hash ring
membership node -> zone, status (up / suspected / leaving), heartbeatEvery operation reads or overwrites a single key, and each node receives about 5,000 replica writes a second to random keys. A log-structured merge tree (LSM tree) suits this pattern because it turns random writes into sequential appends, as described in Indexing. The cost is that a read may have to check several files.
Sketch a put. Which node receives it, how does that node find the key's owners, when does it reply "done", and what happens if an owner is down?
Compare with a model answer
There is no leader. The node that receives the request hashes the key, finds the next 3 distinct nodes on the ring, sends the write to all 3 and replies once 2 have confirmed. If an owner is down, a stand-in node keeps the write as a hint and passes it on when the owner returns.
High-level design
Any node can coordinate any request, because every node holds the ring. The client library also caches the ring, so it can send a request straight to one of the key's replicas, and a node that receives a request for a key it does not own simply forwards it. A key's preference list is the first 3 distinct servers found clockwise from the key's hash, chosen from 3 different zones. Ring positions of a server already chosen are skipped, so one zone outage cannot take all three copies.
request and replyasynchronous message
- N
- 3
- W
- 2
- acks
- 0
1The client calls
put("cart:42", [milk]), and the node that receives the call acts as coordinator.- N
- 3
- W
- 2
- acks
- 0
2The coordinator hashes the key and walks clockwise around the ring. The first 3 distinct servers are B, C and D.
- N
- 3
- W
- 2
- acks
- 0
3It sends the write to all 3 replicas in parallel but waits for only 2.
- N
- 3
- W
- 2
- acks
- 3
4Each replica appends the write to its commit log and confirms. B and C confirm first, which equals W, so the client receives OK. The version is
{B: 1}. D confirms a moment later.- N
- 3
- R
- 2
- answers
- 2
5A later
get("cart:42")with R = 2 uses the first 2 answers. B and D both hold{B: 1}, so the coordinator returns [milk].- N
- 3
- W
- 2
- acks
- 2
6D stops answering and a new write arrives. B and C receive it. E, the next healthy node on the ring, receives a copy tagged for D, called a hinted handoff.
- N
- 3
- W
- 2
- acks
- 3
7B and C confirm, so W = 2 is met by real owners. If only one owner had been up, E's copy would have counted toward W, which is a sloppy quorum: writes stay available but reads become less reliable.
8D comes back 10 minutes later. E sees this through gossip, sends D the hinted writes and deletes them.
Deep dives
Partitioning with consistent hashing
The simplest way to place keys is to compute hash(key) mod number_of_nodes. Adding or removing one node changes the result for almost every key, so nearly all the data has to move. Consistent Hashing places nodes and keys on a ring, so a node joining or leaving only affects the keys next to it.
With one position per node the ring is unevenly loaded, so each server gets about 100 positions, called virtual nodes. For a replicated store the main benefit is parallel rebuilds: a dead node's 2 TB is split into small ranges across the other 29 servers. If each of them streams its share at 100 MB/s, the rebuild takes 2 × 1012 ÷ (29 × 108) ≈ 690 seconds, or about 11 minutes.
Replication and tunable quorums
Each key is stored on N = 3 replicas. A write waits for W of them to confirm and a read waits for R of them to answer. Replication explains why R + W > N means every read set overlaps every write set.
W = 2, R = 2 is the default. A read overlaps every acknowledged write, so it normally sees the latest value, and one replica can be down.
W = 1, R = 1 is the fastest setting, and writes succeed even when two replicas are down. The cost is that a read can miss a write that was just acknowledged, which is acceptable for caches and session data.
W = 3, R = 1 gives fast reads that see every acknowledged write, but one replica being down blocks all writes to its keys, which contradicts the availability goal.
R + W > N does not give linearizability, and interviewers often push on this. Two concurrent writes can both succeed. A write that failed with UNAVAILABLE can still appear on one replica. A sloppy quorum removes even the overlap guarantee, because if stand-in nodes such as E supplied the W confirmations, the real owners may not have the write until the hint is delivered. See CAP and Consistency.
Resolving conflicts
A store that accepts writes during failures will sometimes receive two updates to the same key from clients that do not know about each other. The tracer shows a cart edited from two devices while two replicas cannot reach each other.
- B holds
- milk
- C holds
- milk
1Both replicas hold [milk] with version
{B: 1}, which came from one write coordinated by B.- B holds
- milk, eggs
- C holds
- milk
2The link between B and C fails. The phone reads [milk] with
{B: 1}and adds eggs. B increases its own counter, so the version becomes{B: 2}.- B holds
- milk, eggs
- C holds
- milk, bread
3The laptop had also read [milk] with
{B: 1}. It adds bread through C, and the version becomes{B: 1, C: 1}.- siblings
- [milk, eggs] and [milk, bread]
4The link heals.
{B: 2}has the larger B counter and{B: 1, C: 1}has the larger C counter, so neither version contains the other. The writes were concurrent, and the store keeps both as siblings.- B holds
- milk, eggs, bread
- C holds
- milk, eggs, bread
5The next read returns both carts, the cart code merges them by union into [milk, eggs, bread], and the client writes that back with the merged context. B makes the version
{B: 3, C: 1}, which covers both siblings and replaces them.
There are three ways to handle such conflicts.
Last-write-wins keeps the value with the newest timestamp and discards the other. It silently drops one of two concurrent writes, which in the example would lose the eggs or the bread, and clock differences between nodes decide which one. It suits keys with one writer or harmless lost updates.
Version vectors with siblings, as in the tracer, detect concurrency exactly and never lose a write. The cost is that every caller must merge siblings, and the vectors grow with the number of coordinators.
Conflict-free data types (CRDTs) let the store do the merge itself, because the value is a counter, a set or a map whose merge rule is built in. This only applies to those data shapes, and removals need extra metadata.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Last-write-wins | One value per key and no work for callers. | Silently drops concurrent writes, and clock skew decides which one. | Values written once, keys with a single writer, or data where a lost update is harmless. |
| Version vectors and siblings Usual default | Never loses a write, and the application merges using what it knows about the data. | Every caller must handle siblings, and vectors grow with the number of coordinators. | Data such as carts and settings, where concurrent updates matter and callers can merge. This is my default. |
| CRDTs | The store merges correctly without client code. | Limited to counters, sets and similar types, and removals need extra metadata. | The value is a counter or a set and you want merging without client code. |
Detecting failures and repairing data
No central monitor decides which nodes are dead. Each node gossips a heartbeat counter to a few random peers every second. If a node's counter has not increased for about 10 seconds, its peers mark it as suspected, because from outside a slow node and a dead node look the same.
A suspected node triggers no data movement. Streaming 2 TB to replace a node that reboots in a minute would do harm. Its ranges are rebuilt only after an operator, or automation with a long timeout, declares the node gone. Three mechanisms keep the replicas in sync:
- Hinted handoff covers short outages. A node down for 10 minutes misses 5,000 writes a second × 600 s = 3 million writes, about 30 GB, which stand-ins hold until it returns. Stand-ins keep hints only for a limited time, such as a few hours, so a node that stays down longer is caught up by anti-entropy.
- Read repair fixes a stale replica that a read notices, by sending it the newer version.
- Anti-entropy handles whatever the first two missed. Two replicas compare Merkle trees, which are trees of hashes over sub-ranges of keys, and descend only into branches whose hashes differ. With about 200 million keys per node and 215 leaves, each leaf covers about 6,000 keys. One wrong key then costs a walk down 15 levels and a sync of one leaf.
The storage engine and deletes
A write goes to the commit log and a sorted in-memory table. A full table is written out as an immutable sorted file, and compaction merges these files. A read checks memory and then the files from newest to oldest, and a Bloom filter on each file lets it skip files that definitely lack the key.
Deletes need care. A delete writes a tombstone, a marker saying the key is deleted, and compaction may remove the tombstone only after a grace period, typically several days. If a replica missed the delete and the tombstone is purged before repair reaches that replica, anti-entropy copies the old value back and the deleted key returns. The grace period must be longer than the longest outage the cluster repairs from.
Bottlenecks and failures
At 10 times the load there are 600 TB of replicated data and 2 million client operations a second, which needs about 300 nodes. Consistent hashing handles the growth, but two problems remain. Hot keys do not spread, because a popular key still lives on only 3 nodes. Compaction debt builds up when writes arrive faster than files are merged, and every read then has to check more files.
| When this fails | What happens | What you do |
|---|---|---|
| One node, briefly | Its keys have 2 of 3 replicas, so W = 2 and R = 2 still succeed. | Hinted handoff catches the node up when it returns. |
| One node, permanently | Its 2 TB of data exists only as 2 copies. | Declare it gone, and the other 29 nodes rebuild it in about 11 minutes. |
| A whole zone | Every key loses one of its 3 copies. | Quorums keep working on the other two zones. |
| A network partition | Both sides may accept writes to the same keys. | Version vectors keep both writes as siblings, and callers merge them afterwards. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | Shards by hash, adds replicas and says "eventually consistent", and needs prompting to explain what happens when replicas disagree. |
| Mid | Uses virtual nodes, explains R + W > N, and describes repair. |
| Senior | Ties each choice to the availability requirement, says what quorums do not guarantee, and separates temporary from permanent failure. |
With N = 3, W = 2 and R = 2, is this strongly consistent?
No, it is not linearizable. Every read overlaps every acknowledged write, so it normally sees the latest value. However, concurrent writes can both succeed and become siblings, a failed write can still show up on one replica, and with a sloppy quorum a read can miss a write until the hint is delivered.
So when would you not use this design?
I would not use it for an account balance or a uniqueness check. Those need one leader per key range with consensus, and writes pause for a few seconds during failover, which is the right trade-off for that kind of data.
Follow-up questions
How would you run it in two regions?
Keep N replicas in each region, acknowledge a write after a quorum in the local region, and replicate to the other region asynchronously. Version vectors detect conflicts between regions, and a lost region takes its unreplicated writes with it.
How does a new node join without downtime?
The new node takes about 100 positions on the ring, and the current owners stream it the ranges it now owns while new writes for them also go to it. The old owners delete their copies once it has them.
One key gets 100,000 reads a second. What do you do?
With R = 2 that is 200,000 replica reads spread over only 3 nodes, about 67,000 each, which is more than 4 times the 15,000 a node normally handles. Cache the value for a second in the coordinators, or read with R = 1 if slightly stale data is acceptable.
What happens when a client retries a put after a timeout?
The client cannot tell whether the first attempt was stored, so it sends the same put with the same context again. Because a put overwrites the value rather than adding to it, storing the same value twice is harmless, and the second write supersedes the first. A change that must not be applied twice, such as an increment, needs a unique request id that the store deduplicates.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".