Design: distributed key-value store
Place keys on a consistent-hash ring, replicate each to N nodes, and wait for W write and R read acks; versions resolve conflicts, while gossip, hinted handoff and Merkle-tree repair ride out failures.
Fundamentals you'll use
How it works
- Consistent hashing with vnodes picks N replicas per key; any node can coordinate a request.
- Write to N, wait for W acks, read R replies: R + W > N makes the two sets overlap.
- Concurrent writes need a rule: vector clocks keep both versions to merge; last-write-wins silently drops one.
- Gossip detects failures, hinted handoff keeps writes flowing, Merkle-tree repair resyncs replicas in the background.
- Dynamo's common (N, R, W) is (3, 2, 2): it tolerates one replica down for reads and writes.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your profile store runs N = 3, R = 1, W = 1. Users rename themselves and the next page often shows the old name. No nodes are failing. Cheapest fix?
Go deeper
Full explanation
Requirements
Functional: put(key, value) and get(key), values up to ~1 MB (assumption), optional TTL. Non-functional: always writable (a cart that rejects "add" loses sales), predictable p99.9 latency, scale out by adding nodes, survive node and datacenter loss. Dynamo's example SLA: 300 ms at p99.9 for 500 requests/s.
Questions I'd ask: is eventual consistency acceptable, or do some keys need linearizable reads? Read/write ratio and value size? One region or several?
High-level design
Any node can coordinate a request. Consistent hashing with virtual nodes maps a key to a position; the next N distinct nodes clockwise form its preference list. Writes go to all N and the coordinator waits for W acks; reads wait for R replies. With R + W > N, read and write sets overlap. Dynamo's common setting is (N, R, W) = (3, 2, 2). Each node stores data in an LSM engine (commit log, memtable, SSTables).
The hard parts
Conflicts. Two clients can write the same key through different replicas. Dynamo tags versions with vector clocks: if one descends from the other, keep the newer; if they are concurrent, return both and let the app merge them (a cart takes the union, so deleted items can resurface). Cassandra uses last-write-wins timestamps instead: simpler, but a skewed clock silently drops a write.
Failures. Gossip spreads membership and failure suspicion. If a replica is down, a healthy node accepts its write with a hint and hands it back on recovery (a sloppy quorum). Read repair fixes stale replicas during reads, and Merkle trees per key range let replicas sync only the ranges that differ.
Code Quorum write and vector-clock reconcile
from concurrent.futures import ThreadPoolExecutor, as_completed
N, R, W = 3, 2, 2 # Dynamo's common setting: R + W > N
def descends(a: dict, b: dict) -> bool:
"""Vector clock a has seen every event that b has."""
return all(a.get(node, 0) >= n for node, n in b.items())
def reconcile(versions: list[tuple[dict, bytes]]) -> list[tuple[dict, bytes]]:
# Drop versions that another version descends from; the rest are siblings
uniq = list({tuple(sorted(c.items())): (c, v) for c, v in versions}.values())
return [(c, v) for c, v in uniq
if not any(o != c and descends(o, c) for o, _ in uniq)]
def put(key, value, clock: dict, ring, pool: ThreadPoolExecutor) -> dict:
replicas = ring.preference_list(key, N) # first N healthy nodes clockwise
clock = {**clock, ring.me: clock.get(ring.me, 0) + 1}
futures = [pool.submit(r.write, key, value, clock) for r in replicas]
acks = 0
for f in as_completed(futures, timeout=0.3):
acks += f.result() is True
if acks >= W:
return clock # stragglers finish in the background
raise TimeoutError("write quorum not reached")
def get(key, ring, pool: ThreadPoolExecutor) -> list[tuple[dict, bytes]]:
futures = [pool.submit(r.read, key) for r in ring.preference_list(key, N)]
replies = [f.result() for _, f in zip(range(R), as_completed(futures, timeout=0.3))]
return reconcile([v for reply in replies for v in reply]) # >1 = siblings to mergeReal example
cart:42 has version {A:2}. During a partition, the phone adds book through node A, giving {A:3}; the laptop adds pen through node B, giving {A:2, B:1}. Both writes reach W = 2 thanks to the sloppy quorum. Neither clock descends from the other, so the next read returns two siblings. The cart service merges them into {book, pen} and writes back with the merged context {A:3, B:1}. Had the laptop removed a mug, the union would bring it back: Dynamo's documented trade-off.
Trade-offs +3 · −3
+ You gain
- Always writable: sloppy quorums and hinted handoff accept writes through node failures and partitions.
- No leader and no single point of failure; any node coordinates, so scaling out means adding nodes.
- (N, R, W) per use case lets each workload choose its latency, durability and consistency point.
− You pay
- Key access only: no joins, no ad hoc queries, no multi-key transactions in the Dynamo model.
- The app must merge siblings, or accept lost writes under last-write-wins.
- Repair, tombstones and compaction are constant operational work.
Use it when
Huge key-addressed workloads that must stay writable through failures: carts, sessions, user profiles, feature stores, idempotency tables.
Avoid it when
Multi-key transactions, ad hoc queries or strict linearizability (balances, inventory): use a relational or consensus-backed store.
Numbers to know 4
- Dynamo (2007): common (N, R, W) = (3, 2, 2); example SLA 300 ms at p99.9 for 500 requests/s.
- Divergence is rare: 99.94% of shopping-cart reads saw exactly one version over 24 h.
- Dynamo truncates vector clocks at ~10 (node, counter) pairs; Cassandra stores hints only for a node's first 3 h down (default).
- Sizing: assume 10B keys × 1 KB × 3 replicas = 30 TB; at ~1 TB per node (assumed), ~30 nodes plus headroom.
Common pitfalls 4
- Believing R + W > N means linearizable: sloppy quorums and concurrent writers still return stale or sibling values.
- Last-write-wins with skewed clocks: a write stamped in the past silently disappears.
- Purging tombstones before repair runs: a replica that missed the delete brings the data back.
- Expecting hashing to fix hot keys: one popular key still hits the same N replicas.
Interview questions 3
Answer out loud first, then reveal.
Some keys need strongly consistent reads. What do you change?Show answer
Quorums alone won't do it: R + W > N gives overlap, not linearizability, under sloppy quorums and concurrent writers. For those keys I'd use a leader per partition backed by consensus, as DynamoDB does: Multi-Paxos per partition, a write acknowledged once a quorum persists the log, strong reads served by the leader. Or a compare-and-set through Paxos, like Cassandra's lightweight transactions, paying extra round trips only on those keys.
A node is down for six hours. Walk me through what happens.Show answer
Gossip marks it suspect within seconds. Writes for its ranges go to the next healthy node with a hint, so W is still met, and reads use the other replicas. Cassandra stores hints only for the first 3 h of downtime by default, so this node misses writes that hints never captured. On return, hints replay and a Merkle-tree repair streams only the differing ranges. If it never returns, I replace it and stream its ranges from replicas.
Why vector clocks instead of timestamps?Show answer
Timestamps impose an order on writes that weren't ordered. With two concurrent cart updates, last-write-wins keeps one and silently loses the other, and clock skew can even prefer the older one. Vector clocks detect concurrency and hand both versions to the app, which merges them. The cost: clients pass context back, apps write merge logic, and clocks grow. For overwrite-only data, timestamps are fine.
Deep dive 3
Partitioning and replication
Each physical node owns many virtual nodes (tokens) on the ring, so load evens out and a new node takes small slices from every peer instead of one big range. Cassandra 4.0 lowered its default from 256 to 16 tokens per node, because many tokens slow repair and streaming. The preference list skips tokens owned by the same machine, and in multi-datacenter setups, by the same rack or zone, so N replicas really are N failure domains. Hot keys are not fixed by hashing: one celebrity key still lands on the same N nodes, so cache it or split it.
Conflicts: vector clocks or last-write-wins
A vector clock is a list of (node, counter) pairs. The client sends back the context it read, so the coordinator can tell newer from concurrent. Siblings are rare in practice: over 24 h, 99.94% of Dynamo's shopping-cart reads saw exactly one version. Clocks grow with each coordinator, so Dynamo truncates at ~10 pairs, accepting rare false conflicts. Last-write-wins needs no client cooperation, but it turns concurrency into silent data loss and depends on synchronized clocks. Use it for overwrite-only data (profiles, sessions); use siblings or CRDTs for data that accumulates, like carts or counters.
Failure handling and repair
Gossip lets every node learn membership and suspicions within seconds, without a central coordinator. A sloppy quorum writes to the first N healthy nodes; the stand-in stores a hint and replays it when the owner returns. Hints are best effort: by default Cassandra stores them only for a node's first 3 h of downtime, so a longer outage needs anti-entropy repair. There, replicas exchange Merkle-tree roots per key range and descend only into branches whose hashes differ, streaming just the divergent keys. Deletes are tombstones; purge them only after repair has run, or a stale replica resurrects deleted data.