Courses / System Design Interview / Chapter 9
Module 2 · Building Blocks I: Names, Traffic and Data · Chapter 9 of 49
Design a Distributed Key-Value Store
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Building Blocks: The Parts Every Design Reuses, Load Balancers and Databases: Choosing, Replicating and Partitioning. Next up: Content Delivery Networks.
Part 1 · Requirements and API
What the store must do
A key-value store sits under shopping carts, sessions, feature flags and profile lookups, and its job is to answer one question fast: what is the value for this key. This chapter designs one that spreads across many machines and keeps working when some of them fail.
The functional requirements are small. A client can put a value under a key, get the value for a key, and delete a key. Keys are short strings. Values are opaque blobs of up to a few hundred kilobytes, and the store never looks inside them. There are no joins and no queries on values, and that narrow contract is what makes the rest of the design possible.
The non-functional requirements decide the design. The store must be highly available: a write should be accepted even while some nodes are down, because a shopping cart that refuses to take an item loses a sale. It must scale horizontally, so that adding machines adds capacity without a pause. Reads and writes should finish in a few milliseconds at the 99th percentile. And it must tolerate network partitions, where some nodes cannot reach others. These goals pull against strict consistency, so the store offers tunable consistency: each request chooses how many replicas it waits for, trading freshness for speed.
Several things are deliberately out of scope, and saying so early keeps the design honest. There are no transactions across keys, so two puts to different keys can be seen in either order. There are no queries by value and no secondary indexes. Range scans over keys are not supported, because hashing scatters neighbouring keys across nodes. A system that needs any of these should use a relational database or put another store beside this one, as the databases chapter explained. What remains is a fast, always-writable map, and many products need no more than that for carts, sessions and flags.
That is the design space of Dynamo, the key-value store Amazon described in a 2007 paper, and of its open-source relatives such as Cassandra. The parts of this chapter follow that design: partitioning with consistent hashing, replication with quorums, vector clocks for conflicts, Merkle trees and gossip to repair and track nodes, and a log-structured engine on each node.
The API and an estimate
The client-facing API is three calls. put takes an optional context, an opaque version token returned by an earlier get, which later lessons use to detect conflicting writes. consistency lets the caller pick how many replicas must answer.
PUT /v1/kv/cart:42 HTTP/1.1 X-Consistency: quorum X-Context: eyJ4IjoyLCJ5IjoxfQ {"items": ["dal", "rice"]} GET /v1/kv/cart:42 HTTP/1.1 X-Consistency: one DELETE /v1/kv/cart:42 HTTP/1.1
API sketch. Not run: the chapter builds the parts, not an HTTP server.
Capacity follows from a few assumptions, stated so they can be changed. Suppose the store holds 500 crore keys. Each value is about 1 KB and each key plus its metadata takes about 100 bytes. Every item is stored three times. A node has 2 TB of usable disk, and we keep it half full so there is room for growth and for the temporary copies that compaction makes. The traffic is 50,000 reads and 10,000 writes per second, and we assume one node sustains about 5,000 operations per second.
items = 5_000_000_000 # keys stored # about 1 KB per value, 100 B key and metadata value_bytes = 1_000 replicas = 3 node_disk_tb = 2 # usable disk per node # keep nodes half full for growth and compaction fill = 0.5 reads_per_s, writes_per_s = 50_000, 10_000 per_node_ops = 5_000 # assumed sustained ops per node raw_gb = items * (value_bytes + 100) / 1e9 stored_gb = raw_gb * replicas nodes_disk = stored_gb / (node_disk_tb * 1000 * fill) nodes_ops = (reads_per_s + writes_per_s * replicas) / per_node_ops print(f"raw data {raw_gb:,.0f} GB") print(f"with {replicas} copies {stored_gb:,.0f} GB") print(f"nodes by disk {nodes_disk:.2f}") print( f"nodes by ops {nodes_ops:.1f} (a write lands on {replicas} nodes)" )
est.py: nodes needed by disk and by operations
raw data 5,500 GB with 3 copies 16,500 GB nodes by disk 16.50 nodes by ops 16.0 (a write lands on 3 nodes)
Python 3.12.10 on this machine. Deterministic arithmetic from the stated assumptions.
Both limits point at sixteen or seventeen nodes: 16.5 by disk and 16.0 by operations. Writes count three times because each lands on three replicas, so replication multiplies write load. Agreement between the two numbers is luck in this example. In general the larger one wins, and the answer is a starting size, not a promise.
The estimate counts each write three times when sizing for operations. Why?
Part 2 · Partitioning with consistent hashing
The ring and virtual nodes
One machine cannot hold 500 crore keys, so the store must decide which node owns each key. Taking the hash of the key modulo the number of nodes is simple and fails when a node is added or removed, because nearly every key changes owner. The ring from the load balancer chapter avoids that: nodes and keys are hashed onto the same circle of numbers, and each key goes to the first node found going clockwise from the key's position.
When a node joins, it takes over only the keys between itself and the node before it. When a node leaves, its keys go to the next node clockwise. The idea comes from a 1997 paper by Karger and others on distributing web caches, and it is the placement scheme at the heart of Dynamo.
With one point per server the ring is uneven. A server whose neighbour happens to be close takes few keys, and one with a large gap takes many. The remedy, used by Dynamo, is virtual nodes: each physical server is placed on the ring at many positions, called tokens. The paper lists the benefits: when a node fails, its load spreads over many nodes instead of landing on one neighbour, a new node takes a roughly equal slice from each existing node, and a stronger machine can be given more tokens.
The ring below hashes five servers and 20,000 keys. It prints how many keys the most and least loaded servers get with one point per server and with 100, and then adds a sixth server to see which keys move.
import hashlib from bisect import bisect from collections import Counter def h(s): return int.from_bytes( hashlib.sha256(s.encode()).digest()[:8], "big") class Ring: def __init__(self, nodes, vnodes): self.vnodes = vnodes self.points = [] for n in nodes: self.add(n) def add(self, node): self.points += [(h(f"{node}#{i}"), node) for i in range(self.vnodes)] self.points.sort() self.hashes = [p[0] for p in self.points] def owner(self, key): return self.points[bisect(self.hashes, h(key)) % len(self.points)][1]
ring.py: the ring class
keys = [f"k{i}" for i in range(20_000)] nodes = [f"s{i}" for i in range(5)] for v in (1, 100): ring = Ring(nodes, v) load = Counter(ring.owner(k) for k in keys) lo, hi = min(load.values()), max(load.values()) print( f"vnodes={v:3} keys per server: min {lo:5} max {hi:5} " f"max/min {hi/lo:.1f}" ) ring = Ring(nodes, 100) before = {k: ring.owner(k) for k in keys} ring.add("s5") moved = [k for k in keys if ring.owner(k) != before[k]] print("added s5: moved", len(moved), "of", len(keys), "| all moved keys went to s5:", all(ring.owner(k) == "s5" for k in moved))
Reading the results
With one point per server, the busiest server held 10,673 keys and the quietest 1,029, a ratio of 10.4. With 100 points each, the range narrowed to 4,555 against 3,292, a ratio of 1.4. More tokens flatten the distribution, with diminishing returns.
The sixth server took 3,499 of the 20,000 keys, about a sixth, as expected for one of six nodes, and every moved key went to it. No other pair of servers exchanged data. That is the property the scene shows: a join or a leave touches one slice of the ring.
Watch for the owner of each key: the next server clockwise
Read it as steps
Keys belong to the next server clockwise, so a change moves only the neighbouring keys.
The scene also shows failure. When server B is removed, the keys it owned go to its clockwise neighbour. With virtual nodes the neighbours differ from token to token, so the load of a lost node is shared out. A real system also needs a way for every node and client to know the current ring, which a later lesson covers with gossip.
Clients still have to find the right node. There are two common arrangements. In one, a client sends the request to any node, and that node forwards it to the owner or coordinates it itself, so clients stay simple and an extra hop is sometimes paid. In the other, the client library holds a copy of the ring and sends the request straight to the right node, which saves the hop and makes every client a participant that must hear about ring changes. Dynamo's paper describes both. Either way, a node that receives a request for a key it does not own must be able to say so, and the request must be retried at the correct node after the ring changes.
Part 3 · Replication, quorums and hinted handoff
Replicas and the preference list
Each key is stored on N nodes so that a failed node does not lose it. Dynamo gives each key a home on the ring: the first node clockwise, plus the next N - 1 nodes. The list of nodes responsible for a key, in ring order, is its preference list. With virtual nodes several tokens in a row may belong to the same machine, so the list skips repeats to land on N distinct physical servers.
A client can send its request to any node, which need not be one of those homes, and that node acts as the coordinator for the request. As in the databases chapter, a write succeeds when W of the N replicas acknowledge and a read when R answer, and W + R > N makes the two sets overlap. The Dynamo paper notes that raising W shortens the window in which a write is held by few nodes, at the risk of rejecting more writes.
Strict quorums have a weak spot. If the coordinator insists on specific nodes and one of them is down, the write fails even though most of the cluster is healthy. A shopping cart that refuses an item because one replica is rebooting is a poor design.
Sloppy quorum and hinted handoff
Dynamo relaxes the rule. In a sloppy quorum, reads and writes use the first N healthy nodes in the preference list, which may not be the first N nodes on the ring. If a home replica is down, the coordinator sends its copy to the next healthy node. That node stores it in a separate local table together with a hint naming the intended owner, scans the table periodically, and hands the data off when the owner returns. Once the transfer succeeds, the stand-in deletes its copy, so the number of copies stays at N.
The sketch below builds a five-server cluster with N = 3, W = 2, R = 2. It takes down the first home replica of one key, writes, reads, brings the node back and replays the hints.
import hashlib from bisect import bisect def h(s): return int.from_bytes( hashlib.sha256(s.encode()).digest()[:8], "big") class Store: def __init__(self, name): self.name, self.up, self.data, self.hints = name, True, {}, [] class Coordinator: def __init__(self, names, n=3, w=2, r=2): self.nodes = {x: Store(x) for x in names} self.ring = sorted((h(x), x) for x in names) self.n, self.w, self.r, self.clock = n, w, r, 0 def preference_list(self, key): i = bisect([p[0] for p in self.ring], h(key)) order = [ self.ring[(i + j) % len(self.ring)][1] for j in range(len(self.ring)) ] return order # the first n are the home replicas
hinted.py: the cluster and the preference list
def put(self, key, value): self.clock += 1 order = self.preference_list(key) homes, spare = order[:self.n], order[self.n:] acks = [] for home in homes: node = self.nodes[home] if node.up: node.data[key] = (self.clock, value) acks.append(home) continue stand_in = next(s for s in spare if self.nodes[s].up and s not in acks) self.nodes[stand_in].hints.append( (home, key, (self.clock, value))) acks.append(f"{stand_in} (hint for {home})") return acks if len(acks) >= self.w else None
hinted.py: writes with hints
def get(self, key): homes = self.preference_list(key)[:self.n] seen = [ self.nodes[x].data.get(key) for x in homes if self.nodes[x].up ] return max( (s for s in seen if s), default=None) if len(seen) >= self.r else "unavailable" def replay_hints(self): for node in self.nodes.values(): for home, key, val in list(node.hints): if self.nodes[home].up: self.nodes[home].data[key] = val node.hints.remove((home, key, val)) print( f"{node.name} handed the hint back to {home}")
hinted.py: reads, and replaying the hints
The run
c = Coordinator(["a", "b", "c", "d", "e"]) print("preference list for cart:42 ->", c.preference_list("cart:42")) home = c.preference_list("cart:42")[0] c.nodes[home].up = False print(f"{home} is down") print("put acks:", c.put("cart:42", "2 items")) print("get while down:", c.get("cart:42")) c.nodes[home].up = True print("home copy before replay:", c.nodes[home].data.get("cart:42")) c.replay_hints() print("home copy after replay: ", c.nodes[home].data.get("cart:42"))
The script that runs it
preference list for cart:42 -> ['a', 'd', 'c', 'b', 'e'] a is down put acks: ['b (hint for a)', 'd', 'c'] get while down: (1, '2 items') home copy before replay: None b handed the hint back to a home copy after replay: (1, '2 items')
Python 3.12.10 on this machine. Deterministic: the ring uses SHA-256.
The preference list for the key began with a, which was taken down. The write returned acknowledgements from d and c, plus b holding a hint for a, so three copies exist although one home was down. A read during the outage found the value on the healthy home replicas. After a came back, its copy was still empty. The replay copied the value to it, and then the copy matched.
Watch for the node that is down: the write goes on without it
Read it as steps
The write still reaches two home replicas, and a stand-in holds a hint for the node that was down.
Part 4 · Versioning and conflicts
Why conflicts happen
With sloppy quorums and writes accepted at any node, two clients can update the same key at the same time through different coordinators. Neither write is wrong, and neither has seen the other. The store has to notice that and must not silently pick one. The simplest policy is last-write-wins, from the databases chapter: the highest timestamp is kept, and the other change is discarded without telling anyone. Clocks on different machines also disagree slightly, so even the 'later' write is not reliably later.
The Dynamo paper uses vector clocks to detect the situation. A vector clock is a list of (node, counter) pairs attached to each version of a value. When a node coordinates a write, it increments its own counter in the clock of the version it was given. Comparing two clocks tells you how the versions relate. If every counter in one clock is at least as large as the matching counter in the other, the first descends from the second and replaces it. If neither descends from the other, the versions are concurrent: they were written without knowledge of each other.
Concurrent writes in a cart
The program below uses a shopping cart. Node n1 creates a cart holding dal. Two phones read it. One adds rice through node n2, the other adds tea through node n3. Their clocks cannot be ordered. The script then merges them, and also shows what last-write-wins would have done with the same two writes.
def bump(clock, node): c = dict(clock) c[node] = c.get(node, 0) + 1 return c def descends(a, b): """True if clock a has seen everything clock b has.""" return all(a.get(n, 0) >= c for n, c in b.items()) def compare(a, b): if descends(a, b) and descends(b, a): return "same" if descends(a, b): return "a replaces b" if descends(b, a): return "b replaces a" return "concurrent: keep both" # A cart starts with one item on node n1. v1 = ({"n1": 1}, ["dal"]) # Two phones read v1 and add different items, through different servers. v2 = (bump(v1[0], "n2"), v1[1] + ["rice"]) # phone 1 via node n2 v3 = (bump(v1[0], "n3"), v1[1] + ["tea"]) # phone 2 via node n3 print("v1 vs v2:", compare(v1[0], v2[0])) print("v2 vs v3:", compare(v2[0], v3[0]), v2[0], v3[0])
vclock.py: bump, compare, and two concurrent writes
# Reconcile: union of items; merge the clocks, then bump one. merged_clock = { n: max(v2[0].get(n, 0), v3[0].get(n, 0)) for n in ("n1", "n2", "n3") } v4 = (bump(merged_clock, "n1"), sorted(set(v2[1]) | set(v3[1]))) print("v4:", v4) print("v4 vs v2:", compare(v4[0], v2[0])) print("v4 vs v3:", compare(v4[0], v3[0])) # Last-write-wins with timestamps, same two writes. t2, t3 = 1001, 1002 winner = v2 if t2 > t3 else v3 print("last-write-wins keeps:", winner[1], "(the other phone's item is lost)")
v1 vs v2: b replaces a
v2 vs v3: concurrent: keep both {'n1': 1, 'n2': 1} {'n1': 1, 'n3': 1}
v4: ({'n1': 2, 'n2': 1, 'n3': 1}, ['dal', 'rice', 'tea'])
v4 vs v2: a replaces b
v4 vs v3: a replaces b
last-write-wins keeps: ['dal', 'tea'] (the other phone's item is lost)Python 3.12.10 on this machine. Deterministic.
Version 2 replaced version 1, as it should, because its clock includes everything in the first. Versions 2 and 3 were concurrent, so the store keeps both and returns both on the next read. The client merges them, here as a union of the items, and writes the result back with a clock that descends from both. The merged version then replaces each. With last-write-wins, the write with the later timestamp survived, and a customer's tea disappeared from the cart.
Who resolves, and the limits
The store can detect a conflict and can only guess at a resolution, because the meaning of the data belongs to the application. Dynamo returns all conflicting versions to the client and lets the application merge them. For a cart, a union loses nothing except that a deleted item may reappear. For a counter, a sum is right. For a user profile, a person may have to choose. Some stores offer automatic merge types such as sets and counters that merge without conflict, called conflict-free replicated data types (CRDTs), which a later chapter returns to.
Vector clocks grow when many different nodes coordinate writes to one key. Dynamo limits the growth by recording a timestamp with each pair and dropping the oldest pair when the clock passes a threshold, which it gives as ten. The paper admits that this can make the relationship between versions harder to establish, and says it had not been a problem in production. Cassandra takes the other route and resolves conflicting writes to a cell by timestamp, which is LWW again.
The choice follows the data. If a lost update is acceptable, as with a last-seen time, use LWW and keep the system simple. If it is not, as with a cart, keep versions and merge. If every write must be ordered, a key-value store with leaderless replication is the wrong tool, and a replicated state machine with a leader is the right one.
In the run, why were versions 2 and 3 concurrent?
- Version 2's clock had n2 but no n3, version 3's had n3 but no n2. Neither had seen the other, so neither descends from the other.
What did the merged version's clock look like, and why does it replace both?
- It was n1:2, n2:1, n3:1, which has every counter at least as large as both of the earlier clocks, so it descends from both.
When is last-write-wins an acceptable policy?
- When losing one of two concurrent writes costs nothing, such as a last-seen timestamp. It is unsafe for data such as carts where every write matters.
Part 5 · Anti-entropy and membership
Repairing replicas with Merkle trees
Replicas fall out of step despite hinted handoff: a hint is lost, a node is down for days, a disk is replaced. Anti-entropy is the background process that finds the differences and copies the missing data. Comparing every key between two replicas would be slow and heavy on the network. A Merkle tree makes the comparison cheap.
A Merkle tree is a hash tree. Each leaf holds the hash of one key and its value. Each parent holds the hash of its children's hashes, up to a single root hash. If two replicas hold identical data, their roots are identical, and one comparison is enough. If the roots differ, the replicas exchange the two child hashes, descend only into the child that differs, and repeat until they reach leaves. The Dynamo paper describes this, and keeps one tree per key range, so a node compares the range it shares with another node.
import hashlib def H(b): return hashlib.sha256(b).hexdigest()[:8] def build(items, lo, hi): """Merkle tree over keys lo..hi (inclusive) as nested tuples.""" if lo == hi: k = items[lo][0] return (H(f"{k}={items[lo][1]}".encode()), lo, hi, None, None) mid = (lo + hi) // 2 l, r = build(items, lo, mid), build(items, mid + 1, hi) return (H((l[0] + r[0]).encode()), lo, hi, l, r) def diff(a, b, items, out, seen): seen[0] += 1 # one hash comparison if a[0] == b[0]: return if a[3] is None: out.append(items[a[1]][0]) return diff(a[3], b[3], items, out, seen) diff(a[4], b[4], items, out, seen)
merkle.py: build a tree and walk the differences
keys = [f"k{i:03}" for i in range(256)] r1 = [(k, "v1") for k in keys] r2 = list(r1) # one replica missed one write r2[137] = (keys[137], "STALE") t1, t2 = build(r1, 0, 255), build(r2, 0, 255) out, seen = [], [0] diff(t1, t2, r1, out, seen) print("root hashes:", t1[0], t2[0]) print("hash comparisons:", seen[0], "of", 2 * 256 - 1, "tree nodes") print("keys to repair:", out)
root hashes: 1c5985e6 164267ee hash comparisons: 17 of 511 tree nodes keys to repair: ['k137']
Python 3.12.10 on this machine. Deterministic.
The two replicas each hold 256 keys, and one replica has a stale value for the key k137. Their root hashes differ. The walk made 17 hash comparisons in a tree of 511 nodes: 9 nodes on the path from the root to the stale leaf differed, and at each of the 8 levels below the root one matching sibling was compared and skipped with everything under it. It found exactly the one key to repair. The cost is that when keys change, hashes up the tree must be recomputed, and when a node joins or leaves, key ranges change and trees must be rebuilt, which the paper notes as a disadvantage. Dynamo also repairs on the read path: after answering, the coordinator sends the newest version to any replica that returned a stale one, which the paper calls read repair.
Gossip for membership
Every node must know which nodes are in the cluster and which are alive, and there is no central server to ask. Dynamo, like Cassandra, uses gossip: at regular intervals each node picks another node at random and exchanges what it knows about the cluster. The Dynamo paper says each node contacts a random peer every second, and Cassandra's documentation describes a round every second in which each node exchanges state with one random node. News of a join or a leave then spreads like a rumour.
The simulation below starts with one node knowing something and lets every informed node tell one random node per round, which is the simplest push form of gossip. It repeats this for clusters of 10, 100 and 1,000 nodes, 20 times each, and counts rounds until everyone knows.
import random def rounds_to_spread(n, seed): rnd = random.Random(seed) knows = {0} # node 0 learns that node 7 left rounds = 0 while len(knows) < n: rounds += 1 for node in list(knows): knows.add(rnd.choice([x for x in range(n) if x != node])) return rounds for n in (10, 100, 1000): r = [rounds_to_spread(n, s) for s in range(20)] print(f"{n:5} nodes: rounds to reach everyone, min {min(r)} " f"max {max(r)} average {sum(r)/len(r):.1f}")
gossip.py: rounds until every node has heard
10 nodes: rounds to reach everyone, min 4 max 8 average 6.1 100 nodes: rounds to reach everyone, min 11 max 14 average 12.7 1000 nodes: rounds to reach everyone, min 17 max 22 average 18.2
Python 3.12.10 on this machine. Deterministic: seeded.
A hundred times more nodes needed about three times more rounds: 6.1 on average for 10 nodes, 12.7 for 100, and 18.2 for 1,000. Spread time grows roughly with the logarithm of the cluster size, which is why gossip scales. Each node sends one message per round whatever the cluster size, so there is no central bottleneck.
Failure detection is a separate question. As the core concepts chapter explained, a timeout cannot distinguish a dead node from a slow one, so a detector must accept some false suspicions. Both designs keep that judgement local. The Dynamo paper says a node treats a peer as failed when the peer stops answering its own messages, routes around it and retries it later, and that an early design which kept a global view of failures was dropped once explicit join and leave commands existed. Cassandra's documentation says every node runs a variant of the Phi Accrual Failure Detector, decides on its own from the heartbeat state it receives, and does not gossip its up or down view.
Part 6 · The storage engine
Why a log-structured design
Each node needs a local engine that stores its share of the keys. The workload is write-heavy and key-based, and disks do sequential writes far faster than random ones. A log-structured merge-tree (LSM-tree) turns all writes into sequential appends. The Bigtable paper describes a commit log, a memtable and SSTables, and Cassandra, whose documentation describes it as Dynamo's distribution and replication combined with Bigtable's data and storage model, uses a variant of it.
A write goes through two steps. First it is appended to the commit log, a file on disk that is only ever added to. If the node crashes, the log is replayed to recover. Second the write is placed in the memtable, a sorted structure in memory. When the memtable reaches a size limit it is written out as a sorted string table (SSTable): an immutable file of key-value pairs sorted by key. After the flush, the matching part of the commit log can be discarded.
A read checks the memtable first, since it has the newest data, and then the SSTables from newest to oldest, returning the first version found. Because files are immutable, a delete cannot remove anything. It writes a tombstone, a marker that hides older versions.
A small engine
The program below is a tiny LSM store, small enough to read in full. It flushes when the memtable reaches three keys, supports deletes through tombstones, and has a compact method that merges the tables.
import json, os, tempfile TOMB = "__deleted__" class LSM: def __init__(self, folder, limit=3): self.folder, self.limit = folder, limit self.mem, self.tables = {}, [] # newest table last self.log = open(os.path.join(folder, "commit.log"), "a") def put(self, key, value): # 1. append to the log self.log.write(json.dumps([key, value]) + "\n") self.log.flush() # 2. update memtable self.mem[key] = value if len(self.mem) >= self.limit: self.flush() def delete(self, key): self.put(key, TOMB)
lsm.py: commit log and memtable
def flush(self): # sorted, then immutable table = dict(sorted(self.mem.items())) name = os.path.join(self.folder, f"sst{len(self.tables)}.json") with open(name, "w") as f: json.dump(table, f) self.tables.append(table) self.mem = {} # log no longer needed open(self.log.name, "w").close()
lsm.py: flushing to a sorted table
def get(self, key): for where, t in [("memtable", self.mem)] + [ (f"sstable {i}", t) for i, t in reversed(list(enumerate(self.tables))) ]: if key in t: v = t[key] return (where, None if v == TOMB else v) return ("nowhere", None) def compact(self): merged = {} # oldest first, newer wins for t in self.tables: merged.update(t) self.tables = [{k: v for k, v in merged.items() if v != TOMB}] db = LSM(tempfile.mkdtemp()) for k, v in [("a", 1), ("b", 2), ("c", 3), ("a", 10), ("d", 4)]: db.put(k, v) db.delete("b") db.put("e", 5) print("tables:", len(db.tables), "| memtable:", db.mem) for k in ["a", "b", "c", "e", "z"]: print("get", k, "->", db.get(k)) db.compact() print("after compaction:", db.tables)
lsm.py: reads, compaction, and a short run
tables: 2 | memtable: {'e': 5} get a -> ('sstable 1', 10) get b -> ('sstable 1', None) get c -> ('sstable 0', 3) get e -> ('memtable', 5) get z -> ('nowhere', None) after compaction: [{'a': 10, 'c': 3, 'd': 4}]
Python 3.12.10 on this machine. Deterministic.
Five writes and a delete led to two flushes: the first three keys became table 0, and the next three, including the update of a and the tombstone for b, became table 1. Key e was still in the memtable. A read for a returned 10 from the newer table, and not the 1 in the older one. A read for b found the tombstone first and reported it as missing. A read for c had to go to the older table, and z was found nowhere.
Compaction and the costs
Left alone, tables pile up and every read must check more of them. Compaction merges SSTables in the background: it reads several sorted files, keeps the newest version of each key, drops the entries that tombstones hide, and writes one new file. After compaction in the run, a single table held a, c and d, with b gone and a at 10. The toy merged every table, so it could drop the tombstone too. The Bigtable paper makes the same distinction: only a major compaction, which rewrites all SSTables into one, produces a file with no deletion entries.
The trade-off has a name. LSM engines have high write throughput and pay for it in read amplification, since a read may touch several files, and write amplification, since compaction rewrites data several times. In a replicated store, tombstones must also outlive outages. If a tombstone is purged before a replica that missed the delete has been repaired, anti-entropy copies the old value back. Cassandra keeps tombstones for gc_grace_seconds, ten days by default, for this reason. Two techniques reduce read cost. A Bloom filter per file answers 'this key is definitely not here' without a disk read, and a sparse index per file narrows the search to one block.
The whole store
The pieces of the chapter now fit together. A client sends a request to any node, which hashes the key onto the ring and finds the preference list. The coordinator writes to W replicas or their stand-ins. Each replica appends to its commit log and updates its memtable. Anti-entropy and gossip keep the replicas and the membership honest. Each part is simple, and the design is the way they combine.
| Term | Meaning |
|---|---|
| Preference list | The ordered nodes responsible for a key |
| Sloppy quorum | Using the first N healthy nodes instead of the exact home nodes |
| Hinted handoff | A stand-in keeps a write and passes it to the owner on recovery |
| Vector clock | Per-node counters that show whether versions are ordered or concurrent |
| Merkle tree | A hash tree used to find differing key ranges |
| Memtable and SSTable | An in-memory sorted table and an immutable sorted file on disk |
| Tombstone | A marker written instead of removing data |
Why does the engine append to a commit log before updating the memtable?
- The memtable is in memory and vanishes in a crash. The log is on disk, so replaying it rebuilds the memtable.
In the run, a read for a returned 10. Why not 1?
- Both versions exist, but reads check newer tables first. The write of 10 is in table 1, which is newer than table 0.
What is a tombstone, and when does it actually disappear?
All chapters · Previous: Databases: Choosing, Replicating and Partitioning