Design a Sharded Replicated Key-Value Store for 1M Ops/Sec
System DesignModel answerLast updated
Design a distributed key-value database serving 1M ops/sec over 50M records with low tail latency, five-nines availability, tunable consistency and durable acknowledged writes.
Problem
Several microservices in a large platform need a shared store for session context, service state and live counters. Design a distributed NoSQL key-value store that handles heavy read and write traffic with very low latency.
Required operations
get(key)returns the value stored under a key.put(key, value)creates or overwrites a value.delete(key)removes a record.
Targets
- Throughput: 1,000,000 operations per second at peak.
- Latency (p99): under 5 ms for reads and under 10 ms for writes.
- Availability: 99.999%, surviving the loss of single nodes and whole racks.
- Consistency: selectable per request, from eventual to strong.
- Durability: once a write is acknowledged, it must not be lost.
Sizing assumptions
- 50,000,000 records in total.
- Average key is 64 bytes, average value is 1 KB.
- Peak mix: 800,000 reads/sec (80%) and 200,000 writes/sec (20%).
What to cover in your answer
- Capacity estimate: memory, disk, network bandwidth and a node count.
- Partitioning and routing: how keys map to nodes, how hot spots are avoided, and how clients find the right node.
- Replication and consistency: replica placement, failure handling, and quorum settings (R + W > N).
- Single-node storage engine: compare an in-memory hash table, an LSM-tree and a B-tree against the latency and durability goals.
- Trade-offs: bandwidth versus consistency versus operational complexity.
Hints
Hint 1
Compute the data size first. It is small enough to fit in RAM several times over, so ask what actually limits the cluster size: CPU and network per node, not capacity.
Hint 2
Count replica-level operations, not client operations. A quorum read touches multiple replicas and every write touches all N, so the per-node load is higher than 1M divided by node count.
Hint 3
Place the N replicas of a key in different racks, and let the client route directly using a cached partition map to avoid an extra proxy hop on the p99 path.
Hint 4
Define 'acknowledged' precisely: persisted in a write-ahead log on W replicas. Group commit lets you do that without one fsync per write.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify first
- Access pattern: point lookups only, no range scans or secondary indexes. Hash partitioning is therefore fine.
- Consistency: chosen per request (
ONE,QUORUM,ALL). Counters must stay correct under concurrent increments. - Durability: "acknowledged" means written to a disk log on at least W replicas, not merely held in memory.
- Topology: one region, three racks or availability zones. Cross-region replication is out of scope unless asked.
2. Capacity planning
Storage and memory
- Raw data: 50M x (64 B + 1,024 B) is about 54 GB.
- With index, version metadata and allocator overhead (about 1.5x): roughly 80 GB per copy.
- Replication factor N = 3 gives about 240 GB of RAM cluster-wide, which is modest.
- On disk, a write-ahead log plus compacted files with about 2x space amplification gives roughly 500 GB total. Trivial for NVMe.
Network
- Reads: 800K x about 1.1 KB is about 880 MB/s, or 7 Gbps of client egress.
- Writes: 200K x 1.1 KB is about 220 MB/s in. Fanning out to 3 replicas adds about 660 MB/s, or 5.3 Gbps internally.
- Quorum reads fetch one full value and digests from the others, so extra bandwidth is small.
- Total is about 15 Gbps cluster-wide, spread over many nodes with 10-25 Gbps NICs.
Node count (bound by throughput, not data)
- Replica operations per second: reads at R = 2 give 1.6M, writes applied on 3 replicas give 600K, total about 2.2M.
- A tuned in-memory node handles about 100K ops/s at low tail latency, so about 22 nodes.
- Run at 50-60% utilization to survive a rack loss and spikes: about 36 nodes, 12 per rack.
- Each node holds about 7 GB, so a 64 GB machine can cache everything.
Takeaway: CPU and network size the cluster, not storage.
3. API
get(key, consistency=QUORUM) -> (value, version)
put(key, value, expected_version?, consistency=QUORUM) -> version
delete(key, consistency=QUORUM) # writes a tombstone
increment(key, delta) # optional, for counters
Returning a version enables compare-and-set.
4. Partitioning and routing
- Placement: consistent hashing with about 256 virtual nodes per machine, or a fixed set of logical partitions (for example 4,096) mapped to nodes. Fixed partitions make rebalancing simple: whole partitions move, and adding a node shifts roughly 1/n of the data.
- Replica placement: the 3 replicas of a key go on distinct nodes in different racks, so a rack failure never removes a quorum.
- Routing: a smart client caches the partition map (from etcd/ZooKeeper or gossip), hashes the key and contacts a replica in one hop. A stale map triggers a redirect carrying the newer map version.
- Hot spots: hashing plus virtual nodes evens out ordinary load. For individual hot keys, use client-side or node-side caching, extra read replicas for that key, or split a counter into sharded sub-counters that are summed on read.
5. Replication and consistency
Use leaderless, Dynamo-style replication with N = 3. The coordinator sends to all replicas and waits for R or W acknowledgements.
| Mode | R | W | Property |
|---|---|---|---|
| Eventual | 1 | 1 | Lowest latency, stale reads possible |
| Overlapping quorum | 2 | 2 | R + W > N, read and write sets intersect |
| Read-optimized | 1 | 3 | Fast reads, but one slow replica stalls writes |
Limits of quorums: overlap does not equal linearizability. Concurrent writes, sloppy quorums and partial failures can still show anomalies. For keys that need strict guarantees (CAS, service state), offer a per-partition Raft group with a leader, serving reads via leader lease.
Conflicts: attach a hybrid logical clock for last-write-wins, or vector clocks if the application wants siblings. Counters must not use read-modify-write under LWW; use a PN-counter CRDT (per-replica increments merged by sum) or route increments through the Raft leader.
Failure handling:
- Gossip with a phi-accrual detector marks nodes down.
- A sloppy quorum writes to the next healthy node with a hint, and hinted handoff replays it on recovery.
- Background anti-entropy (Merkle trees) repairs divergence; read repair fixes stale replicas opportunistically.
- A permanently lost node's partitions are re-replicated from survivors.
6. Storage engine
Write path: append to the WAL, group-commit with an fsync about every 1 ms (hundreds of writes per fsync), insert into the memtable, then acknowledge. With W = 2, the ack means durable on two disks. One fsync plus one intra-datacenter round trip fits within the 10 ms write budget.
Engine comparison
| Option | Strengths | Weaknesses |
|---|---|---|
| In-memory hash + WAL + snapshots | Fastest reads | Slow restart replaying the log; RAM-bound |
| B-tree | Good reads | Random-write amplification at 200K writes/s |
| LSM-tree | Sequential writes, Bloom filters, fast recovery | Compaction overhead |
Choice: an LSM-tree with a block cache larger than the per-node dataset, so reads are memory lookups well under 1 ms and writes are sequential. Rate-limit compaction I/O to protect p99.
Deletes: write tombstones and purge them only after a grace period longer than the anti-entropy cycle. Otherwise a stale replica can resurrect a deleted key.
7. Trade-offs
- Consistency vs. latency: QUORUM reads wait on the slower of two replicas. Mitigate with speculative retry to the third replica once the first exceeds its p95, and with digest reads to save bandwidth.
- Replication factor vs. cost: N = 3 triples RAM and write traffic. N = 5 tolerates two failures but costs more cross-rack bandwidth.
- Leaderless vs. leader-based: leaderless has better availability and no failover gap but needs conflict resolution. Raft gives linearizability but has short unavailability during elections.
- Operational complexity: smart clients, gossip, repair jobs and multiple consistency modes add operational surface. Keep a single default (QUORUM) and make the stronger or weaker modes opt-in.
Common mistakes
- Sizing the cluster by data volume (about 80 GB) instead of by throughput.
- Counting 1M client ops instead of about 2.2M replica ops.
- Claiming R + W > N gives strong consistency.
- Acknowledging writes before they reach a disk log.
- Placing all replicas in one rack, or purging tombstones too early.
- Implementing counters as read-modify-write with last-write-wins.