Systemsfor Aravinda
0 / 78 core
Week 9 · Case studies

Design a key-value store

2 hours · core path

Read first: Partitioning and sharding, Replication, Quorums and leaders, Consensus and Raft

In one sitting

A put should succeed when one of three replicas is unreachable, which means a hash ring, a quorum, and hinted handoff rather than a leader per key. Reads overlap writes so a healthy ring returns the latest value, and concurrent puts become two versions the client must merge. This is an interview design in the shape of the Dynamo paper, not a guide to reimplementing it, and it is not DynamoDB.

This is an interview design for a store that accepts a put when one replica cannot be reached. The shape follows the Dynamo paper: a hash ring, N replicas, a quorum, hinted handoff, and a way to see that two puts were concurrent. It is not a tutorial you could reimplement that paper from. Membership gossip, the exact Merkle-tree repair, and the client merge protocol are specified in the paper and in the Dynamo story. Copying them from memory is not the interview. And the paper is not the product DynamoDB, which later used a primary per partition and conditional writes.

Requirements

The caller is an application, not a person at a shell. The person in the story has a shopping bag open on a phone and a laptop. If one of your storage nodes is down, adding milk on the phone should still succeed.

Functional requirements:

  • get(key) and put(key, value). Values are opaque bytes with a version the store understands.
  • A put succeeds when one of the three preferred replicas for that key is unreachable.
  • A get, in the healthy case, returns the latest put that reached a write quorum.
  • If two puts land without either having seen the other, the store returns both versions. It does not pick a silent winner for an opaque value.
  • One key’s operations are the scope. You do not get a transaction across keys.

Non-goals:

  • Range scans, secondary indexes, and search. The partition is by hash. Range scans would want a different split.
  • Multi-key transactions. A bag is one key whose value is the whole bag.
  • Linearizability. You are not promising that the store behaves like one copy with each operation taking effect at a single instant. If the interviewer wants that, you change the design to a leader and you give up puts that succeed through a partition.
  • A tutorial-complete rebuild of the 2007 paper.

Assumption you state as the durability bar: a successful put means the value is on the durable log of W replicas, not merely in their memory. You wait for those logs. You do not wait for all N.

Estimation

Assumptions:

  • 10 million clients in a day.
  • Each does 15 gets and 3 puts. Assumption about the app, not a measured trace.
  • Peak is 3 times the average. Assumption.
  • A typical value is 1 KB. A hard cap you enforce is 100 KB. Both are assumptions.
  • 80 million live keys. Sessions and bags expire. You are not keeping a trillion rows.
  • N is 3, so every successful put is stored three times once repair finishes.

A day is 86,400 seconds. Sketch with 1e5, then divide by 86,400.

gets   150,000,000 / 86400 = 1,736 per second
shortcut 150,000,000 / 1e5 = 1,500 per second
puts    30,000,000 / 86400 = 347 per second
shortcut  30,000,000 / 1e5 = 300 per second
peak gets, 3x  = about 5,200 per second
peak puts, 3x  = about 1,040 per second

The shortcut is about 14 percent low. One million requests a day is about 12 per second, so you are well above the toy number and still in the range where the per-key protocol matters more than the node count.

peak put bytes, client side   1,040 * 1 KB = about 1 MB/s
once replicated three times   = about 3 MB/s of payload
80e6 live keys * 1 KB         = 80 GB
times replication 3           = 240 GB before versions and hints

240 GB is a modest cluster, a handful of machines with room for compaction and a spike. If the interviewer multiplies the QPS by ten, you add nodes. The ring, the quorum, and the conflict rule do not change. A bigger number does not make one hot key any safer. Consistent hashing moves about 1/N of the keys when you add a node. It never splits a single key.

Bandwidth is not the constraint. A same-datacenter round trip is 0.5 ms. The write waits for two durable appends in that building. On modern flash a log append is often tens of microseconds, not the 10 ms spinning-disk seek on the old teaching list. Budget a few milliseconds for a put and measure the disk you have. Do not quote a cloud price, and do not pretend you measured it.

High-level design

flowchart LR
  client[Client] --> coord[Coordinator]
  coord --> nodeA[Replica A]
  coord --> nodeB[Replica B]
  coord --> nodeC[Replica C]
  coord --> hint[Fallback holding a hint]

Hash the key onto a ring. Walk clockwise. The first N distinct physical nodes are the preference list. N is 3. Virtual nodes, many ring positions per machine, keep the balance from depending on three unlucky hashes. Adding a machine moves about one Nth of the keys, not almost all of them. Modulo hashing would move almost everything. That is the Karger result you actually use.

Any node can coordinate a key. The coordinator sends the put to the preference list and waits for W responses. It sends the get and waits for R. With W = 2 and R = 2, a healthy read set overlaps a healthy write set, so the reader sees the latest put. Quorums are that overlap argument. They are not, by themselves, linearizability.

Each replica stores its own keys in a local engine aimed at point reads. An LSM or a B-tree both work at this size. You do not need range iteration, so the hash split is acceptable. Pick the engine in a sentence and move on. The interview is not the storage-engine interview unless they turn it into one.

