Designing a Distributed Key-Value Store
Difficulty: Beginner–Intermediate Topics: Consistent Hashing, Replication, LSM Tree, Quorum Asked at: Amazon, Google, Meta, Microsoft, Databricks · Prerequisites: Consistent Hashing, CAP Theorem, and Merkle Trees
1. Understanding the Problem
A key-value store is the simplest database: give it a key, get back a value. Think of it as a giant distributed dictionary. You PUT(key, value) to store data and GET(key) to retrieve it. No complex queries, no joins, no schemas.
Real examples: Redis (in-memory, sub-ms reads), DynamoDB (millions of req/sec), Cassandra (wide-column), etcd (Kubernetes config store).
Why is this asked? A single-node hashmap is trivial. Distributing it across machines teaches partitioning, replication, consistency, and failure handling - the core of distributed systems.
2. Naive First Cut
flowchart LR
CLIENT["Client"]
SERVER["Single Server<br/>HashMap in memory"]
CLIENT --> SERVER
A single server with an in-memory hashmap. PUT adds to the map, GET retrieves.
Why this breaks:
- Memory limit - one server has maybe 64GB RAM. Your data might be 10TB.
- Single point of failure - server crashes, all data gone
- No scalability - can’t handle more reads by adding machines
- Data loss - in-memory means a restart wipes everything
- No availability - maintenance = downtime
The rest of the doc evolves this into a production-grade distributed store.
3. Prior Art We’re Drawing From
- Amazon DynamoDB (Dynamo Paper) - Introduced consistent hashing with virtual nodes, vector clocks for conflict resolution, and tunable consistency (W, R, N quorum). The foundational paper for distributed KV stores. (Amazon Dynamo Paper)
💡 A quorum is a minimum number of copies that must agree. W is how many must confirm a write, R how many are read, and N how many copies exist - three dials this design hands to the caller rather than fixing itself. - Google Bigtable / LevelDB - Pioneered the LSM-tree storage engine (memtable → SSTable → compaction) that powers most modern KV stores. (Bigtable Paper)
💡 The three words are the whole idea: a memtable is a sorted buffer in memory, an SSTable is that buffer written out to disk as an immutable sorted file, and compaction is the background job that merges those files back together. - Apache Cassandra - Combines Dynamo’s partitioning with Bigtable’s storage model. Apple runs 160K+ Cassandra nodes. (Cassandra Docs)
- etcd / Raft - Shows how strong consistency works in a distributed KV store using Raft consensus. Used by Kubernetes. (etcd.io)
💡 Raft is an algorithm a group of machines uses to elect one leader and agree on a single ordered list of changes. It buys strong consistency at the cost of needing a majority alive, which is the opposite trade from the quorum dials above.
4. Functional Requirements
Core (Top 3)
- PUT(key, value) - store a key-value pair, overwriting if it already exists
- GET(key) - retrieve the value for a given key
- DELETE(key) - remove a key-value pair
Below the Line
- Range queries (scan keys between A and B)
- TTL / automatic expiry
- Atomic compare-and-swap (CAS)
- Batch operations
5. Non-Functional Requirements
Core
| Non-functional requirement (NFR) | Target |
|---|---|
| Scalability | Handle 10TB+ data across many machines, scale horizontally |
| Availability | 99.99% - tolerate node failures without downtime |
| Latency | Sub-10ms P99 for reads and writes |
| Tunable consistency | Let users choose between strong and eventual consistency per operation |
💡 P99 is the latency 99% of requests beat. “Tunable consistency” means the caller decides per request whether to wait for the copies to agree - that choice is what FR3 builds.
Below the Line
- Multi-region replication
- Encryption at rest
- Access control per key
6. Scale Estimation (Back-of-Envelope)
- Write QPS (queries per second): 500K writes/sec
💡 Back-of-envelope estimation is the rough arithmetic you do before picking anything, so each component is chosen against a number. Learn more → - Read QPS: 1M reads/sec (read-heavy workload)
- Storage: 10TB total data, 3x replication = 30TB raw
- Latency target: < 10ms P99
7. Core Entities
- Key - a unique string identifier (e.g.,
user:42,session:abc) - Value - arbitrary bytes (JSON, protobuf, raw text). Up to a few MB.
- Node - a machine in the cluster that owns a portion of the keyspace
- Partition - a range of keys assigned to a specific node
- Replica - a copy of a partition on a different node for durability
8. API / System Interface
PUT /v1/data/{key}
Body: { value: <any>, ttl?: 3600 }
Response: 200 OK { version: 42 }
GET /v1/data/{key}
Response: 200 { value: <any>, version: 42 }
DELETE /v1/data/{key}
Response: 204 No Content
That’s it. The simplicity is the point - no SQL, no query language, just CRUD by key.
Security note: Authentication via API key or JSON Web Token (JWT). Rate-limit per client to prevent abuse.
9. High-Level Design
Let’s build this incrementally, one requirement at a time.
FR1: PUT(key, value) - Storing Data Across Multiple Machines
The first problem: we have more data than fits on one machine. So split it across many, and we need a rule for which node owns which key.
Take the obvious rule: node = hash(key) % num_nodes. Hash the key, divide by the number of
nodes, use the remainder. It is one line, it spreads keys evenly, and a lookup is arithmetic
rather than a directory consultation. Build that.
New components:
- Client / Router - hashes the key, takes the modulus, forwards to that node. Either a smart client library or a thin routing tier.
- Storage Nodes - each owns a slice of the key space. Writes land in a local on-disk store with a B-tree index, which is what any embedded database gives you by default.
💡 A B-tree is the ordinary database index: a sorted tree on disk, so a lookup is a few page reads. Keeping it sorted is what makes reads cheap and, as Deep Dive 2 shows, writes expensive. - Coordinator Service - tracks which nodes are alive and how many there are, since the router needs
num_nodesto compute anything at all.
💡 Knowing which machines are currently alive is its own problem - the cluster finds out by having every node send a periodic heartbeat and treating silence as failure.
flowchart LR
C["Client"]
R["Router<br/>hash mod num nodes"]
N1["Node 1"]
N2["Node 2"]
N3["Node 3"]
N4["Node 4"]
COORD["Coordinator<br/>live node count"]
C -->|"1. PUT key value"| R
R -->|"2. Remainder picks the owner"| N2
N2 -->|"3. Insert into local B-tree"| N2
N2 -->|"4. ACK"| R
R -->|"5. ACK to client"| C
COORD -->|"6. Supplies num nodes"| R
Step-by-step flow for PUT:
- Client calls
PUT key=user:42 value={name: "Alice"} - Router computes
hash("user:42") % 4→ 1, so Node 2 owns this key - Router forwards the write to Node 2
- Node 2 inserts into its local B-tree-indexed file and fsyncs
💡fsyncforces the operating system to actually put the bytes on the physical device rather than leaving them in a buffer. It is the step that makes a write survive a power cut, and it is also the slow step. - Node 2 ACKs the router, which ACKs the client
Why hash the key rather than range-partition it? Range partitioning — A-F on one node, G-M on the next — keeps sequential keys together, which matters if you need range scans. We do not: the API is single-key GET and PUT. And ranges create hotspots, because real key distributions are nowhere near uniform across the alphabet. Hashing trades away an ordering we never use for a distribution we need.
What we have deliberately left broken. Keys are spread across the cluster and every lookup is one hop. Three things are wrong, and the first turns a routine operation into an outage:
- Changing the node count remaps almost everything.
num_nodesis inside the formula, so adding a fifth node to four changes the answer for most keys. A key stays put only ifhash % 4 == hash % 5, which holds for 4 of every 20 hashes — so 80% of 1 billion keys, 800 million of them, now resolve to a node that has never seen them. The data is intact and unreachable, and the cluster serves misses until it is rebuilt. Adding capacity is an outage. That is Deep Dive 1. - A B-tree is the wrong structure for this write rate. Step 4 is a random insert into a sorted on-disk structure: read a page, modify it, sometimes split it, fsync. Several random I/Os per write, against a 500K writes/sec requirement. That is Deep Dive 2.
- One node owns each key, so one crash loses data outright. There is no second copy anywhere, and no amount of partitioning creates one. That is what FR2 is for.
FR2: GET(key) - Reading Data with High Availability
If we only store each key on one node, a single machine failure means data loss. We need replication.
New concept: Replication Factor (N). Each key is stored on N nodes (typically N=3). The primary node replicates to the next N-1 nodes clockwise on the ring.
New components:
- Replica Nodes - for each key, 2 additional nodes hold copies. If the primary dies, reads can still succeed from a replica.
flowchart LR
C["Client"]
R["Router"]
P["Primary<br/>Node 2"]
R1["Replica 1<br/>Node 3"]
R2["Replica 2<br/>Node 4"]
C -->|"1. PUT key value"| R
R -->|"2. Write to primary"| P
P -->|"3. Replicate"| R1
P -->|"4. Replicate"| R2
Step-by-step flow for GET:
- Client calls
GET key=user:42 - Router hashes
user:42→ finds Node 2 is the primary - Router sends read request to Node 2
- Node 2 checks its in-memory cache first, then disk if cache miss
- Node 2 returns the value to the client
But what if Node 2 is down? The router knows the replica list (Nodes 3 and 4 also have the data). It reads from a replica instead. No downtime, no data loss.
Step-by-step flow for a write with replication:
- Client calls
PUT key=user:42 value={...} - Router forwards to Node 2 (primary)
- Node 2 writes locally and ACKs the client immediately
- Node 2 streams the write to Node 3 and Node 4 in the background
What we have deliberately left broken. A single crash no longer loses data, and the price is that the three copies are now allowed to disagree:
- A returning node is silently stale. If Node 3 is down for ten minutes it misses every write in that window, and when it comes back nothing tells it so. It starts answering reads with old values, and because step 3 ACKs before replication, there is no record of what it missed. That is Deep Dive 3.
- Two clients writing the same key can both succeed with different values. Step 3 ACKs on one node’s local write, so two writes routed to different replicas during a partition both return success and both are “the” value. Nothing here decides which one survives. That is Deep Dive 4.
- A read can now contradict a write that already returned 200. Step 3 returns before Node 3 and 4 have the data, so a read served by Node 4 a millisecond later legitimately returns the old value. That is what FR3 is for.
FR3: Tunable Consistency - The W and R Knobs
Here’s the fundamental trade-off: do we wait for ALL replicas to ACK before telling the client “success” (slow but safe), or just one (fast but risky)?
The solution: Quorum reads and writes.
💡 A quorum means “majority must agree.” With N=3 replicas, a quorum is 2. If W=2 (write succeeds after 2 ACKs) and R=2 (read from 2 nodes), then at least one node in the read set has the latest value. This guarantees you always read the latest write.
The rule: As long as W + R > N, you get strong consistency.
| Setting | W | R | Behavior |
|---|---|---|---|
| Strong consistency | 2 | 2 | Always read latest. Slower writes. |
| Fast writes | 1 | 3 | Write is fast (1 ACK). Read must check all 3 nodes. |
| Fast reads | 3 | 1 | Write is slow (all must ACK). Read from any one node. |
| Eventual consistency | 1 | 1 | Fastest, but might read stale data. |
sequenceDiagram
participant C as Client
participant R as Router
participant N1 as Node 1 Primary
participant N2 as Node 2 Replica
participant N3 as Node 3 Replica
C->>R: PUT key=user:42
R->>N1: write
R->>N2: write
R->>N3: write
N1-->>R: ACK
N2-->>R: ACK
Note over R: W=2 met. Respond to client.
R-->>C: 200 OK
N3-->>R: ACK (arrives later, fine)
Why not always use strong consistency (W=N, R=N)? Because if even one node is down, writes fail. With W=2 out of 3, you can tolerate one node being down and still accept writes. This is the availability vs consistency trade-off (CAP theorem in action).
💡 The CAP theorem says that when the network splits, a store has to choose: keep answering and risk serving stale data, or refuse to answer and stay correct. You cannot have both, so every quorum setting in the table above is really a position on that one dial.
And when the R nodes disagree? A read at R=2 can come back with two different values, which is the normal case rather than an error — that is what tunable consistency buys and costs. The obvious rule is to take the one with the later wall-clock timestamp and return it.
What we have deliberately left broken. The W and R knobs let a caller choose its own position between latency and freshness, which is the requirement. The conflict rule underneath them is the weak point:
- Last-writer-wins by wall clock silently discards writes. The rule is only as good as the clocks, and clocks on different machines disagree by milliseconds even under NTP. Two writes 2ms apart on two nodes can be ordered backwards, so the write that genuinely happened second loses and vanishes with no error to anyone. Worse, the rule cannot tell the difference between “B overwrote A deliberately” and “A and B never saw each other”, and those need different answers. That is Deep Dive 4.
- Anything below
W + R > Nis explicitly allowed to serve stale reads, and nothing in the design bounds how stale. The eventual-consistency row in that table has no convergence mechanism behind it yet — Deep Dive 3 supplies it.
10. Technology Choices
| Tier | Purpose | Primary Pick | Alternatives | Why Primary Wins Here |
|---|---|---|---|---|
| Storage Engine | On-disk persistence per node | LSM Tree (RocksDB) | B-Tree (InnoDB), Bitcask, WiscKey | Write-optimized; sequential I/O for high-throughput ingestion |
| Coordination | Cluster membership + leader election | ZooKeeper | etcd, Consul, gossip (Cassandra-style) | Strong consistency for metadata; battle-tested at scale |
| Replication | Data durability across nodes | Raft consensus / quorum writes | Paxos, chain replication, async replication | Tunable W/R quorum balances consistency vs latency per-request |
| Partitioning | Distribute keys across nodes | Consistent Hashing (virtual nodes) | Range partitioning, hash mod N | Minimal data movement on node add/remove |
| Conflict Resolution | Handle concurrent writes | Vector Clocks + LWW | CRDTs, application-level merge | Simple, fits eventual consistency with tunable quorum |
| In-memory Index | Fast key lookup within a node | Bloom Filter + sparse index | Hash index, B-tree index | Bloom filter avoids disk reads for missing keys; sparse index for existing ones |
Why LSM over B-Tree? A KV store at 500K writes/sec needs write-optimized storage. LSM trees batch writes to memtable then flush sequentially — 10x write throughput vs random B-tree page splits. The tradeoff (read amplification from multiple levels) is mitigated by Bloom filters.
11. Data Modeling
LSM Tree Storage Engine (On-Disk — per node):
Memory:
Memtable (active): Red-Black Tree / Skip List
Key → { value, timestamp, tombstone_flag }
Size: 64MB before flush (configurable)
Memtable (immutable): being flushed to disk
Disk (per level):
Level 0: raw SSTables flushed from memtable (may overlap keys)
Level 1-6: sorted, non-overlapping SSTables within each level
SSTable format:
[data_block_1][data_block_2]...[meta_block][index_block][footer]
Each data_block: sorted key-value pairs, compressed (Snappy/LZ4/Zstd)
Index_block: sparse index (one entry per data_block) for binary search
Bloom Filter (In-Memory Index — per SSTable):
One Bloom filter per SSTable file (~10 bits per key)
Purpose: "Is key X definitely NOT in this SSTable?" — avoids disk reads for 99% of missing keys
Memory: ~1.2GB for 1 billion keys
Consistent Hashing (Partition Map):
Virtual nodes: 256 vnodes per physical node on the hash ring
Key → SHA-256(key) mod ring_size → owning vnode → physical node
Replication: next N-1 nodes clockwise on the ring hold replicas
Access Patterns:
| Query | Data Source | How |
|---|---|---|
| PUT key=value | Memtable (RAM) | Write to WAL (durability) → insert into memtable → return success |
| GET key | Memtable → L0 → L1 → … | Check memtable first (sub-μs), then Bloom filter each SSTable level |
| DELETE key | Memtable | Write tombstone marker; actual deletion during compaction |
| Range scan | All levels | Merge-sort across memtable + all SSTable levels |
| Rebalance on node add | Consistent hash ring | Only keys in the affected range migrate to the new node (~1/N of total data) |
How a Read Finds a Key Across LSM Levels:
- Client sends
GET user:42→ router hashes key → routes to owning node (consistent hashing) - Node checks memtable: O(log N) in skip list. If found → return immediately (~1μs)
- If not in memtable: check Level 0 SSTables (newest first). Probe Bloom filter for each — if “definitely not”, skip. If “maybe yes”, binary search the SSTable’s index block.
- Continue down Level 1, 2, … until found or all levels exhausted → return NOT_FOUND
- Worst case (key exists in deepest level): 1 memtable check + ~5 Bloom filter probes + 1 disk read = ~5ms
- Compaction (background): merges SSTables across levels, removes tombstones, reduces read amplification
12. Deep Dives
1) Adding a fifth node moves 800 million keys. How do we make growth routine?
Problem: FR1 put num_nodes inside the routing formula, so the number of machines is baked into where every key lives. Changing it changes almost every answer.
Bad: the hash(key) % num_nodes from FR1. Going from 4 nodes to 5, a key keeps its home only when hash % 4 == hash % 5, which is true for 4 of every 20 hash values — 20% stay, 80% move. At 1 billion keys that is 800 million keys whose owner changed.
What makes this an outage rather than a migration is that the data does not move with the mapping. The bytes are still on the old node, intact; the router simply stops asking for them. So every one of those 800M keys reads as a miss the instant the topology changes, and the cluster serves wrong answers — not errors, misses — until 800M keys have been physically relocated. Removing a node is the same event, and a node crashing is the same event with no warning.
The consequence worth stating: the system punishes you for scaling it. Capacity is something you need most when you are busiest, and this design makes adding capacity most expensive exactly then.
Good: Basic consistent hashing. Place nodes on a ring. Walk clockwise from the key’s hash to find its node. Adding a node only moves keys between it and its predecessor. On average, only 1/N keys move. With 4 nodes, adding a 5th moves ~20% instead of 80%.
Great: Consistent hashing with virtual nodes (borrowing from DynamoDB). Each physical node gets 100-200 positions on the ring.
💡 A virtual node is one of a physical machine’s many positions on the ring. Spreading each machine over 150 scattered positions rather than one means the share of the ring it owns averages out, instead of depending on where its single position happened to land. This ensures even distribution - without virtual nodes, some physical nodes might get 60% of keys by luck of the hash.
In simple terms: Instead of assigning each key to a server using simple math (which breaks when you add/remove servers), we put servers on a circle and each key goes to the nearest server clockwise. Virtual nodes make sure no single server gets overloaded by bad luck.
flowchart LR
subgraph "Hash Ring"
direction LR
VN1["Node A vnode 1"]
VN2["Node B vnode 1"]
VN3["Node A vnode 2"]
VN4["Node C vnode 1"]
VN5["Node B vnode 2"]
end
KEY["key: user:42<br/>hash position"]
KEY -->|"1. Hash to vnode"| VN2
Why virtual nodes matter: Without them, if Node A happens to be at positions 10 and 11 on the ring while Node B is at 50 and 90, Node A only gets keys from positions 11-50 (40% of the ring) while Node B covers 90-10 + 50-90 (60%). Virtual nodes (150 positions per physical node) make the distribution nearly uniform.
2) A B-tree does several random I/Os per write. How does one node absorb 100K of them a second?
Problem: Each node needs to store potentially hundreds of GB on disk efficiently, handle 100K writes/sec, and retrieve any key in sub-10ms.
Bad: the local B-tree FR1 chose. It is the default for a reason — it is what every embedded database hands you, and its reads are excellent: a point lookup is a handful of index pages, so the sub-10ms read target is comfortable.
The write path is the problem. A B-tree keeps keys in sorted order on disk, and our keys arrive hashed, which means every insert lands at a random position. Each one is a page read, a page modify, an occasional page split that rewrites a parent, and an fsync to make it durable — several random I/Os per write. A NVMe device that streams sequentially at gigabytes a second does far less when the access pattern is scattered, and at 100K writes/sec per node the device is the ceiling long before the CPU is.
Note the irony: FR1 deliberately hashed keys to get even distribution, and hashing is precisely what destroys the locality the B-tree needs. The partitioning decision and the storage decision are fighting each other.
Even worse, and worth dismissing: a file per key. Millions of tiny files exhausts inodes, directory lookups degrade, and every write pays filesystem metadata overhead. Nobody reaches for this twice.
Good: Append-only log. All writes are sequential appends (fast!). But reads require scanning the entire log to find a key (slow). Add an in-memory hash index pointing key → offset in the log. Reads are fast now, but the log grows forever.
Great: Log-Structured Merge Tree (LSM Tree).
💡 An LSM Tree splits storage into two layers: a fast in-memory buffer (memtable) and sorted files on disk (SSTables). All writes go to the memtable. When it’s full, it’s flushed to disk as a sorted file. Reads check memtable first, then disk files. Learn more →
In simple terms: Instead of writing directly to disk (slow random writes), dump everything into memory first, then flush to disk in big sorted batches. Reads check memory first, then disk files. This makes writes 100x faster.
flowchart LR
WRITE["Write"]
WAL["WAL<br/>crash recovery"]
MEM["Memtable<br/>in-memory sorted"]
SS1["SSTable L0<br/>on disk"]
SS2["SSTable L1<br/>on disk"]
READ["Read"]
BLOOM["Bloom Filter"]
WRITE -->|"1. Append to log"| WAL
WRITE -->|"2. Insert sorted"| MEM
MEM -->|"3. Flush when full"| SS1
SS1 -->|"4. Compaction"| SS2
READ -->|"5. Check memory"| MEM
READ -->|"6. Check filter"| BLOOM
BLOOM -->|"7. Scan disk"| SS1
New components inside one node:
- WAL (write-ahead log): an append-only file every write is recorded in before anything else happens. It exists because the memtable is in memory, so without the log a crash would lose every write that had not been flushed yet.
- Memtable: the sorted in-memory buffer that absorbs writes. It exists so that the expensive part - putting bytes in sorted order on disk - happens once per 64MB instead of once per write.
- SSTable L0 / L1: immutable sorted files on disk. L0 files come straight from a memtable flush and may overlap; compaction merges them down into non-overlapping levels.
- Bloom filter: a small in-memory summary per SSTable that can say “this key is definitely not in this file”. It exists because a read would otherwise have to touch every file at every level.
The write path:
- Write arrives → append to WAL (Write-Ahead Log) on disk for crash recovery
- Insert into the memtable (a sorted in-memory structure, like a red-black tree)
- When memtable reaches ~64MB, flush it to disk as an SSTable (Sorted String Table)
- Background compaction merges SSTables, removing old versions and deleted keys
💡 Because SSTables are never edited, a delete is written as a “tombstone” - a marker saying this key is gone. Compaction is where the tombstone and the old value finally meet and both disappear, which is also why deletes free no space immediately.
The read path:
- Check the memtable (fastest - it’s in memory)
- If not found, check the Bloom filter for each SSTable.
💡 A Bloom filter is a space-efficient structure that tells you “definitely not here” or “maybe here.” It avoids expensive disk reads for keys that don’t exist in a given file. Learn more → - If Bloom filter says “maybe,” read the SSTable from disk
- Return the value (or 404 if not found anywhere)
Why LSM over B-tree? LSM turns random writes into sequential writes (just append to a log). Sequential disk I/O is 100x faster than random I/O. For write-heavy workloads (500K writes/sec), LSM trees win decisively. LevelDB, RocksDB, and Cassandra all use this pattern.
3) A node comes back after ten minutes down. How does it learn what it missed?
Problem: In a cluster of 100 nodes, machines fail regularly. A node might crash, restart, or become unreachable due to network partitions. The system must continue serving reads and writes without data loss.
Bad: what FR2 built — replicas exist, and nothing reconciles them. A node that comes back after ten minutes down is accepted straight back into the read set carrying ten minutes of stale values, because FR2’s step 3 ACKs the client before replication and therefore keeps no record of what any replica missed.
This is worse than the node staying down. A down node returns errors, which the router can route around. A stale node returns confident wrong answers, and at R=1 roughly a third of reads for its keys get them. The failure is also invisible: no error rate moves, no alarm fires, and the only symptom is users occasionally seeing old data with no pattern anyone can reproduce.
And it compounds. Every subsequent write to those keys is applied on top of a divergent base, so the replicas drift further apart rather than converging. There is no mechanism anywhere in FR2 that ever brings them back together.
Good: With replication (N=3), reads and writes continue via the remaining 2 replicas. But when the node comes back, it’s stale - it missed writes that happened during its downtime. We need a way to bring it back up to date.
Great: Three mechanisms working together:
In simple terms: When a server comes back from being dead, we have 3 ways to catch it up: (1) replay writes that were saved for it while it was down, (2) fix stale data whenever someone reads it, (3) periodically compare what each server has and sync the differences.
Hinted Handoff - while a node is down, writes meant for it are temporarily stored on another node as “hints.” When the dead node comes back, hints are replayed to bring it up to date. Fast recovery for short outages.
💡 A hint is just a parked write with a note saying who it was for. The limit is capacity: hints accumulate for as long as the node is away, so a long outage overflows them and the next mechanism has to take over.
Read Repair - when a read hits multiple replicas and detects version mismatch, the router pushes the latest version to the stale replica. Passive healing on every read.
💡 This is reconciliation done opportunistically: the comparison was already paid for by the read, so fixing the loser is nearly free. It only heals keys somebody actually asks for, which is why the background sweep below still exists.
Anti-Entropy (Merkle Trees) - for long outages where hints might overflow, a background process compares Merkle tree hashes between replicas.
💡 A Merkle tree hashes data in a tree structure - if the root hashes differ, you recursively check children to find exactly which keys diverged. This minimizes data transfer during repair. Learn more →
sequenceDiagram
participant N1 as Node 1 (alive)
participant N3 as Node 3 (alive)
participant N2 as Node 2 (recovering)
Note over N2: Node 2 was down for 5 min
N2->>N1: "I'm back. Compare Merkle trees?"
N1->>N1: Compute tree hash for keys in N2's range
N1-->>N2: Root hash = abc123
N2->>N2: My root hash = xyz789 (different!)
N2->>N1: Send me divergent key ranges
N1-->>N2: Keys user:42 user:99 are stale on you
N2->>N2: Apply updates. Now consistent.
4) Two clients write the same key on different replicas. Which one survives, and who loses work?
Problem: With eventual consistency (W=1), two clients could write different values to the same key on different replicas. When the replicas sync, which value wins?
Bad: last-writer-wins on wall-clock timestamps, the rule FR3 adopted for disagreeing replicas. It is one comparison and it loses data in two distinct ways.
Clock skew reverses the order. NTP typically keeps machines within a few milliseconds of each other, and worse during a resync. Two writes genuinely 2ms apart on two nodes can carry timestamps in the wrong order, so the write that actually happened second is judged older and discarded. The client got a 200. Its data is gone, and nothing logged a conflict because from LWW’s point of view nothing went wrong.
It cannot distinguish overwriting from concurrency. “B read A’s value and deliberately replaced it” and “A and B never saw each other’s write” are different situations needing different answers — the first should keep B, the second should surface both. A timestamp carries no information about what the writer had seen, so LWW treats them identically and silently throws one away.
The second failure is the one that matters for a shopping cart or any read-modify-write value: two concurrent additions to a cart become one, and the user watches an item disappear.
Good: Last-writer-wins with synchronized clocks (NTP). Acceptable for many use cases where losing an occasional write is tolerable (caching, session stores).
💡 NTP, the Network Time Protocol, keeps machine clocks roughly in step with each other - roughly being the operative word. It narrows the window in which two writes can be ordered backwards; it does not close it.
Great: Vector clocks. Each write carries a vector clock that tracks which nodes have seen which version.
💡 A vector clock is a small table carried with each value, counting how many writes this value has seen from each node. Comparing two tables tells you whether one write knew about the other or whether they were genuinely simultaneous - which a timestamp can never tell you. If two writes are concurrent (neither “happened before” the other), the system detects the conflict and either:
- Returns BOTH values to the client to resolve (DynamoDB’s approach)
- Merges automatically using a conflict-free replicated data type (CRDT)
💡 A CRDT is a value whose merge rule is built in and always produces the same answer regardless of the order the updates arrive in. A shopping cart modelled as a set of added items is the classic case: merging two concurrent additions keeps both, so nothing disappears.
In simple terms: When two servers both update the same key at the same time, we need to know if one happened “before” the other or if they truly conflict. Vector clocks track this by counting updates per server — if neither is strictly ahead, we have a conflict and must resolve it.
For most interview answers: Say “we use LWW with versioning for simplicity, but for critical data we’d use vector clocks.” That shows you know both and can choose pragmatically.
13. Design Self-Audit
| Question | Answer |
|---|---|
| Single points of failure? | Coordinator uses ZooKeeper (replicated) or gossip (no single point of failure, or SPOF). Storage nodes are replicated N=3. |
| Hot keys? | A viral key could overwhelm one node. Mitigation: client-side cache, or split the hot key across sub-shards. |
| Data freshness? | Quorum reads (R=2) guarantee latest. Eventual reads (R=1) might be stale by milliseconds. |
| What about network partitions? | With quorum, partitioned minority can’t serve reads/writes (CP). Or accept stale reads (AP). Configurable per operation. |
| Cost at scale? | 10TB with 3x replication = 30TB raw. At $0.10/GB/month for SSDs, ~$3000/month for storage + compute for 100 nodes. |
14. Core Flows
Flow: PUT with Quorum Write
sequenceDiagram
participant C as Client
participant R as Router
participant N1 as Primary
participant N2 as Replica 1
participant N3 as Replica 2
C->>R: PUT key=user:42 value=json
R->>R: hash key maps to Node 1
R->>N1: write
R->>N2: write
R->>N3: write
N1->>N1: write to WAL then memtable
N1-->>R: ACK
N2->>N2: write to WAL then memtable
N2-->>R: ACK
Note over R: W=2 satisfied
R-->>C: 200 OK version=42
N3-->>R: ACK (late, still applied)
Non-obvious failure path: What if Node 2 is temporarily unreachable during the write? With W=2, Node 1 and Node 3 ACK → write succeeds. When Node 2 comes back online, it’s missing the latest version. This is repaired via read repair (on next read, if we detect a stale replica, we push the latest version to it) or anti-entropy (background Merkle tree comparison between replicas).
Flow: GET with Quorum Read
sequenceDiagram
participant C as Client
participant R as Router
participant N1 as Primary
participant N2 as Replica 1
participant N3 as Replica 2
C->>R: GET key=user:42
R->>N1: read
R->>N2: read
N1-->>R: value=json version=42
N2-->>R: value=json version=41 (stale!)
Note over R: R=2 satisfied. Pick highest version.
R-->>C: 200 value=json version=42
R->>N2: (async) read repair - push version 42
The router reads from R nodes, compares versions, returns the highest. If a replica is stale, it triggers a read repair in the background.
15. Final Architecture
flowchart TD
C["Client"]
LB["Load Balancer"]
R["Router Layer<br/>consistent hash ring"]
N1["Node 1"]
N2["Node 2"]
N3["Node 3"]
N4["Node 4"]
N5["Node 5"]
N6["Node 6"]
COORD["Coordinator<br/>ZooKeeper"]
C -->|"GET or PUT"| LB
LB --> R
R -->|"route to the N replicas<br/>that own this key"| N1
R --> N2
R --> N3
R --> N4
R --> N5
R --> N6
COORD -->|"membership<br/>and failure detection"| N1
COORD --> N2
COORD --> N3
COORD --> N4
COORD --> N5
COORD --> N6
New components:
- Load Balancer: spreads client requests across the router tier. Any router can serve any key, because routing is a computation rather than stored state.
- Router Layer: FR1’s router, now walking a consistent hash ring instead of taking a modulus. For each key it produces the N nodes that own it, not one.
- Coordinator (ZooKeeper): holds the authoritative ring membership and detects failures, so every router agrees on the same picture of the cluster. It exists because two routers disagreeing about who owns a key is indistinguishable from data loss.
💡 ZooKeeper is a small strongly-consistent store used purely for this kind of cluster metadata. Cassandra does the same job with gossip instead - every node telling a few others what it knows until the whole cluster converges - which removes this box at the cost of taking longer to agree.
Each node internally uses an LSM tree with WAL for the storage engine. Data is replicated to N=3 nodes via consistent hashing with virtual nodes. Reads and writes use configurable quorum (W, R values).
How it works end-to-end:
- Client sends GET or PUT — request hits the Load Balancer
- Router determines target nodes — consistent hash ring maps the key to N=3 replica nodes
- Write path — request forwarded to all 3 replicas; returns success once W nodes acknowledge (quorum write)
- Read path — request sent to R replicas; response returned once R nodes reply (quorum read, W+R>N ensures overlap)
- Node stores data locally — each node appends to WAL, writes to memtable, flushes to SSTables on disk (LSM tree)
- ZooKeeper manages membership — tracks which nodes are alive, assigns virtual node ranges, handles join/leave rebalancing
- Anti-entropy repair — Merkle trees detect divergent replicas; read-repair and background sync fix inconsistencies
Key Technologies
| Term | What it is |
|---|---|
| Consistent Hashing | Maps keys and nodes onto a ring. Adding/removing a node only moves neighboring keys. Used by DynamoDB, Cassandra, Redis Cluster. |
| Replication Factor (N) | Number of copies of each key. N=3 means survive up to 2 node failures. |
| Quorum (W + R > N) | Tunable consistency knob. Majority must agree for correctness. |
| LSM Tree | Write-optimized storage engine. Sequential appends, background compaction. Used by LevelDB, RocksDB, Cassandra. |
| Bloom Filter | Probabilistic structure: “definitely not here” or “maybe here.” Avoids expensive disk reads. |
| WAL | Write-Ahead Log. Append-only disk log before in-memory changes. Crash recovery guarantee. |
| Vector Clock | Tracks causality between writes. Detects conflicts when replicas diverge. Used in DynamoDB. |
| Merkle Tree | Hash tree for efficient replica comparison. Find exactly which keys diverged without transferring all data. |
What’s Expected at Each Level
Mid-level
Design basic GET/PUT with data split across multiple machines. Explain consistent hashing at a high level - keys map to nodes on a ring, adding a node only moves some keys. Propose replication (N=3) for fault tolerance. With prompting, explain why hash % N is bad when nodes change.
Senior
Explain consistent hashing with virtual nodes for even distribution. Discuss quorum reads/writes (W+R>N). Propose LSM tree storage with memtable + SSTables and explain why it beats B-trees for write-heavy loads. Articulate the CAP theorem trade-off - this system chooses AP with tunable consistency. Discuss read repair as a self-healing mechanism.
Staff+
Address vector clocks for conflict detection, Merkle trees for anti-entropy repair, hinted handoff during temporary failures. Discuss tunable consistency per operation (some keys need strong, others eventual). Cover write amplification in LSM trees (compaction cost), hot key mitigation (client-side cache + key splitting), and the operational complexity of managing a 100+ node cluster (gossip protocol convergence time, network partition handling).
🎯 Key Takeaways
- Consistent hashing distributes data evenly and minimizes reshuffling when nodes change
- Replication (N=3) provides fault tolerance - lose a node, data survives
- Quorum (W+R>N) lets you tune the consistency-vs-speed tradeoff per operation
- LSM trees make writes fast by converting random I/O to sequential appends
- This pattern underpins almost every distributed database - learn it once, apply everywhere
Related Designs
- Rate Limiter - uses Redis (a KV store) for counters
- Leaderboard - Redis sorted sets are a specialized KV structure
- URL Shortener - simple KV mapping of short code → URL
Related Concepts
Understand the building blocks used in this design:
- Consistent Hashing → — places keys on the ring so adding or removing nodes reshuffles minimal data
- CAP Theorem → — frames the availability-vs-consistency choice this store makes under partitions
- Merkle Trees → — power efficient anti-entropy repair between replicas
- Vector Clocks → — detect and reconcile concurrent writes to the same key
- Database Replication → — N-way replication with quorum reads and writes for durability
Discussion
Newest first