To design a key-value store is to decide how a huge set of small records is split across many machines, how many copies are kept, what a read is allowed to return when copies disagree, and how the system heals after a machine fails. A good answer states the guarantees it gives, shows with numbers what each choice costs, and says honestly where it breaks.

This lesson designs the saved-trips store of BusTrack, the bus tracking app from Load Balancing: Introduction. Every rider keeps a list of saved trips and stops. Six runnable programs in Java, with Python and C++ versions, test the decisions interviewers probe most: how one machine stores and finds data, how many replicas must agree, how to handle two edits at once, how a returning node catches up, how to decide a node is dead, and why deleted data can come back. All timings and capacities are assumptions chosen to make comparisons clear, not benchmarks of a product.

Key takeaways

  • On one node, a lookup for an id that does not exist opened 95 files. Merging files cut that to 8, and adding a Bloom filter to each file cut it to 0.06 disk reads on average.

  • With 3 replicas, writing to 1 and reading from 1 returned stale data 32.87% of the time. Writing to 2 and reading from 2 never did, at a write time of 11.9 ms instead of 6.2 ms.

  • When two phones edit the same list, last-write-wins lost a stop in 26.52% of cases. Keeping both versions with vector clocks and merging on read lost none.

  • A returning node held 1,186 old keys. Hints and read repair left 703. A Merkle-tree sync found them by comparing 7,351 hashes instead of 100,000 keys.

  • A failure detector is always a trade between speed and false alarms: a 1.5 second timeout noticed a crash in 1.1 seconds and raised 52 false alarms in a busy half hour.

  • If a node stays down longer than the tombstone retention period (gc_grace), the deleted data it still holds comes back. With a 1 day grace period and 5 days of downtime, all 1,000 deleted trips returned.

1. Clarifying Requirements

