Split 20,000 users over four nodes. Ranges of user ID send every new user to one node. A hash ring with virtual nodes spreads them, and when a fifth node joins it moves about 20% of the keys, where hash mod N moves 80%.
Pick a scheme and watch where new users land. Then add or remove a node and count the keys that move. Then we build, piece by piece, ranges, hashing, the ring, rebalancing, hot keys, secondary indexes, the storage engine inside each node, and erasure-coded blobs.
You need what a hash function is and what a key-value store is. Caching & CDNs helps. We build the rest from zero.
Simulated live in your browser on 20,000 stored user IDs and the next 400 new IDs, with a 32-bit hash. Blue bars are each node's share of new writes; purple bars its share of stored keys. Chapters 1 to 4 work each number.
Chapter 0
Count how many machines your writes and your data need
Your database stores 500 million user profiles of 2 KB each. That is 500,000,000 × 2,000 bytes = 1012 bytes, or 1 TB. This lesson uses decimal units: 1 GB = 109 bytes. Your server has 256 GB of memory, so most reads go to disk.
The writes hurt too. The app needs 40,000 writes a second, and one server handles about 10,000. Replication (keeping full copies on several nodes) adds read capacity, but every copy must apply every write. It does not add write capacity.
The fix is to split the data. Each node holds a subset of the keys and takes the writes for that subset. This is partitioning, also called sharding; each subset is a partition. A rule, the partition key, decides which partition owns each record.
How many partitions? Call the write rate the app needs W and the rate one node can take w. Call the total data D and the data one node should hold d. You need enough partitions for whichever limit is tighter.
P equals the ceiling of the larger of W over w, and D over d.
Divide the needed write rate W by one node's rate w. Divide the data D by one node's share d. Take the larger result and round it up. That is P.
W / w = 40,000 / 10,000 = 4. D / d = 1,000 / 256 = 3.9. The larger is 4, so P = 4 partitions. Writes set the count here, by a small margin.
Each box is one node. The blue bar is its share of the writes against 10,000 a second; the purple bar is its data against 256 GB. Drag the two loads.
Illustrative capacities: 10,000 writes a second and 256 GB of memory per node, an even split, and no headroom. Real clusters keep spare capacity.
This count assumes an even split. The rest of the lesson is about keeping it even: when keys arrive in order, when nodes join, and when one key gets most of the traffic.
Failure. Symptom: you add read replicas and write latency does not move. Measure: writes per second on the primary against its limit. Cause: every replica applies every write, so replicas add read capacity only. Fix: partition the writes by key.
Chapter 1
Give each node a slice of the key order, and watch ordered keys pile onto one slice
The simplest rule: sort the keys and cut the order into slices. Take user IDs from 0 to 99,999 and four partitions. Partition 0 owns 0 to 24,999, partition 1 owns 25,000 to 49,999, and so on. This is range partitioning. A router keeps the list of boundaries and sends each key to its slice.
Ranges make scans cheap. A query for IDs 24,000 to 26,000 touches two partitions, not four. Bigtable (Chang and others, 2006) and HBase store rows in key order and split them into ranges they call tablets or regions. Bigtable splits a tablet when it grows past about 100 to 200 MB.
Ranges have one weakness. If keys arrive in order, every new key lands in the last slice. Auto-increment IDs and timestamps do this. One node takes all the writes while three sit idle. That node is a hot spot.
We measure it with skew. Call the load on the busiest partition Lmax and the mean load over all partitions L̄.
Skew equals L-max divided by L-bar.
Find the busiest partition's load L-max. Divide the total load by the partition count to get L-bar. Divide the first by the second. The cluster runs out of capacity when its busiest node does, so skew tells you how much of the cluster you can use.
100 new users with IDs 100,000 to 100,099 go to four range partitions. All 100 land on partition 3: L-max = 100, L-bar = 100 / 4 = 25, skew = 4.0. The cluster writes as fast as one node.
Each column is one range partition. Blue dots are writes on their way; the purple bar counts the writes each partition took. Pick a key pattern and write 100 rows.
Simulated in your browser. Boundaries at 25,000, 50,000 and 75,000; the last partition owns every ID above 75,000. Random IDs are uniform over 0 to 99,999.
The prefix fix puts a small number in front of the key: (ID mod 4, ID). Writes now spread over four slices. The price: a scan over an ID range must now ask all four slices and merge the results.
Failure. Symptom: one region server runs at 100% CPU while the rest idle. Measure: writes per second per partition. Cause: the row key starts with a timestamp, so all new rows share the last range. Fix: lead the key with something that spreads, such as a sensor ID or a small hash prefix, and keep the timestamp second.
Chapter 2
Scramble the keys so ordered input spreads evenly, then see what mod N does when a node joins
A good hash function turns a key into a number that looks random. IDs 100,000 and 100,001 get unrelated hashes. If you partition by the hash, ordered keys spread evenly. This is hash partitioning. Cassandra hashes the partition key with Murmur3; DynamoDB hashes its partition key too.
The price is range scans. Neighbouring keys now live on different nodes, so "IDs 24,000 to 26,000" must ask every partition. Cassandra keeps one middle path: a compound key. It hashes only the first part and keeps the rest sorted inside the partition.
The obvious way to pick a node is the remainder: partition = hash(key) mod N, for N nodes. It spreads well. It fails when N changes.
Why? A key stays put only if its hash gives the same remainder for N and for N + 1. Take hashes from 0 to N(N + 1) − 1: only the N smallest give the same remainder both times. So 1 in N + 1 keys stay, and the rest move.
Call the node count before the change N.
Moved-mod equals N divided by N plus one.
Count the nodes N before the change. One key in N + 1 keeps its node. All the others move, so the moved share is N over N + 1.
N = 4: 4 / 5 = 80% of keys move to add one node. N = 8: 8 / 9 = 88.9%. On 1 TB, adding a fifth node copies 800 GB, when the new node needs only 200 GB.
Each column is a node and each purple dot a key in it. Press the button: blue dots are keys that move to another node. Then change N and try again.
Simulated: the dots are 120 sample keys; the read-out counts 20,000 keys with the same 32-bit hash.
Failure. Symptom: you add one cache or database node and the backend falls over. Measure: keys moved, or cache misses, in the minutes after the change. Cause: hash mod N reassigned about N / (N + 1) of all keys at once. Fix: a hash ring (Chapter 3) or fixed partitions (Chapter 4).
Chapter 3
Move only the keys the new node needs, then even out the arcs with many points per node
Consistent hashing (Karger and others, 1997) bends the hash range into a circle. Each node hashes its name to a point on the circle. Each key hashes to a point too, and belongs to the first node point clockwise from it.
When a node joins, it takes only the keys between its point and the point before it. With N nodes owning equal arcs on average, the new node takes its fair share of N + 1.
Moved-ring equals one divided by N plus one.
The new node takes one fair share, 1 over N + 1 of the keys. No key moves between old nodes. It is an average: one node's arc can be larger or smaller.
10 nodes and 10,000 keys, add an eleventh: 10,000 / 11 = 909 keys move. Mod N would move 10,000 × 10 / 11 = 9,091.
One point per node gives lumpy arcs. Dynamo (DeCandia and others, 2007) fixed this with virtual nodes: each node takes V points, so its share is the sum of V small arcs. Call its share's spread σ and the fair share μ.
Sigma over mu is about one over the square root of V.
Each node's share is a sum of V random arcs. Adding V random pieces shrinks the relative spread by the square root of V. So to halve the spread, use four times as many virtual nodes.
V = 1: σ / μ ≈ 1. V = 16: 1 / 4 = 0.25. V = 256: 1 / 16 = 0.0625. The exact value for 10 nodes, √((N − 1) / (NV + 1)), gives 0.90, 0.24 and 0.059, and 4,000 random rings in our check script agree.
Orange ticks are node points; purple dots are keys. The bars show each node's share of the ring against the fair line. Raise the virtual nodes, then add a node: blue keys moved.
Simulated: node points from a 32-bit hash of the node and point number; 20,000 keys counted, 160 drawn. One fixed set of hashes, so the lumps you see are one real draw, not an average.
Virtual nodes buy a second thing. A joining node takes many small arcs from many nodes, so the copy load spreads. The cost is metadata: V points per node in every router. Cassandra's default num_tokens is now 16 per node, with a token allocator that places them for balance.
Failure. Symptom: one node in a 4-node ring fills its disk first. Measure: each node's share of the token ring. Cause: one point per node, so arcs differ by twice or more. Fix: more virtual nodes, or a token allocator that places points on purpose.
Chapter 4
Cut the data into many more partitions than nodes, then move partitions instead of keys
Rebalancing moves data so each node holds a fair share again, while the cluster serves traffic. DDIA (Kleppmann, chapter 6) lists three ways to do it.
Each column is a node; each purple tile one partition. Add a node: the blue tiles are partitions that moved. Try 12 partitions, then 1,024.
Simulated: the new node takes partitions one at a time from the node with the most. The time assumes 10 TB in the cluster, equal partitions, and copies throttled to 100 MB/s in total (illustrative).
The worked number. 1,024 partitions on 4 nodes, 256 each. A fifth node wants 1,024 / 5 = 204.8, so it takes 51 from each node: 204 partitions, 19.9% of the data. The old nodes keep 205 each.
That data has to travel. Call the cluster's data D, the node count after the join N + 1, and the copy rate the operator allows B:
The throttle protects live traffic, so a rebalance takes hours.
Too few partitions leave lumps. With 12 partitions on 5 nodes, two nodes hold 3 and three hold 2: skew = 3 / 2.4 = 1.25. With a 13th node, one node holds nothing. Choose P well above the largest cluster you expect, but each partition costs routing metadata.
Failure. Symptom: latency rises for hours after you add a node. Measure: copy bandwidth against client traffic on the donor nodes. Cause: rebalancing reads and sends a fifth of the data at full speed. Fix: throttle the copy, and add capacity before you need it.
Chapter 5
Salt a hot key into k keys, and pay for it with k reads
Hashing spreads many keys. It cannot spread one. Every write to the same key hashes to the same partition. A celebrity's post, a viral product, a global counter: one key can carry more writes than one partition can take.
The limits are real. A DynamoDB partition serves at most 1,000 write units a second (one unit is one write of up to 1 KB). A key that gets 5,000 writes a second is five times over, and more partitions do not change that.
The fix is salting (AWS calls it write sharding): append a suffix from 0 to k − 1 to the hot key, chosen at random on each write. The k new keys hash to different partitions. Call the hot key's write rate Rhot and the number of suffixes k.
L-part equals R-hot divided by k.
Split the hot key's write rate R-hot evenly over k salted keys. If each lands on its own partition, each takes R-hot over k. Two suffixes that hash to the same partition put double on it.
R-hot = 5,000 writes a second, k = 10: L-part = 500 per partition, under the 1,000 limit. But each read of that key must now fetch all 10 salted keys and merge them.
Each bar is one of 32 partitions. Purple is the steady load from other keys; blue is the hot key's share. Red marks load over the dashed limit. Raise the hot rate, then add salts.
Illustrative: 32 partitions, 300 writes a second each from other keys, a 1,000 writes a second limit as on a DynamoDB partition. A real hash places the salted keys, so two salts can share a partition.
Salts hash like any key, so two can share a partition. Here 8 salts land on 8 partitions and all fit; at 10 salts two share one, and it goes over. Leave margin in k.
Salt only the keys that need it. Every reader must know which keys carry salts, and a read costs k requests. DDIA notes that systems rarely do this for you; the app must track which keys are hot.
Failure. Symptom: throttling errors on one key while the table is far below its total capacity. Measure: per-key traffic, from a sampled access log or a hot-key metric. Cause: one key's rate exceeds one partition's limit. Fix: salt that key, or cache its reads in front of the store.
Chapter 6
Ask every partition with a local index, or one partition with a global index
You partition users by user ID. Now you want every user in London. City is a secondary index: a lookup by a field that is not the partition key. There are two ways to partition it.
A local index lives in each partition and covers only that partition's rows. A write updates one partition. A query by city must ask every partition and merge the answers. This is scatter/gather. DDIA lists MongoDB, Cassandra, Elasticsearch and Riak as users.
A global index takes its partitions from the indexed value. All "London" entries live in one index partition. A query asks that one partition. A write may now touch two partitions: the row's and the index entry's. DynamoDB updates its global secondary indexes asynchronously, so a read of the index can miss a write made a moment ago.
Scatter/gather has a hidden cost. The query waits for its slowest partition. Call the chance that one partition replies slowly p and the number of partitions asked n.
P-slow equals one minus, one minus p, to the n.
The query is fast only if all n partitions are fast. Multiply the chance of fast, 1 − p, n times. Subtract from 1 to get the chance that something was slow.
p = 0.01, n = 100: 0.99100 = 0.366, so P-slow = 63%. A partition that is slow 1 time in 100 makes most scatter/gather queries slow. With a global index, n = 1 and P-slow = 1%.
The coordinator sends blue queries to partitions; teal replies come back, pink ones late. Pick the index type and the partition count, then run 1,000 queries.
Illustrative: each partition replies in 10 ms, or in 200 ms with chance 1%, independently. We assume the global index holds the fields the query needs, so it asks one partition.
Failure. Symptom: the 99th percentile of search latency grows each time you add partitions. Measure: latency by number of partitions asked. Cause: scatter/gather waits for the slowest of n. Fix: a global index for hot lookups, or hedged requests to replicas of slow partitions.
Chapter 7
Follow a write into an LSM tree and count every byte it costs the disk
Each partition is a small database. Its storage engine decides how bytes reach the disk.
A B-tree keeps keys sorted in fixed pages, often 4 KB, and updates a page in place. With 500 keys per page, four levels reach 5004 × 4 KB = 256 TB, so a lookup reads about four pages. Postgres and MySQL's InnoDB use B-trees.
An LSM tree (O'Neil and others, 1996) never updates in place. A write goes to a log on disk (the WAL, for crash recovery) and to a sorted table in memory, the memtable. When the memtable fills, the engine writes it out as an immutable sorted file, an SSTable. Background compaction merges files into larger levels, each about 10 times the last. Bigtable, Cassandra and RocksDB use LSM trees.
Both write more bytes than the app sends. Call the bytes the disk writes Bdisk and the bytes the app writes Bapp.
W-A equals B-disk divided by B-app.
Add up every byte the engine writes to disk for a workload, B-disk. Divide by the bytes the app wrote, B-app. Disk bandwidth and SSD wear scale with WA.
B-tree: a random 100-byte update rewrites a 4,096-byte page and logs 100 bytes, so WA = 4,196 / 100 = 42 if each update flushes its own page. LSM: the device below measures 13.6 after 1,000 MB of new keys.
Writes fill the memtable, flush to level 0 files, and compactions merge them down. Each purple bar is a level against its target size. Write 100 MB at a time, or 1,000 at once.
Simulated in MB: a 4 MB memtable, compaction after 4 level-0 files, level 1 at 16 MB, each level 10 times the last (RocksDB's default ratio), new unique keys only. Moving one file down rewrites the overlapping part of the next level. A toy, scaled down from real sizes.
Read the trade. An LSM write is sequential and batched, so it suits write-heavy partitions. A lookup may check the memtable, every level-0 file and one file per level. A Bloom filter per file answers "surely not here" for most of them: at 10 bits per key it lets through about 1% of misses (RocksDB wiki). With levels 10 times apart, about 90% of the data sits in the last level, which bounds the space old versions waste.
Failure. Symptom: write latency spikes, and the engine reports a write stall. Measure: pending compaction bytes and level-0 file count. Cause: compaction falls behind the write rate, so level 0 fills up. Fix: more compaction threads, faster disks, or fewer writes per partition.
Chapter 8
Pack objects into large files, then trade three copies for erasure codes
Photos, videos and backups are blobs: opaque byte strings from kilobytes to terabytes. A blob store partitions by object name, like any key-value store, but it stores the bytes differently.
Windows Azure Storage (Calder and others, 2011) has three layers. A stateless front end checks the request and finds the partition. The partition layer maps each name to a place: (extent, offset, length). The stream layer stores extents, append-only files of about 1 GB, each written to three nodes. A delete marks the bytes dead; a background job reclaims them later.
Three copies cost 3 bytes of disk per byte of data. A sealed extent can be erasure coded instead: cut into k data fragments, add m parity fragments, and store all n = k + m on different nodes. Any k of them rebuild the data. Call the total fragments n and the data fragments k.
Overhead equals n divided by k.
Count all the fragments you store, n. Divide by the data fragments k. The difference n − k is how many nodes can fail before data is lost.
Three copies: n = 3, k = 1, overhead 3, survives 2 losses. HDFS's default RS-6-3: n = 9, k = 6, overhead 1.5, survives 3. For 1 PB of data, that is 1.5 PB of disk instead of 3 PB.
Each box is a node holding one purple fragment. Tap a box to fail it, or use the button. The data stays readable while k fragments survive.
Illustrative 1 GB extent. RS-6-3 is HDFS's default erasure coding policy; Facebook's f4 warm blob store used RS-10-4. Repair reads assume plain Reed-Solomon.
Erasure codes save disk and cost repair work. To rebuild one lost fragment, a node reads k others: 6 for RS-6-3, against one copy for replication. So hot, young data stays replicated, and sealed, cooler extents get coded.
Failure. Symptom: network traffic between racks jumps after a disk dies. Measure: repair bytes read per byte rebuilt. Cause: each lost fragment needs k fragments read from other nodes. Fix: spread repairs over time, and keep hot data replicated.
Chapter 9
Choose a scheme and a workload, grow the cluster, and read the skew and the moved keys
The hero's cluster, with every knob from Chapters 1 to 5. Pick a scheme and a workload. Add or remove nodes. Each node shows its share of stored keys and of the next 2,000 writes, and the line under the chart reports what the last change moved.
Purple bars: share of the 20,000 stored keys. Blue bars: share of the next 2,000 writes; red where a node takes over 1.5 times its fair share. Change anything, then add a node.
Simulated in your browser with the same engine as the hero: 20,000 stored IDs, a 32-bit hash, 2 to 10 nodes. Range adds a node by splitting the fullest range at its median, the last one on a tie.
Things to try:
The worked number: ring with 64 virtual nodes, 4 nodes, then a fifth. The simulation moves 19.7% of 20,000 keys, all to the new node; the formula 1 / (N + 1) predicts 20%. The same step under mod N moves 79.9%, against a predicted 80%.
Failure. Symptom: after a capacity add, one node is still the bottleneck. Measure: write skew per node before and after. Cause: the load was a hot key or ordered keys, which more nodes do not split. Fix: change the key (prefix or salt), not the node count.
Chapter 10
Keep the numbers, the choices and the code for the next dataset you split
Partition when writes or data outgrow one node. Ranges keep scans cheap and turn ordered keys into a hot spot. Hashing spreads keys, and a ring or fixed partitions keep a join from moving most of them. Virtual nodes and many partitions even out the shares.
No scheme splits one hot key, so salt it. Secondary indexes cost reads when local and writes when global. Inside each partition, the engine trades write amplification for read cost, and blob stores trade disk for repair work.
| Term | What it is | This lesson's number |
|---|---|---|
| Partitions needed | P = ⌈max(W / w, D / d)⌉ | 40,000 writes/s, 1,000 GB: 4 |
| Skew | Lmax / L̄ | ordered IDs on 4 ranges: 4.0 |
| Mod N join | moved = N / (N + 1) | 4 to 5 nodes: 80% |
| Ring join | moved = 1 / (N + 1) | 10 to 11 nodes: 909 of 10,000 |
| Virtual nodes | σ / μ ≈ 1 / √V | V = 256: about 6% |
| Rebalance time | t = D / (N + 1) / B | 10 TB, 5 nodes, 100 MB/s: 5.6 h |
| Salting | Lpart = Rhot / k | 5,000 / 10 = 500 writes/s |
| Scatter/gather | Pslow = 1 − (1 − p)n | p 1%, n 100: 63% |
| Write amplification | WA = Bdisk / Bapp | B-tree 42; LSM toy 13.6 |
| Erasure coding | overhead = n / k | RS-6-3: 1.5, survives 3 |
| Workload | Scheme | Examples |
|---|---|---|
| Point lookups by key | hash: ring, or fixed partitions | Dynamo, Cassandra, DynamoDB, Redis Cluster |
| Range scans, time series | range, with split on size or load | Bigtable, HBase, Spanner |
| Search over many fields | hash plus local indexes, scatter/gather | Elasticsearch |
| Large objects | hash on name, extents, erasure coding | Azure Storage, HDFS, f4 |
num_tokens is 16, not the older 256.python# a hash ring with virtual nodes, and the keys a join moves (sketch) import bisect, hashlib def h(s): # a 32-bit position on the ring return int.from_bytes(hashlib.md5(s.encode()).digest()[:4], "big") class Ring: def __init__(self, nodes, v=64): self.v, self.pts = v, [] # sorted (position, node) for n in nodes: self.add(n) def add(self, node): # V points per node: sigma/mu ~ 1/sqrt(V) for i in range(self.v): bisect.insort(self.pts, (h(f"{node}#{i}"), node)) def owner(self, key): # first node point clockwise i = bisect.bisect_left(self.pts, (h(key), "")) return self.pts[i % len(self.pts)][1] keys = [f"user{i}" for i in range(20000)] r = Ring(["A", "B", "C", "D"]) before = {k: r.owner(k) for k in keys} r.add("E") moved = sum(before[k] != r.owner(k) for k in keys) print(moved / len(keys)) # about 1/5; every moved key now lives on E modn = sum(h(k) % 4 != h(k) % 5 for k in keys) print(modn / len(keys)) # about 4/5 under hash mod N
Now press Present or Teach and explain five things from memory. Explain why ordered keys make a hot spot under ranges. Explain why mod N moves 4 keys in 5 and a ring moves 1 in 5. Explain why virtual nodes even out the shares by the square root of V. Explain why a local index makes most queries slow at 100 partitions. Then go back to the hero, switch to Range, and add a node.