Design a Distributed Key-Value Store
Understanding the Problem
🗝️ What is a distributed key-value store? A key-value store maps an opaque key to an opaque value, and offers little more than
put,getanddelete. A distributed one spreads those keys across many machines and keeps several copies of each, so it can hold far more data than one server and keep serving when servers die. DynamoDB, Cassandra, Riak and Redis Cluster all sit in this family.
You will hear this question in a few forms: "design a Dynamo-style key-value store," "design DynamoDB," "design a Redis-like store," or simply "design a distributed database." They are the same problem. The core is always partitioning, replication and what happens when machines fail. "Redis-like" shifts the emphasis toward in-memory storage and microsecond latency, and "distributed database" invites questions about richer queries. We'll design the general store first and cover the in-memory variant as its own deep dive.
Functional Requirements
The API of a key-value store is tiny, so the functional requirements are short. Agree on them quickly with your interviewer and spend the time on the non-functional side.
Core Requirements
- Users should be able to
puta value under a key,getit back anddeleteit. - Users should be able to set an optional time-to-live (TTL) on a key, after which it disappears.
- Users should be able to choose, per read, between a fast eventually consistent read and a strongly consistent one, and to make conditional writes ("only write if the version is still 7").
Below the line (out of scope)
- Secondary indexes and queries on value contents. Values are opaque bytes.
- Multi-key transactions. (We'll mention how you would add them.)
- Range scans across keys in sorted order. A hash-partitioned store doesn't support these cheaply; a range-partitioned one does, and we'll say where that choice is made.
Non-Functional Requirements
Ask your interviewer for the scale. For our design:
Core Requirements
- The system should store 100 TB of data: about 100 billion keys with an average value of 1 KB, with values up to 400 KB.
- The system should serve 1M reads/sec and 500k writes/sec at peak, with p99 latency under 10 ms for single-key operations.
- The system should be highly available (99.99%) and keep accepting reads and writes when a node, or a whole availability zone, fails.
- The system must be durable: once a write is acknowledged, it is never lost.
- The system should scale horizontally: adding machines adds capacity, with no downtime and no manual data moves.
Below the line (out of scope)
- Multi-region active-active replication. We'll design for one region with three availability zones.
- Encryption, access control and billing.
The back-of-the-envelope math tells us where the difficulty is. 100 TB with three replicas is 300 TB on disk. If each storage node has about 4 TB of NVMe SSD and we keep it half full to leave room for compaction and growth, we need roughly 150 nodes. Spread the traffic across them and each node sees about 7,000 reads/sec and, counting all three replicas, 10,000 writes/sec of 1 KB each, which is about 10 MB/s. That is comfortable for one NVMe drive.
So throughput per machine is not the problem. The problem is that the data is spread over 150 machines, and at that size something is always broken. With a few percent of servers failing each year, plus disk failures, kernel patches and deploys, a node in this cluster is down or restarting most days. Failure is the normal case, and almost every decision below is about handling it.
A good opening line in this interview: "The single-node version is a hash map and a log file. Everything interesting comes from having 150 of them and assuming two are broken right now."
The Set Up
Planning the Approach
We'll start with a single node that stores data correctly, then partition the data across nodes, then replicate each partition. The deep dives cover rebalancing, the consistency model, failure detection and repair, hot keys and the in-memory (Redis-like) variant.
Defining the Core Entities
- Item: a key, a value, a version and an optional expiry time. The version is what makes conditional writes and conflict detection possible.
- Partition: a slice of the key space (a range of hash values) that is stored, replicated and moved as a unit. It's the unit of scaling.
- Storage Node: one machine that holds replicas of many partitions.
- Replica Group: the three nodes, one per availability zone, that hold copies of one partition.
- Partition Map: the metadata that says which partitions exist, which nodes hold them and, if there is one, which replica is the leader.
API or System Interface
PUT /kv/{key}
headers: If-Match: <version> // optional, conditional write
body: { value: <bytes>, ttlSeconds?: number }
-> 200 { version }
-> 412 { currentVersion } // condition failed
GET /kv/{key}?consistency=eventual|strong
-> 200 { value, version } | 404
DELETE /kv/{key}
headers: If-Match: <version> // optional
-> 204
In practice clients talk to the store through a thin SDK over a binary protocol (gRPC or a custom TCP protocol), not JSON over HTTP, because serialization overhead matters at a million requests per second. The shape of the API is the same.
High-Level Design
1) Users should be able to put, get and delete a value by key
Start with one machine. The tempting version is an in-memory hash map, but that loses everything on a crash and can't hold 4 TB. We need a storage engine that is durable and works on disk.
The standard choice for write-heavy key-value stores is a log-structured merge tree (LSM tree), used by RocksDB, LevelDB, Cassandra and many others:
- A write is appended to a write-ahead log (WAL) on disk and fsynced, then inserted into an in-memory sorted structure, the memtable. Only then is it acknowledged. Appends are sequential, which disks are very good at.
- When the memtable reaches a size limit (say 64 MB), it is written out as an immutable sorted file, an SSTable, and a fresh memtable takes over. The WAL segment covering it can then be deleted.
- A read checks the memtable, then the SSTables from newest to oldest. Each SSTable has a Bloom filter (about 10 bits per key gives roughly a 1% false positive rate), so most files that don't contain the key are skipped without a disk read, and a sparse index finds the right block in the files that might.
- A background compaction process merges SSTables, keeping only the newest version of each key, so reads don't have to look through hundreds of files.
A delete can't erase the key from immutable files, so it writes a tombstone: a marker that says "this key is deleted as of version N." Reads that find the tombstone return 404, and compaction eventually drops both the tombstone and the older values under it.
The alternative is a B-tree (InnoDB, Postgres, BoltDB), which updates pages in place. B-trees give more predictable read latency, while LSM trees turn random writes into sequential ones and compress better. With a write rate this high, an LSM tree is a reasonable default. Either answer is fine if you can say why.
This node works, but one machine can't hold 100 TB, can't serve 1.5M operations a second, and takes all the data with it when it dies.
2) Users should be able to store more data than one machine holds
We need to split keys across nodes. Hash the key (say with a 64-bit MurmurHash or xxHash) and use the hash to pick a partition. Hashing spreads keys evenly, even when keys like user:1, user:2, user:3 are very similar.
The naive way to map hash to node is hash(key) % N. It works until you add node N+1, at which point almost every key changes owner and must move. Instead we split the hash space into many fixed partitions (more on this in the deep dives) and keep a partition map that assigns each partition to nodes. Adding a node means moving some partitions to it, not rehashing everything.
Who does the lookup? A request router layer holds a cached copy of the partition map, hashes the key, and forwards the request to the right storage node. The map itself lives in a small, strongly consistent metadata store (etcd or ZooKeeper), which routers watch for changes. Routers are stateless, so we can run as many as we need behind a load balancer. A smart client SDK can also cache the map and skip the router hop, which saves a network round trip; that's what Cassandra drivers and Redis Cluster clients do.
If a router's cached map is stale (the partition moved), the storage node rejects the request with "not mine, try node X," and the router refreshes its map and retries. This keeps the hot path free of metadata lookups while staying correct.
This is the point where the "range scans" decision happens. If we partitioned by key ranges instead of hashes, a scan over user:1000 to user:2000 would hit one or two partitions. Range partitioning makes scans cheap but makes hot spots likely (sequential keys all land on the newest partition). We picked hash partitioning because our API is single-key.
3) Users should be able to choose strong or eventual reads and make conditional writes
Each partition lives on one node right now, so a node failure makes its keys unavailable, and a disk failure loses them. We replicate each partition to a replica group of three nodes, one in each availability zone. Losing a node or a whole zone still leaves two copies.
The simplest replication scheme that supports both read modes is a leader per partition. Writes go to the partition's leader, which assigns the next version number, appends the write to its log, and sends it to the two followers. The leader acknowledges the client once a majority (itself and at least one follower) has the write durably on disk. That is exactly what a consensus protocol like Raft or Multi-Paxos gives us, and it's how DynamoDB and CockroachDB handle each partition.
With that in place:
- A strong read goes to the leader, which has every acknowledged write. (The leader must be sure it is still the leader; we'll cover leases in the deep dives.)
- An eventual read goes to any replica, usually the nearest or least loaded. It might miss the last few milliseconds of writes, and costs a fraction as much, because two thirds of the cluster's replicas can serve it.
- A conditional write is checked by the leader: since every write to the partition passes through it in order, "write only if version is 7" is a simple comparison against its current state. No locks are needed.
TTL fits in the same model. The expiry time is stored with the item. Reads check it and treat expired items as missing, and compaction physically removes them later. No timer per key is needed, which matters with 100 billion keys.
Potential Deep Dives
1) How do we partition the data and rebalance it as the cluster grows?
The partition map decides who owns what. The way we assign keys to partitions and partitions to nodes determines how much data moves when the cluster changes.
Bad Solution: Hash Modulo the Number of Nodes
Approach
node = hash(key) % N. No metadata, every client can compute the owner.
Challenges
Going from 150 to 151 nodes changes the owner of about 150/151 of all keys, so nearly all 300 TB has to move. During that move, reads miss and the network is saturated. This scheme only works for fixed-size clusters, and ours isn't.
Good Solution: Consistent Hashing with Virtual Nodes
Approach
Place nodes on a hash ring (the space 0 to 2^64). A key belongs to the first node clockwise from its hash. Adding a node only takes over the keys between it and its predecessor, about 1/N of the data. To keep the load even, each physical node takes many positions on the ring, called virtual nodes, so a new node takes small slices from many existing nodes rather than one big slice from one neighbor. Replicas go on the next distinct nodes clockwise, skipping nodes in the same zone. This is the scheme from the original Dynamo paper, covered in more detail in consistent hashing.
Challenges
The partition boundaries are tied to node positions, so adding a node changes the boundaries, and the data to move has to be found by scanning key ranges inside existing files. The unit being moved isn't a clean file. Balancing is also only statistical: with too few virtual nodes the load is uneven, and with too many the metadata and repair work grow.
Great Solution: Many Fixed Partitions, Assigned by a Placement Service
Approach
Split the hash space into a fixed, large number of partitions up front, far more than nodes. Say 16,384 partitions of about 6 GB each at today's 100 TB. Each node holds about 330 partition replicas. Redis Cluster uses the same idea with 16,384 hash slots; Riak and Couchbase use fixed partitions too.
A placement service (a leader-elected controller that writes to the metadata store) decides which three nodes hold each partition, respecting zones and balancing by disk use and load, not only by count. Adding a node means the controller moves whole partitions to it, one at a time:
- The new node copies a snapshot of the partition's SSTables from an existing replica, then catches up on the log since the snapshot.
- Once caught up, it joins the replica group as a fourth member.
- The controller removes one of the old replicas and updates the partition map.
Partitions don't have to stay fixed in size forever. When one grows too large or too hot, the controller splits it in two along its hash range, as DynamoDB and CockroachDB do. Splitting is cheap if the new halves stay on the same nodes at first and move later.
Challenges
We now run a control plane, and it has to be correct: a bug that assigns a partition to the wrong nodes, or removes the last good replica, loses data. Moves have to be rate-limited so they don't eat the bandwidth that client traffic needs. The upside is that every move is a clean, bounded unit, and the controller can make smart decisions (avoid the node that's at 90% disk) that a ring can't.
If your interviewer pushes on "why not just consistent hashing," the answer is control. Consistent hashing decides placement with math. A placement service decides it with knowledge of disk usage, load and zones, and can split hot partitions. Large managed systems tend to end up with the second.
2) How do we replicate writes, and what consistency do we get?
This is the heart of the question. There are two families of designs, and you should know both.
Bad Solution: Asynchronous Primary-Replica
Approach
Each partition has a primary. The primary acknowledges a write as soon as it's in its own log and ships it to replicas in the background. If the primary dies, a monitor promotes a replica.
Challenges
Acknowledged writes can be lost: anything the primary accepted but hadn't shipped yet is gone when a replica is promoted. That breaks our durability requirement. Worse, if the old primary was only partitioned away and not dead, both may accept writes for a while (split brain), and the store ends up with two histories. Redis's default replication works like this, which is one reason it's usually treated as a cache and not a system of record.
Good Solution: Leaderless Quorums (Dynamo Style)
Approach
There's no leader. With N = 3 replicas, the client's coordinator sends a write to all three and waits for W acknowledgments, and sends a read to all three and waits for R responses, returning the newest version. If R + W > N, every read set overlaps every write set in at least one replica, so a read sees the latest acknowledged write. N=3, W=2, R=2 is the common balanced choice. W=1 and R=1 gives the fastest, weakest mode, and a per-request choice of R gives us the eventual-versus-strong knob.
To stay available when replicas are down, Dynamo uses a sloppy quorum: if one of the three home replicas is unreachable, the write goes to a stand-in node with a hint saying where it really belongs. When the home node comes back, the stand-in hands the data over (hinted handoff).
Without a leader, two clients can write the same key at once on different replicas, so the store needs a way to resolve conflicts:
- Last-write-wins (LWW): each write carries a timestamp and the highest one wins. Simple, and what Cassandra does, but it silently drops one of two concurrent writes, and clock skew between machines can make an older write win.
- Vector clocks: each version carries a counter per writer, which lets the store tell "B replaced A" from "A and B happened concurrently." Concurrent versions are both kept and returned to the client to merge, as Dynamo did with shopping carts.
- CRDTs: data types (counters, sets) whose merges always converge, so the store can merge automatically.
Challenges
Quorums give a "sees the latest write" guarantee only in the easy cases. Sloppy quorums break the overlap (the write went to a stand-in your read didn't ask), concurrent writes need conflict handling, and a write that reached only one replica before failing can show up in some reads and not others. Conditional writes are especially hard: "write if version is 7" can't be checked atomically when there's no single place that orders writes, so Cassandra had to add Paxos-based lightweight transactions for it, at several times the cost of a normal write. Leaderless is the right call when availability matters more than anything and the data tolerates merges.
Great Solution: Consensus per Partition, with Leases
Approach
Run a small Raft (or Multi-Paxos) group per partition, as in the high-level design. The leader orders all writes, so versions are a simple increasing number per key and conditional writes are trivial. A write commits once a majority has it on disk, so losing any one node, or one zone, never loses an acknowledged write. If the leader dies, the followers elect a new one in a few hundred milliseconds to a couple of seconds, and the Raft rules guarantee the new leader has every committed write.
For strong reads, the leader must know it is still the leader, or a deposed leader that hasn't noticed could serve stale data. Rather than asking a majority on every read, the leader holds a time-based lease: followers promise not to elect anyone else for, say, 2 seconds after their last heartbeat, so a leader with an unexpired lease can answer reads alone. Leases depend on clocks not drifting much over a few seconds, which is a safe assumption with NTP, and safer still with bounded clock error.
Eventual reads go to any replica. Followers may lag by a few milliseconds, which is exactly the trade the client asked for.
Challenges
Each partition's writes go through one leader, so a hot partition is limited by one machine (we'll handle that in deep dive 4). During a leader election, writes to that partition stall for a second or two. And with 16,384 partitions there are 16,384 Raft groups; heartbeats must be batched per node pair rather than per group, or the heartbeat traffic alone becomes significant. These are well-understood engineering problems, and in return we get linearizable single-key operations with no conflict resolution at all.
| Leaderless quorum | Consensus per partition | |
|---|---|---|
| Write availability | Accepts writes with any replicas up (sloppy quorum) | Needs a majority of the partition's replicas |
| Consistency | Tunable, conflicts possible | Linearizable per key |
| Conditional writes | Expensive (extra Paxos round) | Cheap (leader checks) |
| Failover | None needed | Election, a second or two of write stall |
| Examples | Dynamo, Cassandra, Riak | DynamoDB, CockroachDB, TiKV |
Say which one you're picking and why. For a general-purpose store with conditional writes and strong reads in the requirements, consensus per partition is the stronger answer. If your interviewer stresses "writes must always succeed, even during a partition," the leaderless design is the better fit, and you should say that it costs you conflict resolution.
3) How do we detect failures and repair replicas?
Replication only helps if the system notices failures and puts the copies back.
Detecting failures. Within a replica group, Raft heartbeats already tell followers when the leader is gone and trigger an election. For the cluster as a whole, every storage node sends a heartbeat to the placement service (or gossips with peers, as Cassandra does with its phi-accrual failure detector). We separate two thresholds:
- Briefly unreachable (seconds to minutes): a restart or a network blip. Do nothing beyond the leader election. The node will catch up from its peers' logs when it returns.
- Gone (say 10-30 minutes, or a disk reported dead): declare the replica lost and re-replicate its partitions elsewhere.
Reacting too fast is expensive: re-replicating a node's 2 TB of data because of a 2-minute reboot moves 2 TB for nothing.
Re-replicating. When a node is declared dead, each of its ~330 partitions is down to two copies. The placement service picks a new node for each, and the new replica copies from one of the surviving two. Because the partitions are spread across the whole cluster, its 2 TB is rebuilt by many nodes in parallel, maybe 100 sources and 100 destinations each moving 20 GB, which takes minutes rather than the hours it would take to copy one disk to one disk. Fast rebuilds matter: the window when a partition has only two copies is the window when a second failure hurts.
Catching silent divergence. Replicas can drift even without visible failures: a bug, a bit flip, a missed message. Two tools catch it:
- Read repair: when a read touches several replicas and sees different versions, it writes the newest version back to the stale ones.
- Anti-entropy with Merkle trees: each replica builds a hash tree over its key range, where each leaf hashes a small range of keys and each parent hashes its children. Two replicas compare root hashes. If they match, the whole partition is identical; if not, they descend only into the subtrees that differ. That finds a handful of differing keys among millions while exchanging a few kilobytes of hashes. A background job runs it on every partition every few days.
Tombstones need care here. If a replica was down when a delete happened, and the tombstone has already been compacted away on the others, anti-entropy will see the old value on the returning replica and "repair" it back into existence. The rule is to keep tombstones longer than the longest time a replica can be down without being rebuilt. Cassandra's gc_grace_seconds (10 days by default) exists for exactly this reason.
Checksums everywhere. Every SSTable block and log entry carries a checksum, verified on read. A replica with a corrupt block treats it as missing and refetches from a peer, rather than serving bad data.
4) How do we handle hot keys and hot partitions?
Hashing spreads keys evenly, but it can't spread a single key. If one celebrity's profile is read 200k times a second, the three replicas of its partition take all of it.
Bad Solution: Provision Every Node for the Peak
Approach
Size the whole cluster so that any partition can handle the worst hot key.
Challenges
It means paying for 100x the capacity you need everywhere, for a problem that hits one partition at a time.
Good Solution: Split Hot Partitions and Spread Reads
Approach
The storage nodes report per-partition request rates. When a partition is hot, the placement service splits it and moves the halves to separate nodes, so two leaders share the load. For read-heavy hot spots, route eventual reads across all replicas rather than just the nearest, which triples the capacity without any other change. DynamoDB's "adaptive capacity" does a version of this, splitting partitions that stay hot.
Challenges
Splitting only helps when the load is spread across many keys in the partition. A single hot key lands in one half and is no better off. Splits also take time to settle, so they don't help with a spike that lasts 30 seconds.
Great Solution: Hot-Key Caching and Write Sharding
Approach
For a single hot key on reads, put a small in-memory cache in the request routers. Each router keeps the few hundred most-requested keys for a second or so. With 50 routers, a key read 200k times a second becomes about 50 reads a second to the storage node. This is only valid for eventual reads, and the one-second staleness bound should be documented.
For a single hot key on writes (a global counter, say), there's no store-side trick that keeps one key linearizable at unlimited write rates. The fix belongs in the data model: the application spreads writes over counter#0 to counter#9 and sums them on read. Mention it as guidance you'd give to the application team, and note that counters like this are covered in depth in the likes counter design.
Challenges
A router cache is one more layer of staleness, so it has to stay off for strong reads. Write sharding pushes complexity to clients. Both are worth it only for the handful of truly hot keys, so detect them (sample requests in the routers, count with a heavy-hitters sketch) rather than applying them everywhere.
Per-tenant admission control belongs here too. In a multi-tenant store like DynamoDB, each table or tenant gets a token-bucket rate limit at the router, so one customer's hot key throttles that customer with a clear error, instead of slowing down every tenant that shares the node.
5) What changes if we need a Redis-like in-memory store?
If your interviewer asks for "a Redis-like store," the target is sub-millisecond latency and rich in-memory data types (lists, sets, sorted sets), with a smaller data set. The design changes in a few specific places.
- Storage engine. Data lives in RAM in hash tables and specialized structures, so there's no LSM tree or Bloom filter on the read path. A single node can do on the order of 100k+ operations a second on one core. Redis runs commands on a single thread, which makes every command atomic without locks and makes Lua scripts a cheap way to do multi-step operations. The cost is that one slow command (
KEYS *on a big database) blocks everyone. - Durability. RAM loses everything on a crash, so the node writes either periodic snapshots (fork and dump the whole data set) or an append-only file of every command. Fsyncing the append-only file on every write is safe but slow; the usual setting fsyncs once a second, which can lose up to a second of writes. That's a product decision, and you should say it out loud.
- Replication. Replication is asynchronous from a primary to replicas, with a monitor (Redis Sentinel, or the cluster itself) promoting a replica if the primary dies. As in deep dive 2, that can lose acknowledged writes. If an in-memory store must not lose writes, put a consensus log underneath it, which is what systems like Amazon MemoryDB do with a durable multi-zone log.
- Partitioning. Redis Cluster uses 16,384 fixed hash slots (
CRC16(key) mod 16384), assigned to primaries. Clients cache the slot map and get aMOVEDreply when they guess wrong, and anASKreply while a slot is being migrated. Keys that must be operated on together can be forced into the same slot with a hash tag, like{user:42}:cartand{user:42}:profile. - Memory limits. RAM is the expensive resource, so the store needs a policy for when it's full: reject writes, or evict keys. Eviction policies (LRU, LFU, TTL-based) are covered in the distributed cache design.
The cost comparison is worth doing out loud. Our 100 TB with three replicas in RAM is 300 TB of memory, which is thousands of large servers. In memory, the same data set costs many times what it does on SSD, which is why a Redis-like store usually holds the hot working set and a disk-based store holds everything.
Final Design
The main flows:
- A client SDK hashes the key and sends the request to a request router (or, with a smart client, straight to the right node). The router checks the tenant's rate limit and looks up the partition in its cached partition map.
- A write goes to the partition's leader. The leader checks any condition (
If-Match), assigns a version, appends to its Raft log and WAL, and replicates to the two followers in other zones. Once a majority has it on disk, the leader applies it to its memtable and acknowledges the client. - A strong read goes to the leader, which answers from its memtable and SSTables while holding a valid lease. An eventual read goes to any replica, and hot keys may be served from the router's short-lived cache.
- Each node flushes memtables to SSTables and compacts them in the background, dropping overwritten values, expired items and old tombstones.
- The placement service watches node heartbeats and partition sizes and load. It splits hot or large partitions, moves partitions to new nodes, and re-replicates the partitions of nodes that are declared dead. All of its decisions are recorded in the metadata store, which routers watch.
- Anti-entropy jobs compare Merkle trees between replicas and repair any differences.
What is Expected at Each Level?
Mid-level
You should get to a design with hash-based partitioning and three replicas, explain why hash % N is a problem and reach for consistent hashing. You should know the basic quorum idea (R + W > N) and be able to say what happens to reads and writes when one replica is down. Knowing what an LSM tree is, at the level of "log, memtable, sorted files, compaction," is a plus rather than a requirement.
Senior
You should compare leaderless quorums with leader-based replication and pick one for stated reasons, including how conflicts are resolved and what that means for conditional writes. Expect to explain the storage engine in some depth (WAL, memtable, SSTables, Bloom filters, tombstones), how a router finds a partition and recovers from a stale map, and how the system detects and repairs a failed node. You should bring up hot keys on your own.
Staff+
You should treat this as an operations problem as much as a data structure problem. Expect to discuss the control plane (who decides placement, how its decisions are made safe), how fast a dead node's data is rebuilt and why that sets your real durability, tombstone lifetimes and resurrected data, leases and clock assumptions, and per-tenant isolation in a shared cluster. You should be able to say how the design shifts if the interviewer changes one requirement, such as "writes must succeed during a network partition" or "it needs to be in memory," and what you'd give up in each case.