A distributed key-value store offers the simplest possible interface, get(key) and put(key, value), across hundreds of machines that fail all the time. Amazon's 2007 Dynamo paper showed how to build one that stays writable through node crashes and network partitions, and its ideas live on in Cassandra, Riak, ScyllaDB and Voldemort. This case study assembles the pieces you met separately (consistent hashing, replication, quorums, vector clocks, gossip, Merkle trees and LSM storage) into one coherent, interview-ready design.
Think of it like
A ring of librarians sharing notebooks
Picture librarians seated around a round table. Every topic is assigned to a seat by its hash, and that librarian plus the next two clockwise each keep a copy of its notebook. To record something, you need two of the three to write it down. If one is out sick, the next librarian keeps a sticky note saying "give this to Carol when she's back". Every evening, neighbors compare a one-line checksum of each notebook section and only reread the pages that differ. Nobody is in charge, so nobody's absence stops the library.
1. Requirements
Functional
put(key, value),get(key)anddelete(key)- Keys up to ~1 KB, values up to ~1 MB (opaque bytes)
- Per-request consistency: the caller chooses how many replicas must answer
- Return conflicting versions to the caller when concurrent writes happen (or resolve them by policy)
- Optional per-key TTL
Non-functional
- Always writable: accept writes during node failures and partitions (AP in CAP Theorem & PACELC terms)
- Low latency: p99 under ~10 ms within a data center
- Durable: an acknowledged write survives the loss of any single node
- Incremental scalability: add a node, and only its share of data moves
- Decentralized: no single master, no single point of failure
| In scope | Out of scope |
|---|---|
| Partitioning, replication, versioning | Multi-key transactions (see Distributed Transactions) |
| Failure detection and repair | Range scans across the whole key space (hash partitioning prevents them) |
| Per-node storage engine (high level) | Secondary indexes and query languages |
| Multi-data-center replication (brief) | Strongly consistent compare-and-set (needs consensus, see Consensus: Raft & Paxos) |
2. Back-of-the-envelope estimation
Assume 10 billion keys averaging 1 KB (key plus value), a peak of 500,000 reads/s and 100,000 writes/s, replication factor N = 3 and quorums R = W = 2. Compute capacity from storage and from throughput separately, then take the larger. See Back-of-the-Envelope Estimation.
Cluster
~40 nodes
throughput-bound
Data per node
~750 GB
30 TB ÷ 40
Replication traffic
~300 MB/s
100k writes × 1 KB × 3
Rebuild one node
~10 min
750 GB at ~1.2 GB/s (a 10 Gbps NIC), pulled from many peers
3. API and data model
syntax = "proto3";
package kv.v1;
service KeyValue {
rpc Get(GetRequest) returns (GetResponse);
rpc Put(PutRequest) returns (PutResponse);
rpc Delete(DeleteRequest) returns (PutResponse);
}
enum Consistency {
CONSISTENCY_UNSPECIFIED = 0;
ONE = 1; // fastest, may be stale
QUORUM = 2; // R or W = floor(N/2) + 1
ALL = 3; // slowest, fails if any replica is down
}
message Version {
bytes value = 1;
bytes context = 2; // opaque: the vector clock for this version
}
message GetRequest { bytes key = 1; Consistency consistency = 2; }
message GetResponse { repeated Version versions = 1; } // more than one = siblings
message PutRequest {
bytes key = 1;
bytes value = 2;
bytes context = 3; // context from the Get this write is based on
Consistency consistency = 4;
uint32 ttl_seconds = 5;
}
message PutResponse { bytes context = 1; }
message DeleteRequest { bytes key = 1; bytes context = 2; Consistency consistency = 3; }Getcan return several versions. If two clients wrote concurrently, the store does not guess: it returns both siblings and the caller merges them (or a configured policy such as last-write-wins does).Putcarries the context it read. The opaque context is the vector clock of the version the client saw, so the server knows which versions this write supersedes. This is the read-modify-write contract from the Dynamo paper.- Consistency is per request. A session store might write with
ONEwhile a checkout reads withQUORUM.
| Field (per stored version) | Type | Purpose |
|---|---|---|
key | bytes | Hashed to find the partition; stored for collision safety and range repair |
value | bytes | Opaque to the store |
vector_clock | list of (node id, counter) | Detects concurrent versions |
timestamp | int64 µs | Tie-breaker for last-write-wins and TTL expiry |
tombstone | bool | A delete marker; must be kept until every replica has seen it |
4. High-level design
Every node runs the same software and owns several ranges of a hash ring. Any node can coordinate a request: it computes the key's preference list (the first N distinct nodes clockwise from the key's hash), forwards the operation to those replicas, and replies once enough of them answer. Press play to watch a quorum write, a read with repair, and a write that survives a dead node.
cart:42 hashes just before node A, so its preference list is A, B, C, with D as the first fallback. Pick a flow above to animate a request.5. Deep dive: partitioning and preference lists
Keys are placed with Consistent Hashing: hash the key onto a ring, walk clockwise to the first token. Adding or removing a node moves only about 1/n of the keys. Two refinements make it production grade.
Virtual nodes
- Each physical node owns many small token ranges (Cassandra historically used 256 per node; recent versions default to 16 with a smarter token allocator)
- Load evens out statistically; no hand-tuned token placement
- A failed node's load spreads over many peers, not one neighbor
- Bigger machines can take more tokens (heterogeneous hardware)
Preference lists
- Walk clockwise collecting N distinct physical nodes, skipping extra vnodes of a node already chosen
- Skip nodes in the same rack or availability zone so one failure cannot take out every copy
- Extra nodes after the first N are the fallbacks used by sloppy quorums
- Every node can compute any preference list from the gossiped ring
6. Deep dive: replication and tunable quorums
Each key lives on N replicas; a write waits for W acknowledgments and a read for R responses. The full theory is in Quorums & Leaderless Replication; here is how the choice plays out for this store.
| N, R, W | Overlap (R + W > N)? | Survives for writes | Typical use |
|---|---|---|---|
| 3, 2, 2 | Yes | 1 replica down | Default: balanced latency and consistency |
| 3, 1, 3 | Yes | 0 replicas down | Read-heavy data that must be fresh; writes are fragile |
| 3, 3, 1 | Yes | 2 replicas down | Write-heavy; every read pays for the slowest replica |
| 3, 1, 1 | No | 2 replicas down | Caches, metrics, sessions: speed over freshness |
| Multi-DC: 3+3, LOCAL_QUORUM | Yes within a DC | 1 replica per DC | Low latency locally, async cross-region |
- 1
Read repair (on the read path)
When replicas return different versions, the coordinator pushes the newest version to the stale ones. Cheap, but only heals keys that are read.
- 2
Hinted handoff (on the write path)
Writes meant for a down node are parked on a fallback node and replayed when it returns. Heals short outages quickly.
- 3
Anti-entropy (in the background)
Replicas compare Merkle trees and stream only the ranges that differ. Heals everything else, including cold keys and expired hints.
7. Deep dive: versioning and conflict resolution
Because any replica accepts writes, two clients can update the same key at the same time on different sides of a partition. The store must detect that the versions are concurrent rather than silently picking one. Dynamo attaches a vector clock (one counter per coordinating node) to each version. See Time, Clocks & Ordering for the theory.
| Step | Event | Vector clock | Relationship |
|---|---|---|---|
| 1 | Client writes D1 through node Sx | [Sx:1] | First version |
| 2 | Client updates to D2 through Sx | [Sx:2] | D2 descends from D1, so D1 can be discarded |
| 3 | Client 1 updates to D3 through Sy | [Sx:2, Sy:1] | Descends from D2 |
| 4 | Client 2 (also read D2) writes D4 through Sz | [Sx:2, Sz:1] | Neither D3 nor D4 dominates: concurrent |
| 5 | A read returns both siblings; the client merges and writes D5 through Sx | [Sx:3, Sy:1, Sz:1] | Dominates D3 and D4; the conflict is resolved |
Last-write-wins (timestamps)
- Highest timestamp wins; no siblings, simple API
- Concurrent writes are silently lost
- Depends on clock sync; a fast clock can win for minutes
- Used by Cassandra (per column), fine for immutable or idempotent data
Vector clocks + siblings
- Detects concurrency precisely
- The application must merge siblings (union of cart items, say)
- Clocks grow with the number of coordinators; Dynamo truncated old entries
- Used by Dynamo and Riak (later with dotted version vectors)
CRDTs
- Data types whose merge is automatic and deterministic (counters, sets, maps)
- No lost updates and no application merge code
- Only for operations that fit a CRDT
- Riak data types, Redis Enterprise active-active
8. Deep dive: anti-entropy with Merkle trees
Replicas that drifted apart (a lost hint, a disk swapped after failure) must be reconciled without shipping terabytes. Each node builds a Merkle tree per token range: leaves hash buckets of keys, and every parent hashes its children. Two replicas compare roots; if they match, the whole range is identical. If not, they descend only into the children that differ.
Replica B Replica C
root 9f3c root 51aa <- differ: descend
/ \ / \
h01 77d2 h23 a8e0 h01 77d2 h23 0c4b <- left matches: skip half
/ \ / \ / \ / \
h0 1a h1 5e h2 c3 h3 99 h0 1a h1 5e h2 c3 h3 f0 <- only bucket 3 differs
Exchange: 2 + 2 + 2 hashes, then stream the keys of bucket 3 only.
Cost ≈ O(differences × log(buckets)) instead of O(all keys).- Rebuilding trees is the expensive part: a node must read all its data to hash it. Systems rebuild periodically (Cassandra's
nodetool repairbuilds trees on demand), or maintain hashes incrementally on writes. - Virtual nodes complicate it: more, smaller ranges mean more trees to build and compare, one reason Cassandra moved to fewer tokens per node.
- Run repair more often than the tombstone grace period. Otherwise a replica that missed a delete can resurrect the key (see the deletes section below).
9. Deep dive: membership and failure detection
With no master, nodes learn the ring and each other's health through gossip: every second, each node exchanges its membership table (node, status, heartbeat counter, tokens) with a few random peers, and news reaches the whole cluster in O(log n) rounds. A phi accrual detector turns heartbeat arrival times into a suspicion level instead of a hard timeout. Both are covered in Heartbeats & Gossip Protocols.
Transient failure (down)
- Detected automatically by gossip and phi accrual
- The node keeps its token ranges
- Writes go to fallbacks with hints; nothing is re-replicated
- Most failures are this kind: reboots, GC pauses, network blips
Permanent change (leave or replace)
- Triggered by an operator or automation, not by a timeout
- Token ranges are reassigned and data is streamed to new owners
- Expensive: hundreds of GB move across the network
- Dynamo required an explicit command so a flapping network could not trigger a storm of rebalancing
10. The write and read paths inside a node
Each replica stores data in a log-structured merge tree (LSM), introduced in Database Indexing. Writes are sequential appends, which suits a replicated store where every logical write hits N disks. Press play to follow both paths.
11. Scaling, bottlenecks and failure handling
- Adding capacity: a new node takes tokens from many existing nodes and streams just those ranges. Only ~1/n of the data moves, and with vnodes the work is spread across the cluster.
- Hot keys: consistent hashing balances keys, not traffic. A celebrity key still lands on N nodes. Add a cache in front, replicate hot keys more widely, or split the value across suffixed keys (
key#0..key#7). - Multiple data centers: keep N replicas per region and use local quorums for user requests; replicate across regions asynchronously. A full region outage then costs freshness, not availability.
- Compaction debt: if writes outpace compaction, SSTables pile up and reads slow down. Monitor pending compactions and throttle or scale before it snowballs.
- Large partitions and values: cap value size and partition size; a 1 GB partition makes repair, streaming and GC painful. See Sharding & Partitioning.
| Failure | What happens | Recovery |
|---|---|---|
| One node crashes | Quorums still succeed with 2 of 3; hints accumulate on fallbacks | Node restarts, replays its commit log, receives hints |
| Disk lost on one node | Node returns empty | Replace and stream its ranges from the other replicas (rebuild), then repair |
| Network partition | Both sides accept writes via sloppy quorums | Siblings or LWW resolve conflicts after the partition heals |
| Rack or AZ outage | Up to one replica per key lost if placement is rack-aware | Same as a node crash, at larger scale |
| Coordinator dies mid-write | Some replicas have the write, some do not | Client retries (idempotent put with the same context); read repair and anti-entropy converge the rest |
| Clock skew | LWW picks the wrong winner | NTP monitoring, bounded skew alarms, or vector clocks for data where it matters |
Implementation
Each physical node places many tokens on the ring. A preference list walks clockwise and collects N distinct physical nodes.
import bisect
import hashlib
def _hash(s: str) -> int:
return int.from_bytes(hashlib.md5(s.encode()).digest()[:4], "big")
class Ring:
def __init__(self, vnodes_per_node: int = 128) -> None:
self.vnodes = vnodes_per_node
self.positions: list[int] = []
self.owners: list[str] = []
def add_node(self, node: str) -> None:
for i in range(self.vnodes):
pos = _hash(f"{node}#{i}")
idx = bisect.bisect_left(self.positions, pos)
self.positions.insert(idx, pos)
self.owners.insert(idx, node)
def remove_node(self, node: str) -> None:
kept = [(p, o) for p, o in zip(self.positions, self.owners) if o != node]
self.positions = [p for p, _ in kept]
self.owners = [o for _, o in kept]
def preference_list(self, key: str, n: int) -> list[str]:
start = bisect.bisect_left(self.positions, _hash(key))
out: list[str] = []
for i in range(len(self.owners)):
node = self.owners[(start + i) % len(self.owners)] # wrap around
if node not in out: # skip extra vnodes
out.append(node)
if len(out) == n:
break
return outKey takeaways
- The always-writable requirement drives everything: leaderless replication, sloppy quorums, hinted handoff and conflict detection.
- Consistent hashing with virtual nodes spreads data and rebuild work evenly; preference lists pick N distinct physical nodes, ideally in different racks or zones.
- Tunable N, R and W let each request choose its point on the latency and consistency curve; R + W > N gives overlap, not linearizability.
- Vector clocks detect concurrent writes so they can be merged instead of silently lost; last-write-wins is simpler but drops updates.
- Three repair mechanisms work together: read repair for hot keys, hinted handoff for short outages, Merkle-tree anti-entropy for everything else.
- Each node is an LSM engine: append-only writes, Bloom-filtered reads, compaction in the background, and tombstones that must outlive repair.
Common pitfalls
- Claiming R + W > N makes the store strongly consistent, forgetting sloppy quorums, partial writes and clock-based conflict resolution.
- Using hash partitioning and then promising efficient range scans across keys.
- Treating a missed heartbeat as permanent failure and triggering massive rebalancing on a network blip.
- Purging tombstones before every replica is repaired, which resurrects deleted data.
- Placing all N replicas in one rack or availability zone because the ring walk happened to pick neighbors there.
Interview tips
- State the CAP choice first and tie each later component back to it.
- Do the capacity math both ways (storage and replica operations per second) and size the cluster by the larger.
- Draw the ring with a concrete key and preference list, then animate a write with one node down: it shows sloppy quorum and hinted handoff in one story.
- Contrast with a leader-based design: if the interviewer wants strong consistency, switch to one Raft group per partition and explain what you lose.
Real-world applications
- Amazon Dynamo (2007 paper) powered internal services such as the shopping cart; it is the origin of this design. Note that the later DynamoDB service uses leader-based replication per partition (Multi-Paxos), not Dynamo's leaderless quorums.
- Apache Cassandra (created at Facebook) combines Dynamo-style partitioning and gossip with a Bigtable-style LSM data model and last-write-wins per column.
- Riak implemented Dynamo closely, including vector clocks (later dotted version vectors), sibling resolution and CRDT data types.
- ScyllaDB is a Cassandra-compatible reimplementation in C++ with a shard-per-core architecture.
- LinkedIn Voldemort was an open-source Dynamo-inspired store used for read-heavy serving data.
Test yourself
With N = 3, which (R, W) pair guarantees that every read quorum overlaps every write quorum?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.