SysDesignAtlas

Design a Distributed Key-Value Store

Building Dynamo from first principles — consistent hashing, quorums, vector clocks, anti-entropy, and the failure handling that makes it stay available.

HLDHard11 min readcase-studydynamoquorumconsistent-hashing
Confidence

#1. Requirements

Functional

  • get(key) and put(key, value).
  • Values are opaque blobs, up to ~1 MB.
  • No queries by value, no joins, no transactions — say this explicitly, because the constraint is what makes the design possible.

Non-functional

  • Always writable. Availability prioritized over consistency (the classic shopping-cart requirement: never reject an "add to cart").
  • Tunable consistency per operation.
  • Linear horizontal scale; add nodes without downtime.
  • No single point of failure — a symmetric, peer-to-peer design.
  • Low latency: p99 under ~10 ms.

Clarifying questions: Availability or consistency priority? Value size range? Do we need range scans like "all keys from user:100 to user:200" (a big fork — that requires an ordered partitioner, which places keys by their sorted order rather than by hash)? Single or multi-region?

#2. Estimation

1 PB of data, 1M QPS, values averaging 10 KB.

   Objects: 1 PB / 10 KB = 10¹¹ = 100 billion keys
   With replication factor 3: 3 PB physical

   At 4 TB usable per node: 3 PB / 4 TB = 750 nodes

   Per node: 1M QPS / 750 ≈ 1,300 QPS  ← very comfortable
   → this cluster is sized by STORAGE, not throughput

Knowing which resource sizes the cluster is a useful thing to state — it tells you that node count is driven by capacity, so you'd choose dense storage nodes and the design should optimize for storage efficiency.

#3. Partitioning

Consistent hashing with virtual nodes.

   hash(key) → position on a ring
   key belongs to the first node clockwise

   Each physical node holds ~200 virtual nodes:
     ✓ even load distribution despite random placement
     ✓ on failure, one node's load spreads across MANY
       successors rather than landing entirely on one
     ✓ heterogeneous hardware via vnode count (weighting)

Why virtual nodes are non-negotiable here: without them, a node failure dumps all its keys onto exactly one successor, which may then also fail — cascading around the ring. With 200 vnodes, the load spreads across the whole cluster.

Membership (which nodes are in the cluster, and where they sit on the ring) propagates by gossip: every second or so, each node swaps what it knows with a few random peers. There's no coordinator, each node sends only a constant handful of messages per round, and news reaches all nodes in about log(N) rounds — around 10 rounds for 750 nodes. Every node learns the full ring, so any node can route any request. That's what makes the system symmetric: there are no special nodes.

#4. Replication

Each key is stored on the N successive distinct physical nodes clockwise from its ring position (the preference list).

   key K hashes between vnodes → walk clockwise, collecting
   distinct PHYSICAL nodes until we have N=3

   preference list for K: [node-7, node-12, node-3]
                           ▲ coordinator (first in list)

The "distinct physical" detail matters — if you naively take the next 3 virtual nodes, you can end up with 3 copies on the same machine. Candidates get this wrong regularly, and catching it is a nice depth signal.

For multi-AZ durability, skip nodes until you have replicas in 3 different availability zones.

#5. Consistency — quorums

   N = 3 replicas
   W = replicas that must ack a write
   R = replicas that must respond to a read

   R + W > N  →  read and write sets overlap → reads see
                 the latest completed write

   Default: W=2, R=2, N=3  — tolerates one failure on both paths

Full treatment in Quorums. The key points to state:

Tunable per operation. A shopping cart write uses W=1 (fastest, most available). A read of a config value uses R=3 to be safer. This is a per-request dial, not a cluster setting — and that flexibility is a headline feature.

What it does NOT give you: linearizability — the guarantee that the system behaves like a single copy, where once any read sees a new value, every later read does too. Quorums fall short in three ways:

  • Concurrent writes still conflict. Two writes at once can each reach a different quorum, leaving no single "latest" value.
  • A failed write can surface later. A write that reached 1 replica instead of the required 2 is reported as failed — but that replica still has the value, and a later read may return it.
  • Reads can go backwards. While a write is still spreading, one read's quorum may include the new value and the next read's quorum may not, so a client sees the new value and then the old one. Being precise about this — rather than claiming "R+W>N means strong consistency" — is what separates a good answer from a memorized one.