Membership is the part you must not fake in detail. Nodes need to agree, approximately, on who is in the ring. The paper uses gossip. You say “gossip, so a dead node leaves the preference list without a human editing a file,” and you stop. You cannot recite the paper’s protocol from this page, and you should not try.

Deep dive

Quorum, N = 3, R = 2, W = 2

N is how many replicas you intend to have. W is how many must acknowledge a put before you tell the client it succeeded. R is how many must answer a get before you return a value.

R + W is 4, and N is 3, so R + W is greater than N. Any two of the three preferred replicas include at least one replica that saw any write that reached two of them. The reader compares versions and keeps the newest. That is the happy path, and it is the path you draw first.

You can lose one replica and still read and write, because two survivors are enough for both quorums. You cannot lose two. “Always writable” in the requirement means one failure, not any failure. If two of the three preferred nodes are down and you refuse to write elsewhere, puts fail. Say the number. Interviewers listen for people who promise availability against every outage and then draw W = 2.

This overlap is not a linearizable register once you add sloppy quorums, retries, and lost replies. Consistency models are the vocabulary. The practical version: a reader can observe a put, a later reader can miss it if they hit a different pair and repair has not run, and a timed-out put may have landed even though the client is retrying. CAP is the reason you are choosing at all. During a partition you cannot have a response from every live node and a single-copy register. You chose the response.

If the product actually needs a single order, stop and switch. A leader per partition, elected with a lease or with consensus, makes every put a write on that leader’s log. You get one sequence. You lose the put when the leader’s quorum cannot be reached. Raft per put is the wrong tool for “the bag must accept a write during a partition,” and it is also the wrong thing to invent in the last ten minutes. Name the fork. Do not claim both sides.

Hinted handoff

A preferred replica is down. The coordinator still wants the put to succeed. It writes to the next healthy node on the ring, one that is not in the preference list, and it stores a hint: this value belongs to the node that was down. W can include that fallback, so the client gets success. When the preferred node returns, the fallback sends the hint home and deletes it.

Until that hint lands, a get that only asks the original preference list can miss the put. The overlap proof assumed the write landed on the preferred set. A sloppy quorum keeps availability and weakens the proof on purpose. You say that sentence. It is the whole point of the technique.

Hints are not the only repair, because a hint can die. The fallback can crash before it delivers, and then the put exists only on the preferred replicas that did acknowledge it. If W was satisfied by one preferred node and one fallback, and the fallback is gone, you have a single copy left. Anti-entropy is the slow path that compares replicas and copies what is missing. The paper uses Merkle trees for that comparison. This design only needs the idea: a tree of hashes so two replicas can find the keys that differ without shipping every key. Do not invent the tree’s fanout. Point at the paper.

Read repair is the cheap cousin. A get that sees two versions writes the winner back to the replica that was behind. It helps keys that are read. It does nothing for keys nobody reads. You want both. Hints for the keys written during the outage, a hash comparison for the ones hints lost, read repair for the ones people touch.

Conflict

Two devices, one bag, a network cut. The phone reads version V and puts a bag containing milk. The laptop, which also read V and cannot see the phone’s put, puts a bag containing bread. Each put reaches a quorum. Neither put’s version dominates the other.

A vector clock is how you notice. Each replica has a counter. A coordinator increments its own counter on a put and keeps the max of every counter it has seen. Version A dominates version B if every counter in A is at least the counter in B and one is greater. If neither dominates, the puts were concurrent. The get returns both values. The client merges.

For a shopping bag the merge is a union of items, if the value is a set of item ids and quantities are handled with a rule you can explain, such as “take the larger quantity.” For a setting like “theme is dark,” a union is nonsense and last-writer-wins is the product rule. Last-writer-wins needs a total order, usually a timestamp plus a replica id, and it will drop one of the two puts. Dropping milk is a bug. Dropping an older theme is fine. The store cannot guess which value it is holding if the bytes are opaque. The application defines the merge, or the application promises one writer.

Clocks grow when many replicas write the same key, and someone has to merge. That pain is in the paper. A server that simply keeps every version forever will fill the disk with abandoned conflicts. The client merge has to write back a single descendant that dominates the versions it merged, so the others can be dropped. If the client never writes back, the next reader sees the same pair again.

Do not reach for a consensus round to avoid the merge unless you are willing to reject the “writable during one failure” requirement. One writer per key, via a leader, removes the conflict by refusing the second writer when it cannot see the leader. That is a clean design for a feature flag. It is a bad design for the bag on the airplane.

Tradeoffs

Choice What you gain What you spend
Leaderless quorum, W = 2, R = 2, N = 3 A put succeeds with one preferred replica down Concurrent puts, and reads that must compare versions
Leader per partition One order, no client merge Puts fail when the leader quorum is unavailable
Sloppy quorum and hinted handoff The put still succeeds if a preferred node is the one that is down Overlap does not hold until the hint is delivered
Strict quorum only The overlap proof stays intact A single preferred-node failure can reject puts once a second node is slow
Vector clock and client merge You do not drop a concurrent bag update Clock metadata, and a client that must actually merge
Last-writer-wins One value, simple reads One of two concurrent puts disappears

