Design a Distributed Key-Value Store with Range Scan Support
System DesignModel answerLast updated
Design a horizontally scalable, fault-tolerant key-value store that supports high write throughput, low-latency reads, and efficient range scans across multiple data centers.
Distributed Key-Value Store with Range Scan Support
You are tasked with designing a persistent, distributed key-value store meant to run across multiple data centers. The system must handle heavy write traffic while keeping read latency low, and it must support both point lookups and range queries efficiently.
Functional Requirements
put(key, value)— insert or update a key-value pairget(key)— retrieve the value associated with a keydelete(key)— remove a key-value pair from the storescan(start_key, end_key)— return all key-value pairs whose keys fall within a given range, in sorted order
Non-Functional Requirements
- Availability: the system must keep serving requests even when individual nodes fail
- Scalability: the system should handle petabyte-scale data and millions of requests per second
- Consistency: choose a consistency model, state it explicitly, and justify the trade-offs
What your design should cover
- Partitioning strategy — how do you distribute data across the cluster, and how does the cluster handle nodes being added or removed?
- Storage engine — which on-disk data structure best fits the workload, and why?
- Replication and fault tolerance — how does the system survive node and zone failures without losing data?
- Client API and inter-node communication — what do the interfaces look like, and how do clients find the right node?
- Performance optimization — how do you make range scans efficient, and how do you manage background maintenance work like compaction?
Take roughly 45 minutes. Start by clarifying scale and constraints before drawing any architecture. Examiners will pay attention to how your partitioning choice interacts with range scans, so address that connection explicitly.
Hints
Hint 1
The scan requirement is a trap: if you partition by hashing keys, range queries must fan out to every node. Think about what partitioning strategy preserves key order.
Hint 2
For a write-heavy workload, compare how an LSM-tree and a B-tree handle disk I/O differently — specifically around sequential vs. random writes and read amplification.
Hint 3
Raft gives you a clean story for per-range replication and leader election, but synchronous cross-region quorums add real latency. Be prepared to discuss how to handle the multi-DC trade-off.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The hidden pivot in this problem is the scan requirement. Most candidates jump straight to consistent hashing because it is the familiar answer for distributed stores — but consistent hashing destroys key ordering, which means every range scan has to fan out to the entire cluster. A strong answer catches this early and lets it drive the partitioning decision.
1. Clarify Scale Before Drawing Anything
Pin down concrete numbers first. This signals structured thinking and bounds later decisions.
- Data volume: 1 PB logical. Keys under 1 KB, values averaging 1 KB → roughly 10¹² key-value pairs. At 3× replication: ~3 PB raw storage.
- Traffic: ~2M requests per second at peak, ~70% writes. Target p99 read latency under 10 ms within a region.
- Nodes: assuming 8 TB usable NVMe per node with 50% headroom for compaction → ~750 nodes across 3+ regions.
- Consistency model: per-key linearizability within a replication group, with snapshot-consistent scans. Rationale: users expect read-your-writes from a general-purpose store, and eventually consistent range scans are hard to reason about in application code. The explicit cost is a quorum round-trip on every write. Offer an opt-in stale read mode (served by followers) for latency-sensitive, conflict-tolerant workloads.
The alternative worth naming: a Dynamo-style leaderless store with tunable quorums (R + W > N) gives better write availability during network partitions, but pushes conflict resolution (vector clocks or last-writer-wins) onto the application. State this trade-off; interviewers want to see a deliberate choice, not a default.
2. API Design
put(key, value, [expected_version]) -> version
get(key, [consistency=STRONG|STALE]) -> (value, version)
delete(key) -> version // writes a tombstone, not a hard delete
scan(start, end, limit, page_token, [snapshot_ts]) -> (items[], next_token)
- Transport: gRPC/HTTP2 with protobuf for both client-to-server and server-to-server communication.
- Smart client library: caches the
key range → leader nodemap locally and routes each request directly to the right node, avoiding a proxy hop. OnNOT_LEADERorRANGE_MOVEDerrors, it refreshes the map and retries transparently. - Scans are paginated via a
page_tokenand pinned to asnapshot_ts, so a multi-page scan sees a consistent view even as writes continue.
3. Partitioning: Range Partitioning, Not Hash Partitioning
The keyspace is split into contiguous sorted ranges of roughly 256–512 MB each (thousands of ranges per node, millions total). A range splits when it grows past its size limit or exceeds a per-node load threshold; small cold neighbors merge.
A placement driver — a metadata service backed by its own Raft group — stores the authoritative range → replica set map. Clients and nodes consult it to route requests.
Cluster resizing: when a node joins, the placement driver migrates some ranges by adding a replica, catching it up from a snapshot, then dropping the old replica. Only ~1/N of the data moves, which matches the benefit of consistent hashing's virtual nodes, while preserving key order.
Trade-off to state explicitly: range partitioning creates hotspots on monotonic keys (e.g., timestamp-prefixed keys all landing on the most recent range). Mitigate this with load-based splitting, or let users hash-prefix keys when they do not need range scans. If scans were not required, consistent hashing with virtual nodes would be the simpler and more hotspot-resistant choice.
4. Storage Engine: LSM-Tree
The workload is write-heavy, which makes an LSM-tree (RocksDB/LevelDB-style) a better fit than a B-tree. B-trees perform random in-place page writes that cause write amplification on SSDs and suffer from page splits under load. LSM-trees convert all writes to sequential disk I/O.
Write path:
- Append to the write-ahead log (WAL); fsync with group commit to amortize the cost across concurrent writes.
- Insert into the in-memory memtable (a skiplist sorted by key).
- When the memtable reaches ~64 MB, flush it as an immutable SSTable to disk.
Read path:
- Check the active memtable.
- Check immutable memtables.
- Search SSTables newest-to-oldest. Each SSTable has a Bloom filter (~10 bits/key, ~1% false positive rate) and a sparse block index, so a cache-miss point read costs at most one disk seek. A block cache keeps hot data in memory.
Deletes and MVCC: a delete writes a tombstone rather than erasing data immediately. Keys are stored as (user_key, timestamp) tuples, which enables the snapshot isolation needed for consistent range scans.
5. Replication and Fault Tolerance
Each range runs as a Raft group with 3 replicas in different availability zones. For cross-region durability, promote to 5 replicas across 3 regions.
- Writes go to the range leader, which appends to the Raft log and acknowledges once a majority persists the entry.
- Strong reads are served by the leader while it holds a lease — no extra quorum round-trip needed.
- Stale reads can be served by any follower at a closed timestamp.
- Node failure: followers detect a dead leader via heartbeat timeout (~1–3 s) and elect a new one. If a node stays down beyond a threshold (~5 min), the placement driver triggers re-replication from healthy peers. Each lost range rebuilds from a different source in parallel, so recovery throughput scales with the cluster.
- Replica catch-up: a lagging replica replays the Raft log. One that has fallen too far behind receives an SSTable snapshot instead.
- Corruption detection: periodic Merkle tree comparison across replicas of each range catches silent disk corruption.
Multi-DC trade-off: synchronous cross-region quorums add 50–100 ms to write latency. An alternative is region-local Raft groups with asynchronous cross-region replication, accepting a small data loss window (RPO of a few seconds) in a regional disaster in exchange for lower normal-case write latency.
6. Range Scans and Compaction
Scans: because keys are range-partitioned, a scan touches only the contiguous ranges it spans. Those ranges are fetched in parallel with bounded concurrency. Within each node, a merging iterator across the memtable and SSTables yields keys in sorted order. Prefix Bloom filters, sequential read-ahead, and pushing the limit predicate down to storage all reduce wasted I/O. Scans execute at a fixed snapshot timestamp so they never block concurrent writes.
Compaction: leveled compaction keeps read amplification and space amplification low (~1.1×) at the cost of higher write amplification (10–30×). Tiered compaction reduces write amplification but hurts read performance. A practical default for write-heavy traffic is tiered compaction at the top levels (L0/L1) and leveled below. To protect foreground latency, rate-limit compaction I/O and run it at lower scheduling priority.
Common Mistakes
- Choosing hash partitioning without acknowledging that it breaks range scans.
- Picking a B-tree storage engine without discussing how its random-write pattern performs under heavy write load.
- Saying "eventual consistency" without specifying what anomalies that exposes to application code.
- Treating compaction as a footnote — it directly affects both write throughput and read latency and deserves explicit discussion.
- Skipping the multi-DC latency trade-off when synchronous replication is chosen.