Build a Durable, Replicated Key-Value Store Step by Step
System DesignModel answerLast updated
Design a store with put, get and delete that starts as a single-node storage engine and grows into a partitioned, replicated cluster with defined consistency and failure handling.
You are asked to design a storage service that maps keys to values. Clients must be able to:
- put(key, value): store or overwrite a value
- get(key): return the current value, or report that the key is absent
- delete(key): remove a key
The scope is deliberately open. Begin on one machine and then extend the design so it runs across many machines. Decide, and say aloud, which guarantees you are offering.
Nothing is specified about data volume, key and value sizes, traffic, latency goals, consistency needs, or range scans. Ask about these or state explicit assumptions.
Your answer should cover:
- Requirements and assumptions: API, sizes, read/write mix, durability, consistency, whether ordered scans are needed.
- Single-node storage engine: how writes become durable, how reads stay fast, how deletes and disk space are handled.
- Partitioning: how keys are spread across nodes and how the cluster grows or shrinks with limited data movement.
- Replication: the consistency model and the quorum or consensus mechanism that implements it.
- Failure handling and operations: node crashes, leader failover, recovery, rebalancing, hot keys, monitoring.
Justify the trade-offs you choose, including what happens during a network partition.
Hints
Hint 1
Pin down requirements first: does the data fit in RAM, must it survive restarts, is point lookup enough, and is stale data acceptable after a write?
Hint 2
For a single node, think about an append-only log for durability plus an in-memory structure for recent writes that is periodically flushed to sorted immutable files. Ask how a delete can be represented in an append-only world.
Hint 3
For the cluster, consider hashing keys onto a ring with virtual nodes, replicating each key to several successive nodes, and choosing read and write quorum sizes R and W against replication factor N. Decide explicitly between favoring consistency or availability under partition.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and assumptions
I would confirm these first and otherwise assume:
- API:
put,get,delete; point lookups only (no range scans), optional TTL. - Keys up to ~256 B, values up to ~100 KB, typically ~1 KB.
- Total data ~50 TB, so it cannot fit on one machine; ~100k reads/s and ~20k writes/s at peak.
- Latency: p99 under ~10 ms for reads and writes within a region.
- Durability: an acknowledged write must survive a single node loss.
- Consistency: tunable. Default to strong-enough reads via quorums, with an option for eventual consistency on cheap reads.
If range scans were required, I would choose range partitioning and a sorted engine rather than hash partitioning. I note that now because it changes the partitioning choice later.
2. Single-node storage engine
A write-heavy workload suits an LSM-tree design:
- Write path: append the record to a write-ahead log (sequential, fsync per batch, or group commit), then insert into an in-memory sorted structure (the memtable). Acknowledge after the log write. This gives fast, durable writes.
- Flush: when the memtable reaches a size limit (e.g. 64 MB), write it out as an immutable sorted file (SSTable) and drop its WAL segment.
- Read path: check the memtable, then SSTables from newest to oldest. To avoid touching many files, keep a Bloom filter per file and a sparse index plus block cache. A miss usually costs no disk reads.
- Deletes: write a tombstone marker, since files are immutable. Reads treat a tombstone as "absent".
- Compaction: background merging of SSTables discards overwritten values and, once tombstones are older than every file that could hold the key, the tombstones themselves. Leveled compaction gives lower read amplification and space use; size-tiered gives lower write amplification. Choose by workload, and throttle compaction so it does not hurt foreground latency.
- Recovery: on restart, replay the WAL into a fresh memtable.
Alternative: a B-tree engine gives predictable reads and in-place updates but worse write throughput and more random I/O. For a read-dominant workload with scans, it is a reasonable pick.
3. Partitioning
- Use consistent hashing: hash each key onto a ring; each node owns the arc preceding its position. Adding or removing a node moves only about 1/N of the keys.
- Give each physical node many virtual nodes (e.g. 128-256) so load is even and a failed node's load is spread across many peers.
- Clients or a thin routing layer learn the ring layout from a metadata service or via gossip, so requests go straight to the right node.
- Alternative: a fixed number of partitions (e.g. 4096) assigned to nodes by a coordinator. Rebalancing then means moving whole partitions, which is simpler to operate and monitor.
4. Replication and consistency
Replicate each partition to N = 3 nodes (on distinct racks or zones).
Option A, leaderless quorums (Dynamo style):
- A write goes to N replicas and succeeds after W acks; a read queries R replicas.
- If R + W > N (e.g. N=3, R=2, W=2), reads overlap the latest write.
- Conflicts from concurrent writes are resolved with version vectors or last-write-wins timestamps; read repair and background anti-entropy (Merkle trees) fix divergence.
- Hinted handoff and sloppy quorums keep writes available when replicas are down, at the cost of weaker guarantees.
- Favors availability under partition.
Option B, leader-based consensus (Raft or Paxos per partition):
- One leader per partition orders writes and replicates the log to followers; commit happens on a majority.
- Gives linearizable writes, and linearizable reads if served via the leader (with lease or read-index).
- The minority side of a partition cannot accept writes. Favors consistency.
My default: Option B if the requirement is "a get after a successful put always sees it". Option A if availability and write latency matter more and clients tolerate conflicts. I would state this CAP choice explicitly.
5. Failure handling and operations
- Failure detection: heartbeats or gossip with a suspicion timeout, avoiding flapping on short hiccups.
- Node crash: with Raft, followers elect a new leader in seconds; with quorums, other replicas keep serving. The replacement node streams data from peers (snapshot plus log tail), throttled to protect live traffic.
- Adding nodes: new virtual nodes or partitions are assigned, data streams over, and ownership switches only after catch-up.
- Hot keys: cache hot values at a front tier, split reads across replicas, or add key-level salting for known hot keys. Monitor per-partition load and split hot partitions.
- Large values: store big blobs in object storage and keep a pointer in the store.
- Disk corruption: checksum blocks and WAL entries; repair from replicas.
- Observability: p50/p99 latency, compaction backlog, replication lag, under-replicated partitions, disk and memory use, and error rates, with alerts on the leading indicators (compaction backlog, replication lag).
- Backups: periodic snapshots plus the log for point-in-time recovery; cross-region replication asynchronously for disaster recovery.
Trade-offs summary
| Decision | Choice | Cost |
|---|---|---|
| Engine | LSM-tree | Read and space amplification, compaction work |
| Partitioning | Consistent hashing, virtual nodes | No efficient range scans |
| Replication | Raft per partition (or quorums) | Write latency / weaker guarantees respectively |
| Deletes | Tombstones | Space held until compaction |
Common mistakes
- Jumping straight to sharding without describing durability on one node.
- Forgetting tombstones, so deleted data reappears from older files or stale replicas.
- Using
hash(key) % N, which reshuffles almost all keys when N changes. - Claiming strong consistency and high availability under partition at once.
- Ignoring hot keys, rebalancing cost, and compaction's effect on tail latency.
- Choosing quorum values without checking R + W > N.