The row you are defending is the first one, plus hinted handoff, plus a merge the shopping bag can define. If the value is a theme toggle, you say last-writer-wins and you stop pretending you need the paper’s full client protocol.

Failure modes

  • Two replicas down. W = 2 cannot be satisfied on the preferred set, and if you also cannot find a healthy fallback you trust, the put fails. The requirement was one failure. Symptom: error rate tracks a second node death, not the first. If your dashboard pages on every single-node blip, you built the wrong alert for the quorum you chose.
  • Hint lost. The fallback acknowledged, then died, and only one preferred replica ever stored the put. A later get can miss it or return an older version. Durable logs on the W nodes that acknowledged are the bar. A hint that lived only in the fallback’s memory was not durability. Anti-entropy against the surviving copy is how you find out. You may still have lost the put. Say that out loud. Availability choices move data loss into a narrower window. They do not delete the window.
  • Hot key. A global configuration key that every request reads sits on one preference list. Ten times the cluster QPS on one key does not get better when you add nodes. Cache that key at the client or replicate that one key onto every node on purpose. More partitions are the wrong sentence.
  • Retry storm. Clients time out at 5 ms and retry immediately while a replica is slow, so the remaining replicas receive the puts twice or more. Bound the retries, back off with jitter, and make the retry present the same idempotency token. A slow store plus a tight retry is how you finish the store off.
  • Split views of membership. Two coordinators disagree about the ring and write a key to different triples. Gossip converges, but the window produces the same symptom as a conflict. The merge has to handle it. A human-edited host file that is stale on one machine produces a longer version of the same bug.
  • A value the client cannot merge. Opaque JSON, two versions, and the application overwrites one with the other because it did not look at the clock. Symptom: milk disappears from the bag only when the two devices were offline together. The store did its job. The client treated a pair of versions as “pick index zero.”
  • Ack before the log is durable. A power loss on both W nodes after they replied and before they flushed drops a “successful” put. The fix is in the requirement: W durable appends, then the ack. The cost is those appends on the critical path.

In the interview

Spend the first five minutes on the requirement that forces the shape. “Can a put succeed if one replica is down, and can two clients write one key at the same time?” Yes and yes is this design. Draw the ring, say N = 3, R = 2, W = 2, and say the overlap in one sentence. Give the numbers: about 300 puts per second and 1,500 gets per second with the shortcut, peak around three times that, a few hundred gigabytes with three copies. The bottleneck is not capacity. It is a conflict, a lost hint, or a hot key.

Say, early, that you are not reimplementing the Dynamo paper and you are not proposing DynamoDB. You will not draw Merkle trees in detail. You will not run a consensus round per put.

Skip a Paxos lecture. If they ask “why not Raft,” the answer is the requirement: a leader fails the put when it cannot see a majority, and you were asked not to fail that put.

The question that follows is usually “both devices updated the bag.” You return two versions and the client unions them. The tradeoff you admit is that a get can be stale until a hint lands, and you refused to pretend the result is linearizable.

Check yourself

With three replicas, why do a read of two and a write of two guarantee overlap on the happy path?

Any subset of two replicas and any other subset of two replicas share at least one node, because 2 plus 2 is greater than 3. The shared node saw the write, if the write went to the preferred replicas the reader is also using. The reader still has to compare versions rather than trust whichever reply arrived first.

A preferred replica is down, so you write to a fallback and count it toward W. What did you give up until the hint is delivered?

You gave up the overlap proof. A get that queries the original preferred pair can miss the fallback and return an older value. Hinted handoff repairs that later. Until it does, the put was available and the read is not guaranteed to see it. If the fallback dies before delivering the hint, you may be down to one copy.

Two clients each put a different bag after reading the same version. What should a later get return, and why not a single winner?

Neither vector clock dominates, so the puts were concurrent. The get returns both values and the client merges. For a bag, the merge keeps both items. A silent last-writer-wins would drop milk or drop bread depending on a clock, which is data loss the product can see. A single winner is appropriate only when the product truly wants one, such as a theme setting.

Why is a Raft round per put the wrong way to meet the writable-during-one-failure requirement?

Raft commits when a majority has the entry, and only the leader appends. If the leader cannot reach a majority, the put fails. That is a single order, which this requirement traded away. Using consensus to elect a leader is a different design. Using it as the cost of every put does not make the bag more writable. It makes the bag wait for a quorum that may be on the other side of the partition.

Your steady put rate is a few hundred per second and the data is a few hundred gigabytes. A single key is half of all gets. What do you change?

Not the node count. Consistent hashing will keep that key on one preference list no matter how many nodes you add. Cache it outside the quorum path, or deliberately copy that one key everywhere. Adding machines fixes a large keyspace, not a hot key.

Based on: Dynamo, SOSP 2007, DeCandia and others; Karger and others, consistent hashing, 1997; Gilbert and Lynch, CAP; Designing Data-Intensive Applications, Kleppmann and Riccomini.