Functional requirements

  • put(key, value), get(key) and delete(key) for small values (a rider's saved trips, about 600 bytes).

  • Reads and writes by key only. No joins and no ad hoc queries.

  • Data survives the loss of a machine.

  • The cluster grows and shrinks without downtime.

Non-functional requirements

  • Always writable: a rider should be able to save a trip even when one replica is down.

  • Low latency, a few milliseconds at the 99th percentile for a read.

  • Tunable consistency: the app can ask for a stronger read when it needs one.

  • Scale by adding nodes, with no single master that every request must pass through.

Say what you leave out: transactions across keys, secondary indexes, and strict ordering of all writes. If the interviewer needs those, the answer is a different kind of store (see the last section). This is the choice the CAP theorem describes: when the network splits, we keep accepting writes and repair the differences later.

2. Back-of-the-Envelope Estimation

  • Data: 40 million riders with 12 saved trips each at about 600 bytes is 288 GB. With 3 copies that is 864 GB. Storage is not the limit.

  • Traffic: at peak 50,000 reads and 10,000 writes per second. A write goes to 3 replicas (30,000 replica writes per second). With a read quorum of 2, a read touches 2 replicas (100,000 replica reads per second). That is 130,000 replica operations per second.

  • Nodes: we assume a node handles 10,000 operations per second. 130,000 operations on 22 nodes is 5,909 per node (59%), rising to 6,190 (62%) after one node fails.

  • Disk writes: from the first program, merging files makes a node write each value about 2.45 times. Plan disk bandwidth for that, not for 1.

3. Core APIs

The store exposes a small data API and an operations API.

  • GET /v1/trips/{riderId}?read=one|quorum|all returns the value, or several versions when edits overlapped, plus a context token.

  • PUT /v1/trips/{riderId} sends the new value and the context from the read it is based on. A query option write=one|quorum|all sets how many replicas must acknowledge.

  • DELETE /v1/trips/{riderId} stores a tombstone (section 10).

  • POST /v1/cluster/nodes adds a node; POST /v1/cluster/nodes/{id}:decommission removes one by moving its data first.

  • GET /v1/cluster/status lists each node's state, hints waiting and repair progress.

A read that finds overlapping edits returns every version, so the caller can merge them:

{
  "key": "rider-4471",
  "versions": [
    { "value": ["HYD-0412", "HYD-0987"], "clock": {"n1": 3, "n2": 1} },
    { "value": ["HYD-0412", "SEC-0120"], "clock": {"n1": 3, "n3": 1} }
  ],
  "context": "opaque-token-for-the-next-put"
}

4. High-Level Design

Every node runs the same software and any node can receive a request. The node that receives it is the coordinator: it finds the replicas for the key, sends the request to them, waits for enough answers and replies. There is no master, so there is no single point of failure and nothing that limits throughput.

Placement. The key is hashed onto a ring and its replicas are the next 3 distinct nodes clockwise. This is the technique from Consistent Hashing, so adding a node moves only a small share of the keys. Each node also owns many small ranges (virtual nodes) so load stays even.

Each replica keeps its data on disk in a log-structured merge tree, covered next. The rest of the lesson takes the hard questions one at a time: how many replicas must agree, what to do with two edits at once, how a node catches up, how a node is judged dead, and what a delete really does.

5. One Node: Storing and Finding Data

A node must take writes fast and find a key quickly. The common answer is a log-structured merge tree (LSM tree). A write is added to a log (for safety) and to an in-memory table, the memtable. When the memtable is full it is written out as one sorted, never-changed file. A read checks the memtable, then the files from newest to oldest. Writes are cheap because disk writes are sequential. The price is that a read may have to look in many files.

Two tools control that price. Merging (compaction) combines files and drops old copies of overwritten keys. A Bloom filter per file answers "this file certainly does not hold the key" from a small bit array in memory, so the file is not opened.

The first program simulates one node: 200,000 writes over 50,000 trip ids (a few ids are written far more often), a memtable of 2,000 ids, then 20,000 reads, 80% for ids that were used and 20% for ids that never existed. The Bloom filter uses 10 bits per id and 7 hash probes.

Output

One storage node of the saved-trips store: 200000 writes over 50000 trip ids (a few ids are written far more often than others).
A full memtable (2000 ids) is written out as one file. Then 20000 reads: 80% ask for ids that were used, 20% for ids that never existed.
A read checks the memtable for free, then the files from newest to oldest. Each file it opens counts as one disk read.

setup                              files     disk reads    disk reads    ids written   copies stored  Bloom
                                             (id found)    (id absent)   per write     per id         memory
no merging, no Bloom filter        95        15.63         95.00         0.95          4.73           -
no merging, Bloom filter           95        1.04          0.79          0.95          4.73           231 KB
merge 4 files per level, no Bloom  8         4.72          8.00          2.45          2.09           -
merge 4 files per level + Bloom    8         0.95          0.06          2.45          2.09           102 KB
  • With no merging and no filters the node had 95 files. A lookup for an id that existed averaged 15.63 disk reads, and an absent id needed all 95.

  • Bloom filters alone cut those to 1.04 and 0.79. The 0.79 is the filters' false alarms: about 0.8% of the 95 files were opened for nothing. They cost 231 KB of memory.

  • Merging 4 files per level left 8 files. Reads fell to 4.72 and 8.00 without filters.

  • Both together gave 0.95 and 0.06 reads, with 102 KB of filters (filters are rebuilt for the merged, smaller set).

  • The cost of merging is writing data again: 2.45 ids written to disk per user write, against 0.95 without merging. Without merging each id also had 4.73 stored copies on average, against 2.09 with it, so merging saves space as well.

The 0.95 for "id found" is below 1 because some ids were found in the memtable for free. "Absent" also includes the few low-numbered ids that were never written. This is the standard trade of an LSM tree: fast writes, more disk work in the background. A B-tree (used by many relational databases) updates pages in place and reads one place, but pays random writes.

6. Replication and Quorums

With 3 replicas, how many must acknowledge a write (W) and how many must answer a read (R)? If W + R > N, every read set overlaps every acknowledged write set, so at least one answer holds the latest acknowledged value. If not, a read can miss it.

The second program stores one trip on 3 replicas. A write is sent to all 3 and applied after 2 to 19 ms. Each copy is slow (+150 ms) 5% of the time. A read starts 0 to 9 ms after the write was acknowledged, asks all 3 replicas, and uses the first R answers. We count reads that did not see the new value. It then makes replica 3 always slow (+200 ms).

Output

A saved trip lives on 3 replicas. 100000 write-then-read pairs per row; the read starts 0 to 9 ms after the write was acknowledged.

Healthy cluster: 5% of write copies are slow (+150 ms)
setting      W+R > 3   stale reads    write time     read time
W=1, R=1   no        32.87%         6.2 ms         4.3 ms
W=2, R=1   no        12.35%         11.9 ms        4.3 ms
W=1, R=2   no        8.99%          6.2 ms         6.0 ms
W=2, R=2   yes       0.00%          11.9 ms        6.0 ms
W=3, R=1   yes       0.00%          35.8 ms        4.3 ms
W=1, R=3   yes       0.00%          6.2 ms         7.7 ms

Replica 3 is always slow (+200 ms)
setting      W+R > 3   stale reads    write time     read time
W=1, R=1   no        41.47%         7.5 ms         4.3 ms
W=2, R=1   no        27.11%         13.5 ms        4.3 ms
W=1, R=2   no        11.12%         7.5 ms         6.0 ms
W=2, R=2   yes       0.00%          13.5 ms        6.0 ms
W=3, R=1   yes       0.00%          210.4 ms       4.3 ms
W=1, R=3   yes       0.00%          7.5 ms         7.7 ms
  • Healthy cluster: W=1, R=1 returned stale data 32.87% of the time. W=2, R=1 gave 12.35% and W=1, R=2 gave 8.99%. Every setting with W + R > 3 gave 0.00%.

  • W=2, R=2 took 11.9 ms to write and 6.0 ms to read. W=3, R=1 reads in 4.3 ms but its write took 35.8 ms, because it waits for the slowest copy.

  • With replica 3 always slow, W=3 wrote in 210.4 ms. W=2, R=2 stayed at 13.5 ms write and 6.0 ms read and still returned 0.00% stale reads.

  • W=1, R=3 is also correct but any one slow or dead replica blocks every read.

Two cautions. The guarantee only covers reads that start after the write was acknowledged, and a read that overlaps a write in flight can still see either version. And with W=2, R=2 the store stops accepting writes if 2 of 3 replicas are down. See Consistency Models for the names of these guarantees. A common default is W=2, R=2 for data that must not go stale, and W=1 where being always writable matters more.

7. Concurrent Edits and Versions

When a rider edits the saved trips from two phones, the two edits may reach different replicas before they know about each other. The store must decide what the final value is. The simplest rule is last write wins (LWW): keep the value with the larger timestamp. It is easy and it silently loses data, and it trusts the clocks of the phones and servers.

A vector clock records, for each node that took a write, how many it took. Comparing two clocks tells whether one version came after the other or whether they overlapped. If they overlapped, the store keeps both and returns both on the next read. The caller merges them (for a list of saved stops, take the union) and writes the merge back with the context it was given.

The third program has two parts. Part 1 is a clean case: phone B read phone A's edit and then edited, 1 to 2,000 ms later, so B's edit must win. Each phone's clock is wrong by a random amount. Part 2 is messier: each phone adds a different stop, edit 1 reaches B's server after 50 to 1,499 ms, B edits 0 to 2,999 ms after A, and clocks are wrong by up to 500 ms.

Output

Saved stops of one rider, edited from two phones. 100000 pairs of edits per row.

Part 1: the second phone read the first edit before making its own, so the second edit must win.
phone clock error      last-write-wins kept       vector clocks kept
                       the OLDER edit             the older edit
+/- 0 ms               0.00%                      0.00%
+/- 20 ms              0.34%                      0.00%
+/- 200 ms             3.44%                      0.00%
+/- 2 s                28.81%                     0.00%
+/- 30 s               48.22%                     0.00%

Part 2: each phone adds a different stop; clocks are wrong by up to 500 ms.
edits that really overlapped (second edit made before the first arrived): 25.71%

strategy                           lists missing a stop       reads showing two versions
last-write-wins                    26.52%                     0.00%
vector clocks + merge on read      0.00%                      25.71%
  • With perfect clocks LWW never went wrong in part 1. With a clock error of 20 ms it kept the older edit in 0.34% of cases, 200 ms in 3.44%, 2 seconds in 28.81% and 30 seconds in 48.22%. Vector clocks kept the older edit 0% of the time because edit 2's clock includes edit 1.

  • In part 2, 25.71% of edit pairs really overlapped. LWW left a stop missing in 26.52% of lists, a little more than the overlap because clock errors also reordered some edits that were not concurrent.

  • Vector clocks plus a merge lost nothing. The price: 25.71% of reads saw two versions and the application had to merge them.

The vector clocks here have two entries. In a real cluster they grow with the number of coordinators, so stores prune them, which can make some ordered edits look concurrent (extra merging, not lost data). Another option is a data type that merges itself, such as a set that only ever adds (a CRDT). LWW is still reasonable when overwrites are harmless, such as a "last seen" time.

8. A Node Returns: Hints, Read Repair and Merkle Trees

When a replica is down, writes still succeed on the others, so the returning node is out of date. Three mechanisms bring it back, from cheapest to most complete.

  • Hinted handoff: a node that could not reach a replica keeps the write (a hint) and delivers it when the replica returns. Hints are kept only for a limited time.

  • Read repair: when a read finds replicas disagreeing, the coordinator sends the newest value to the stale ones. It only fixes keys that are read.

  • Anti-entropy with Merkle trees: replicas compare a tree of hashes, descend only into the branches that differ, and copy only the keys that are different.

The fourth program has node C of a 3-node group down for 60 seconds while 20 writes per second go to nodes A and B over 100,000 keys. A keeps hints for C only during the first 20 seconds. After C returns, clients read 200 keys per second for 30 seconds. The tree has 8 keys per leaf.

Output

Node C of a 3-node group is down for 60 s. 20 writes/s go to nodes A and B over 100000 trip keys (a few keys are written far more often).
Node A keeps hints for node C only during the first 20 s of the outage. After C returns, clients read 200 keys/s for 30 s.

step                                           keys on C that still hold an old value
C is back, nothing done                        1186
hinted handoff replayed                        794
+ read repair for 30 s                         703  (91 repaired by reads)
+ Merkle-tree sync                             0

Merkle-tree sync cost: one tree over 100000 keys, 8 keys per leaf. Comparing every key would check 100000 keys.
case                                         hashes compared   leaves that     keys compared   keys streamed
                                                               differ
sync right away, hints and reads not used    7351              1090            8720            1186
sync after hints + read repair               5415              673             5384            703
sync when a single key differs               29                1               8               1
  • C came back with 1,186 keys holding an old value. Replaying the hints left 794 (the hints covered only the first 20 seconds). Read repair for 30 seconds fixed another 91 keys and left 703: reads only repair keys that are read.

  • A Merkle sync right after C returned compared 7,351 hashes, found 1,090 leaves that differed, compared 8,720 keys inside them and copied the 1,186 that were old. Comparing every key would have checked 100,000.

  • After hints and read repair the sync needed 5,415 hashes and copied 703 keys.

  • When a single key differed, it needed 29 hashes and compared 8 keys.

A Merkle tree pays off only when few keys differ. In a trial with 10,000 keys and 10 minutes of heavy writes, nearly every key changed and the tree saved nothing. Run it regularly to keep the gap small, and do not expect it to be cheap after a very long outage. The tree must also be rebuilt or updated as data changes, which has a cost of its own.

9. Deciding That a Node Is Dead

Nodes send heartbeats. A node that has been silent for longer than a limit is suspected. The limit is a trade: short means a quick reaction and more false alarms when the network is busy, long means few false alarms and a slow reaction. A false alarm is expensive, because it can start moving data around for a node that was only slow.

The fifth program has node X send a heartbeat every second for an hour. In the first half hour heartbeats are 20 to 79 ms late and 1% are delayed up to 3 seconds. In the second, busier half hour they are 20 to 319 ms late, 3% are delayed up to 2 seconds and 0.3% are paused for 5 to 10 seconds. It compares fixed timeouts, an adaptive timeout (the mean of the last 100 gaps plus 4 or 8 times their spread), and a fixed timeout where 3 helper nodes must also fail to reach X before it is declared dead. The helper rows assume each helper fails independently, 10% of the time in the quiet half and 25% in the busy half.

Output

Node X sends a heartbeat every second for one hour. Gaps are checked once a window of the last 100 gaps is full.
Quiet half hour: heartbeats arrive 20-79 ms late, 1% are delayed up to 3 s.
Busy half hour: 20-319 ms late, 3% delayed up to 2 s, 0.3% paused for 5-10 s. Node X never really fails in the alarm columns.

detector                            false alarms           average time to notice a real crash
                                    quiet      busy        quiet        busy
fixed timeout 1.5 s                 17         52          1.08 s       1.29 s
fixed timeout 3 s                   6          7           2.58 s       2.79 s
fixed timeout 10 s                  0          0           9.58 s       9.79 s
adaptive: mean + 4 x spread         16         23          1.31 s       2.49 s
adaptive: mean + 8 x spread         11         11          2.05 s       4.20 s
fixed 1.5 s + 3 helpers must agree  0          0           1.58 s       1.79 s

gaps checked: quiet 1699, busy 1800.
  • A fixed 1.5 second timeout noticed a real crash in about 1.1 seconds, and raised 17 false alarms in the quiet half hour and 52 in the busy one.

  • A fixed 3 second timeout raised 6 and 7, and noticed a crash in about 2.6 to 2.8 seconds. A fixed 10 second timeout raised none and took about 9.6 to 9.8 seconds.

  • The adaptive timeout (mean plus 8 spreads) raised 11 and 11 false alarms, so its alarm rate stayed steady as the network got noisier, but it took 4.20 seconds to notice a crash in the busy half. It was not better than a well-chosen fixed 3 second timeout here, because delays with rare large spikes are not well described by a mean and a spread.

  • Asking 3 helpers before acting removed the false alarms in this run (0 and 0) and added about half a second (1.58 and 1.79 seconds). That depends on the helpers failing independently. If they share the same congested network, they fail together.

Real systems use the same ideas with more care, for example a suspicion score that grows with silence, and gossip so that every node learns of a failure. Treat "suspected" and "dead" as different states: suspect quickly, but move data only after a longer, confirmed outage.

10. Deletes and Tombstones

A delete cannot just erase the value. The other replicas may still hold it, and a repair would copy it back. So a delete is a write of a marker, a tombstone, that replicates like any value and wins over older versions. Tombstones cannot be kept forever, so each node purges one after a retention time (gc_grace).

The danger is a node that was down while the delete happened and returns after the tombstones were purged. It still has the old value, and nobody holds a tombstone to say it was deleted, so repair treats its value as the newest one. The deleted data returns.

The sixth program deletes 1,000 of 10,000 trips during 2 days on nodes A and B while node C is down. It counts how many come back for different retention times and outage lengths, compares two ways to bring C back, and counts how many tombstones are stored at different retention times for 1,000 deletes a day.

Output

Node C is down while 1000 of 10000 saved trips are deleted on nodes A and B (deletes spread over 2 days).
A tombstone is purged gc_grace after its delete. When C returns, repair copies the newest version; a purged delete leaves nothing to compare.

deleted trips that come back to life (out of 1000):
gc_grace \ C was down    1 hour       1 day        5 days       12 days
1 hour                   0            485          1000         1000
1 day                    0            0            1000         1000
3 days                   0            0            1000         1000
10 days                  0            0            0            1000

C was down 5 days and gc_grace is 1 day. What to do when C returns:
action                                  zombies   keys copied between nodes
rejoin and run repair                   1000      1000 (from C to A and B)
wipe C, rebuild it from A and B         0         9000 (from A and B to C)

Cost of a long gc_grace: 1000 deletes a day for 30 days. Tombstones still stored on day 30:
gc_grace   tombstones stored   node may be down at most
1 hour     46                  1 hour
1 day      998                 1 day
3 days     2999                3 days
10 days    10000               10 days
  • With a 1 hour retention, a node that was down for 1 day brought back 485 deleted trips, and one that was down 5 days brought back all 1,000.

  • With a 1 day retention, an outage of 1 day was safe but 5 days brought back all 1,000. With 10 days, 5 days was safe and 12 days brought back all 1,000.

  • If C was down 5 days with a 1 day retention, letting it rejoin and repair brought back 1,000 deleted trips, copying them from C to A and B. Wiping C and rebuilding it from A and B brought back none, and copied 9,000 live keys.

  • The cost of a long retention: with 1,000 deletes a day, 1 hour kept 46 tombstones on day 30, 1 day kept 998, 3 days kept 2,999 and 10 days kept 10,000, as many as the live keys in this example. Reads must skip over them.

The rule that follows: never let a node rejoin after being down longer than the retention period; rebuild it instead, and run repair on every node more often than the retention period.

11. Choosing the Design

NeedChoiceCost
Always accept writesW=1, keep versions, repair in the backgroundStale reads and merging in the app
Never read stale dataW + R > N (for example 2 and 2)Writes fail if too many replicas are down
Strict order of all writesA consensus-based store with one leader per rangeLower availability during partitions, higher latency
Cheap deletes at scaleTombstones with a retention periodNever rejoin a node after the period

A store like this suits data that is read and written by one key and where one user rarely edits from several places at once: sessions, carts, profiles, saved items. It is a poor fit for money transfers or anything needing a transaction across keys.

12. Trade-offs to Mention

  • Availability against consistency: W=1 keeps accepting writes during failures; W + R > N keeps reads fresh. Pick per operation if the API allows it.

  • LSM trees give fast writes and cost background merging and read work. Bloom filters spend memory to save disk reads.

  • LWW is simple and loses data; vector clocks keep data and push merging to the application.

  • A short failure timeout reacts fast and raises false alarms; confirmation by other nodes costs time.

  • Long tombstone retention is safe for longer outages and stores more deleted markers.

  • No master means no bottleneck, and the cluster must agree on its own membership through gossip.

13. Common Mistakes

  • Saying "eventually consistent" without saying how stale and how it is repaired.

  • Using W + R > N and forgetting that it only covers reads that start after the write was acknowledged.

  • Using last-write-wins on data where losing an edit is not acceptable.

  • Trusting wall clocks across machines.

  • Setting one failure timeout without testing it on a busy network.

  • Letting a node that was down for a long time rejoin with its old data.

  • Designing the happy path and skipping what happens when a node returns.

14. Interview Questions

  • How do you place keys on nodes? Hash onto a ring, take the next N distinct nodes, and use virtual nodes for even load.

  • What does W + R > N guarantee? That a read set and an acknowledged write set overlap, so a read sees the latest acknowledged write if it starts after the acknowledgement.

  • Two clients write the same key at once. What happens? With LWW one is lost; with vector clocks both are kept and the application merges.

  • A node was down for an hour. How does it catch up? Hinted handoff for recent writes, read repair for keys that are read, Merkle-tree anti-entropy for the rest.

  • Why can deleted data reappear? A node that missed the delete returns after the tombstone was purged. Rebuild such nodes.

  • How do you stop one slow node from looking dead? Do not decide from one observer; ask others, and separate suspected from confirmed.

Summary

  • Every node can coordinate; keys map to N replicas by a hash ring.

  • Each node uses an LSM tree: merge files and add Bloom filters so reads stay cheap.

  • Choose W and R from the product's needs, remembering W + R > N.

  • Keep both versions of overlapping edits and merge them; do not trust clocks.

  • Heal with hints, read repair and Merkle trees.

  • Suspect quickly, confirm slowly, and never rejoin a node that outlived the tombstones.

Conclusion

A key-value store is simple to describe and hard to run well, because every shortcut shows up as a failure case: a stale read, a lost edit, a false alarm, a deleted record that returns. The design above handles each with a mechanism and a number. In an interview, name the failure, show what it costs, and say which trade you chose.

Previous topic: Design API Gateway. Next topic: Design Distributed Cache.

References and further reading

  • DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store (SOSP 2007), the source of quorums, vector clocks, hinted handoff and Merkle-tree anti-entropy in this style of design.

  • O'Neil et al., The Log-Structured Merge-Tree (1996), and Chang et al., Bigtable (OSDI 2006), for the storage engine.

  • B. H. Bloom, Space/Time Trade-offs in Hash Coding with Allowable Errors (1970).

  • Hayashibara et al., The Phi Accrual Failure Detector (2004), for suspicion scores.

  • Consistent Hashing, CAP Theorem and Consistency Models on this site.