#6. Conflict resolution — vector clocks

Two clients write concurrently to the same key. Both succeed on different quorums. Now what?

Last-write-wins by timestamp is wrong — clock skew means the write that really happened last may have a lower timestamp, so you silently lose data.

Vector clocks sidestep the guessing entirely. Instead of asking "which came later?", they record what each writer had seen when it wrote. If A's version already includes everything B knew, A genuinely came after B and wins outright. If neither includes the other, the two writes truly happened without knowledge of each other — and the system says so instead of picking one.

   Each write carries a version vector: [(node, counter), ...]

   Client A writes → [(n1, 1)]
   Client B writes concurrently → [(n2, 1)]

   Comparing: neither dominates (neither has seen
   everything the other has) → CONCURRENT
   → store BOTH as siblings; return both on read
   → the client (or application) merges and writes back,
     which collapses them: [(n1,1),(n2,1),(n3,1)]

The shopping cart is the canonical example: merge by union — the merged cart contains every item in either version. The catch: if you removed an item on one side of a network partition while the other side still had it, the union puts it back. So a partition might resurrect a removed item, but it can never lose an added one. That asymmetry is a deliberate business decision — a spurious item is a minor annoyance; a lost purchase is lost revenue. Framing it as a product choice rather than a technical one is a strong move.

The cost: vectors grow with the number of writers. Prune the oldest entries past a threshold, accepting rare false "concurrent" verdicts. Modern systems often prefer CRDTs, which merge automatically without surfacing siblings — worth mentioning as the evolution of this idea.

#7. Failure handling

This is where the interview goes deep. Three mechanisms, each solving a different failure duration.

Hinted handoff — temporary failure.

   Preference list for K: [A, B, C].  B is down.
   Write goes to A, C, and D (the next healthy node).
   D stores a HINT: "this belongs to B."
   When B returns, D delivers the data and drops the hint.

This is a sloppy quorum — it keeps writes succeeding during failures, at the cost of the overlap guarantee (a strict read quorum of A, B, C could miss a write that landed on D). Naming that tradeoff explicitly is exactly the kind of precision that scores.

Read repair — passive, ongoing. During a read, the coordinator sees divergent versions, returns the newest to the client, and writes it back to stale replicas. Free repair for hot data — but cold data is never read, so never repaired. Which motivates:

Merkle trees — permanent failure and cold data. The problem: two replicas hold a million keys each and need to find the handful that differ, without shipping a million keys to each other. A Merkle tree solves it by hashing the data in chunks, then hashing those hashes, and so on up to a single root value. Two replicas compare one number; if it matches, everything below it matches too.

              root hash
             /         \
         h(A)           h(B)      Compare roots.
        /    \         /    \     Equal → in sync, one comparison
      h1     h2      h3     h4    for the entire key range.
                                  Differ → descend only into
                                  the differing subtree.

Data exchanged is proportional to the number of differences, not the dataset size. This is what makes background repair affordable across a petabyte.

Failure detection uses gossip with indirect probing and a suspect state (SWIM-style). If node A can't reach node B, it asks a few other nodes to try B too (indirect probing), and B is first marked "suspect" rather than dead, with time to answer. This matters because a node frozen for a second by a garbage-collection pause shouldn't be evicted, and a single bad network link between A and B shouldn't make B look dead to everyone.

#8. Storage engine per node

LSM tree. Each write goes into a memtable (a sorted in-memory table) and is appended to a WAL (write-ahead log on disk, so a crash loses nothing). When the memtable fills, it's written out as an SSTable — a sorted file that is never modified afterwards. Background compaction merges SSTables together and throws away overwritten values.

   WRITE:  WAL append (sequential) + memtable insert  → very fast
   READ:   memtable → Bloom filter per SSTable → sparse index
           → block read

The Bloom filter per SSTable is essential: without it, every read for a missing key would scan every file at every level.

