System design interview: design a key-value store
A distributed key-value store keeps every value on several machines so it survives failures, and lets you choose per request how many replicas must answer before a read or write counts. The interview covers partitioning, replication with quorums, what happens when two writes to the same key race, how a node that was down catches up, and how each node stores data on disk efficiently.
By Evin JohnPublished 8 min read
1. Clarify the requirements
Start by asking what the store is for. A shopping cart, a session store and a user-profile store all fit, and each one tolerates different trade-offs between availability and consistency.
- Functional:
put(key, value),get(key),delete(key); keys up to a few hundred bytes, values up to about 1 MB; no queries across keys. - Non-functional: stays writable when machines and even a whole zone fail; low single-digit millisecond latency at the median; durable once acknowledged; grows by adding machines; consistency tunable per use case.
- Out of scope unless asked: range scans and secondary indexes, multi-key transactions, cross-region active-active replication.
2. Estimate the scale
Illustrative figures, stated as assumptions so the interviewer can change them.
| Quantity | Assumption | Result |
|---|---|---|
| Data | 100 TB of values, about 1 KB each | about 100 billion keys |
| Replication | N = 3 | about 300 TB stored |
| Disk per node | 4 TB, kept about 70% full for compaction headroom | about 2.8 TB usable, so about 107 nodes |
| Writes | 200,000 a second | 600,000 replica writes a second, about 5,600 per node |
| Reads | 600,000 a second with R = 2 | 1.2 million replica reads a second, about 11,200 per node |
Two things follow. The data set needs over a hundred machines, so partitioning and automatic rebalancing are not optional. And with that many machines, some are always failing or being replaced, so recovery has to be routine and automatic, not an incident.
3. Define the API
put(key, value, context=None, w=2) -> new context (version information)
get(key, r=2) -> [ (value, context), ... ] more than one if versions conflict
delete(key, context, w=2) -> writes a tombstone
context is opaque to the caller: pass back the one you read when you write,
so the store knows which version your write replaces.4. Sketch the data model
The store itself knows only bytes, but each stored record carries bookkeeping that the design depends on.
| Field | Purpose |
|---|---|
key | Hashed to find the replicas; stored for lookups and compaction |
value or tombstone | The data; a tombstone marks a delete so older replicas do not resurrect the value |
| version (timestamp or version vector) | Decides which of two copies is newer, or that they conflict |
expires_at (optional) | TTL support; expired records are dropped during compaction |
| checksum | Detects corruption on disk before a bad value is served |
5. The core decision: replication and quorums
Place nodes on a hash ring with many virtual points each (the sharding guide explains the ring). A key's replicas are the first N distinct physical nodes clockwise from its hash, chosen so they sit in different racks or zones. Any node can act as coordinator for a request: it forwards the write to all N replicas and answers the client once W of them confirm; for a read it asks the replicas and answers once R reply.
| R / W | Behavior | Fits |
|---|---|---|
| R = 2, W = 2 | Read and write sets always share a replica; tolerates one replica down for both | A balanced default |
| R = 1, W = 3 | Fast reads; a write fails if any replica is unreachable | Read-heavy data that changes rarely |
| R = 3, W = 1 | Fast, highly available writes; slow reads | Write-heavy logging-style data |
| R = 1, W = 1 | Fastest and most available; reads may be stale | Caches and data where staleness is harmless |
R + W > N means every read quorum overlaps every write quorum, so a read sees at least one copy of the latest acknowledged write. It is not full linearizability: concurrent writes, sloppy quorums during failures and clock-based conflict rules can still surprise you. Say that out loud; interviewers like hearing the limits of a rule.
When two writes race
Two clients can update the same key through different coordinators during a partition. Last-write-wins keeps the copy with the higher timestamp: simple, but it silently drops one write and depends on clocks. Version vectors (a counter per coordinating node) let the store tell "newer" from "concurrent". When versions are concurrent, the store returns both and the application merges them, for example by taking the union of two shopping carts.
def compare(a, b):
"""Compare two version vectors (dict node -> counter)."""
nodes = a.keys() | b.keys()
a_ahead = any(a.get(n, 0) > b.get(n, 0) for n in nodes)
b_ahead = any(b.get(n, 0) > a.get(n, 0) for n in nodes)
if a_ahead and b_ahead:
return "conflict" # concurrent writes: keep both, let the reader merge
if a_ahead:
return "a newer"
if b_ahead:
return "b newer"
return "equal"
print(compare({"n1": 2, "n2": 1}, {"n1": 1, "n2": 1})) # a newer
print(compare({"n1": 2}, {"n1": 1, "n2": 1})) # conflict6. The architecture
- Clients
- Ring-aware client library
- or load balancer
- Coordination
- Any node acts as coordinator
- Ring and membership from gossip
- Replicas
- N replica nodes in different zones
- Repair
- Hinted handoff
- Read repair
- Merkle-tree anti-entropy
- Per-node storage
- Commit log
- Memtable
- Sorted files + Bloom filters
- Compaction
- Write path on a replicaAppend the record to the commit log and sync it (or batch syncs every few milliseconds), insert into the in-memory sorted table, acknowledge. When the memtable fills, write it to disk as an immutable sorted file.
- Read path on a replicaCheck the memtable, then the sorted files from newest to oldest. A small Bloom filter per file says "definitely not here" for most files, so a read touches few of them.
- CompactionMerge sorted files in the background, keeping the newest version of each key and dropping tombstones once every replica has seen them.
- MembershipNodes gossip their view of who is alive every second or so. A node that stops responding is marked suspect, and requests route around it.
7. Scale it and keep replicas in sync
- Sloppy quorum and hinted handoff. If a replica is down, the coordinator writes to the next healthy node on the ring with a hint naming the intended owner. When the owner returns, the hint is delivered and deleted. Writes stay available through short outages.
- Read repair. When a read gets different versions from replicas, the coordinator writes the newest one back to the stale replicas. Hot keys repair themselves this way.
- Anti-entropy with Merkle trees. For keys nobody reads, replicas periodically compare hash trees over their key ranges. Matching roots mean nothing to do; otherwise they descend only into the branches that differ and exchange those keys.
- Adding capacity. A new node takes over some virtual points and streams the matching key ranges from the current owners before it starts serving them.
- Hot partitions. A single very hot key still lands on N nodes. Callers can put a distributed cache in front for reads; for writes, split the key at the application level.
8. What breaks, and what you do about it
| Failure | Effect | Mitigation |
|---|---|---|
| One replica down for minutes | Fewer replicas answer | Sloppy quorum with hinted handoff keeps writes available; hints delivered on return |
| Node lost for good | Its ranges have one fewer copy | Operator or automation removes it; ranges re-replicate to other nodes from surviving copies |
| Network partition | Both sides may accept writes to the same key | Version vectors expose conflicts after healing; or require strict quorums and refuse writes on the minority side |
| Deleted value comes back | An old replica missed the delete and repairs others | Tombstones kept longer than the longest expected outage, removed only after repair |
| Clock skew | Last-write-wins picks the wrong winner | Version vectors, or hybrid logical clocks if timestamps are kept |
| Disk corruption | Bad bytes served | Checksums per record; on mismatch, read from another replica and repair |
9. Trade-offs to discuss
- Leaderless or leader per partition. Leaderless replication (any replica accepts writes) stays available during failures but needs conflict handling. A leader per partition with consensus gives simple, consistent semantics at the cost of a failover pause and a write path through one node.
- LSM tree or B-tree. LSM storage turns random writes into sequential ones and suits write-heavy loads, but reads may check several files and compaction uses disk bandwidth. B-trees read faster and more predictably but write in place.
- Conflict rule. Last-write-wins is easy for callers and loses data under concurrency; version vectors keep everything and push merging to the application.
- Strict or sloppy quorums. Sloppy quorums keep writes available during failures but weaken the overlap guarantee until hints are delivered.
- Durability versus latency. Syncing the log on every write is safest; batching syncs every few milliseconds is much faster and risks the last few milliseconds of writes on a power loss of all replicas at once.
10. How to talk through it in the interview
Fictional example
- Interviewer
- You said N = 3, R = 2, W = 2. So reads are always up to date?
- Candidate
- A read always overlaps the replicas of the last write that was acknowledged, so it sees that version. But if two writes are concurrent, the read can see both, and if we used a sloppy quorum during an outage, the overlap can be with a stand-in node. So I would call it read-your-acknowledged-writes in normal operation, not linearizable.
- Interviewer
- What does the client do with two versions?
- Candidate
- For a cart, merge them and write back with both contexts, which tells the store the conflict is resolved.
A 45-minute plan for this prompt: 5 minutes on the API and the availability question, 5 on sizing, 5 on partitioning, 15 on replication, quorums and conflicts, 10 on recovery (hinted handoff, read repair, Merkle trees) and the storage engine, and 5 on trade-offs. If the interviewer cares more about the storage engine, swap the recovery time for LSM details such as compaction strategies.
- Name N, R and W explicitly and say what each setting buys.
- Never claim R + W > N makes the store strictly consistent.
- Mention tombstones before the interviewer asks how deletes survive repair.
Practicing this design with Natively
Rehearse the quorum explanation until it is short and exact. During a mock interview on a call, Natively listens to both sides, writes the transcript as you talk and can offer points to cover when a question arrives; comparing them with your answer quickly shows whether you mentioned tombstones or sloppy quorums. It can also draw the ring and replica layout as a diagram when you ask. The transcript and notes are saved, so you can go back to the minute where the conflict explanation fell apart.
Questions people ask
What does R + W > N mean in a key-value store?
With N replicas, a write waits for W acknowledgements and a read for R replies. If R + W is greater than N, every read set overlaps every write set, so a read sees at least one copy of the latest acknowledged write. It does not make the store linearizable on its own.
How does a distributed key-value store handle conflicting writes?
Either last-write-wins, which keeps the copy with the higher timestamp and can silently drop a write, or version vectors, which detect concurrent writes and return both versions so the application can merge them. The choice depends on whether losing a write is acceptable.
What is hinted handoff?
When a replica is down, the coordinator writes to another healthy node with a hint naming the intended owner. When the owner comes back, the hint is delivered and deleted. It keeps writes available during short outages, at the cost of a weaker overlap guarantee until hints arrive.
Why do key-value stores use LSM trees?
An LSM tree appends writes to a log and an in-memory table, then flushes sorted immutable files and merges them in the background. That turns random writes into sequential ones, which suits write-heavy workloads. Bloom filters per file keep reads from checking every file.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