#9. Request flow

   PUT(key, value)
     1. client → any node (that node becomes coordinator)
     2. coordinator computes the preference list from the ring
     3. sends the write to the top N healthy nodes
     4. waits for W acks
     5. returns success (with the new version vector)

   GET(key)
     1. coordinator computes the preference list
     2. requests from N nodes, waits for R responses
     3. if versions differ:
          - one dominates → return it, repair the others
          - concurrent    → return all siblings to the client

A nice property worth noting: clients can cache the ring and route directly to a replica, eliminating the coordinator hop entirely — "zero-hop" routing. That takes a network round trip out of every request.

#10. Failure modes & follow-ups

FailureBehaviour
One node downHinted handoff keeps writes succeeding. Reads still meet R from remaining replicas. No user impact.
Whole AZ downWith AZ-aware placement, each key still has 2 of 3 replicas. W=2/R=2 still satisfiable — barely. Worth noting the margin is thin.
Network partitionBoth sides keep serving (AP). Divergence resolved by vector clocks and Merkle repair when it heals.
Node permanently lostReplace it; the new node bootstraps from replicas via Merkle comparison. Throttle this — replacement traffic competes with foreground reads.
Hot keyConsistent hashing spreads keys, not load. One key at 40% of traffic saturates its replicas. Needs caching or key-splitting.

Follow-ups:

  • "How do you add a node?" — it claims vnode positions, streams ranges from current owners, then the ring updates. Throttle the transfer; it's a lot of bytes.
  • "Range scans?" — not supported by a random (hash) partitioner, because hashing scatters neighbouring keys across the ring. Requires an ordered partitioner, which reintroduces hot spots on sequential keys: if keys are timestamps, every new write lands at the end of the range, on the same node. A genuine architectural fork worth naming.
  • "How would you add strong consistency?" — put a Raft group per partition instead of quorum replication. That's essentially the design of Spanner/CockroachDB, and it trades availability and latency for linearizability. Being able to describe both architectures and when each is right is a strong close.
  • "Secondary indexes?" — either local (query every partition — scatter-gather) or global (a separate index, eventually consistent). Both have real costs; there's no free version.

#Check yourself

What resource sizes a 1 PB key-value cluster at 1 million QPS?Show answer
Storage, not throughput: 3 PB with replication ÷ 4 TB per node ≈ 750 nodes at only ~1,300 QPS each — so choose dense storage nodes.
Why are virtual nodes non-negotiable?Show answer
Without them a failed node's keys all land on one successor, which may fail in turn and cascade. With ~200 vnodes per node, load spreads across the cluster and hardware can be weighted.
What is the preference-list trap?Show answer
Taking the next N virtual nodes can put several replicas on the same physical machine; walk clockwise collecting N distinct physical nodes, ideally in different AZs.
What does R + W > N give you — and not?Show answer
Read and write sets overlap, so reads see the latest completed write, tunable per request. Not linearizability: concurrent writes conflict, failed writes can resurface, reads can go backwards.
Why vector clocks rather than last-write-wins?Show answer
Clock skew makes LWW silently drop the real latest write. Vector clocks record what each writer had seen: a dominating version wins, truly concurrent ones are kept as siblings for the application to merge.
Why does a shopping cart merge siblings by union?Show answer
A business choice: a partition may resurrect a removed item, but can never lose an added one — a spurious item is an annoyance, a lost purchase is lost revenue.
Hinted handoff, read repair and Merkle trees — which failure does each handle?Show answer
Hinted handoff: temporary failure (a neighbour holds writes, a sloppy quorum). Read repair: hot data, fixed during reads. Merkle trees: cold data and permanent loss, exchanging only differing subtrees.
How would you make this store strongly consistent?Show answer
A Raft group per partition instead of quorum replication — the Spanner/CockroachDB design, trading availability and latency for linearizability.

#What to carry forward

  • No queries, joins or transactions — that constraint makes Dynamo possible.
  • Consistent hashing with vnodes, gossip membership and symmetric nodes: no special node.
  • Quorums are tunable per request but aren't linearizable; say so precisely.
  • Vector clocks expose concurrent writes; merging is often a product decision.
  • Three repair mechanisms for three failure durations: hinted handoff, read repair, Merkle anti-entropy.
00:00
/ 11m