Key takeaways
- ✓With consistent hashing, adding a fifth shard moved only the users on the new shard's stretches of the ring: 35,775 of 200,000 (17.9%), all of them to the new shard. Picking the shard by the remainder of the hash would have moved about 160,000, four in five, most of them between the old shards.
- ✓Switching the router to the new ring and then copying the rows failed 1,044 of 30,195 reads and 202 of 5,920 writes during a 12.8 s copy: a moved user's request went to the new shard before their row did. A steady copy predicts about 1,140 reads and 230 writes, close to what was measured.
- ✓A dual ring, the new ring with the old one as a fallback until the copy is done, failed nothing under the same load: 1,037 reads were served by the old shard, and 198 writes moved their row to the new shard before updating it.
- ✓After each run every user's balance was compared with the starting balance plus every update the client was told succeeded. Both ways: 0 wrong, 0 missing, 0 on two shards. The 202 refused writes in the first way were refused, not lost.
- ✓Moving a row while a copy job runs has a race: the job may already have put the row on the new shard. The lab's first version added the two balances, which would double the user's money; the fix is to do nothing when the row is already there, safe because writes never go to the old shard during the move.
- ✓A Snowflake ID packs the time in milliseconds, a machine number and a per-millisecond counter into 64 bits, so every machine makes unique IDs on its own, as long as machine numbers are unique and its clock never goes back. A clock stepping back nine times made 180, 900 and 9,000 duplicates for steps of 1, 5 and 50 ms; remembering the last millisecond and waiting made none, for 1, 37 and 442 ms of waiting in all.
- ✓Snowflake IDs sort only roughly by time: even with perfect clocks, 14.5% of neighbouring IDs were in the wrong real order, because inside one millisecond the machine number decides. With clocks up to 100 ms apart, an ID could be newer than its neighbour for an event 67.6 ms earlier.
A service keeps its users in four databases. A fifth one is added while the service keeps running. For about thirteen seconds, users go missing: 1,044 reads and 202 writes fail. Nobody's balance comes out wrong, and no row is lost; each one was on its old database or the new one, just not where the service looked. A second way to do the same move fails nothing. This chapter measures both, checks every balance, and then turns to a related problem: making unique IDs on each machine, without one shared counter, and what a clock that steps backwards does to them.
The examples come from Lab 10 (Partitioning and Sharding) of the system design labs, scripts 03_resharding.py (adding a fifth shard under load, two ways, then a check of every balance) and 04_ids.py (Snowflake IDs on a clock the test controls), with the lab's modules partitioner.py (which shard a key lives on), service/app.py (the router in front of the shards) and snowflake.py (the ID generators). Chapter 18 covers the same lab's first half: partitioning schemes, hot keys and queries over every shard (scripts 01_partitioning.py and 02_shards.py). 00_setup.py only loads the users. The setup is the earlier chapters' laptop (an Apple M4 Max, Docker Desktop with 16 virtual CPUs): five Postgres 18.6 databases with one CPU each, and a Python web service (FastAPI) as the router, all in Docker. The ID part runs in plain Python, with no databases. The lab's 381 unit tests (the partitioners, the ID generators, the load generator and percentile code) run in about 1.5 seconds without Docker; they all pass. Other work kept the laptop busy (a load average, the number of processes wanting a core, of about 5 to 12), so read the shapes, not the last digit.
Filing cabinets
One database holding everything eventually gets too big or too busy. Sharding (or partitioning) splits the data across several databases, each holding a part: a shard. Here the data is 200,000 users, one row each with a balance, on four Postgres shards called s1 to s4. A fifth, s5, starts empty.
In front sits a router: a small service that takes each request ("read user 42", "add 1 to user 42's balance") and sends it to the shard that holds that user. The user's ID is the partition key: the value that decides the shard.
Think of filing cabinets. Each shard is a cabinet, each user's row is a file, and the router is the clerk at the door who knows which cabinet holds which file. The clerk's rule is a ring. Hash each user's ID to a number, and picture all possible numbers laid round a circle. Each cabinet puts marks on the ring, and owns the stretch up to each of its marks: a file belongs to the first mark clockwise from its hash. That's consistent hashing. Each cabinet here has 64 marks spread round the ring (virtual nodes), so the stretches even out: the four cabinets hold 49,110, 56,513, 45,383 and 48,994 users. Chapter 18 measures what virtual nodes do.
What has to move
When s5 arrives, its 64 marks land round the ring and take over the stretches just before them. Only files on those stretches move, and every one goes to s5. The lab's ring moved 35,775 users, 17.9%, taken from every old cabinet, but unevenly: 17,078 from s2 and 3,631 from s1.
The simpler rule picks the shard by the remainder: hash the ID, divide by the number of shards, and the remainder is the shard (hash % N, called modulo). Going from 4 to 5 changes the answer for almost every key: a key stays only if its hash has the same remainder divided by 4 as by 5, which is true for 4 values in 20. On the same 200,000 users, the lab's modulo rule would move 159,822 (79.9%), 4.47 times as many, and 119,785 of them would only shuffle between the old four.
Users in each cabinet
The fifth cabinet's 64 marks land all round the ring (the bright arcs: 48 stretches after merging neighbours). Only files on those stretches move, and every one goes to s5: 35,775 users, 17.9%. It takes some from every old cabinet, unevenly: 17,078 from s2 but 3,631 from s1.
Shards are drawn as filing cabinets: a shard is one Postgres database, a file is one user's row. The ring is the lab's real one (BLAKE2b hash, 64 marks per shard); the counts come from running the lab's partitioner.py over users 1–200,000, as 03_resharding.py does. The remainder view is the same users under the lab's modulo partitioner (hash % number of shards); the lab never ran a move that way.
The ring decides how much moves. The next question is how to move it while people use it.
The test
03_resharding.py sends 1,000 reads and 200 writes a second for 30 s, spread evenly over all 200,000 users. A write adds 1 to a user's balance. Five seconds in, the router gets the new five-shard ring, and a copy job starts moving the 35,775 rows: it reads a batch of 2,000 from an old shard, inserts them on s5, deletes them from the old shard, and pauses 0.3 s, as a gentle job on a live system would. The copy took about 13 s (12.8 s in one run, 12.7 s in the other).
Both ways replay exactly the same requests: the load generator picks users from a fixed random seed.
Switch, then copy
The first way is the obvious one: tell the router to use the new ring at once, then copy. A moved user's request now goes to s5, which doesn't have their row until the copy job reaches it. The router answers 404, the HTTP status for "not found", with "no such user here".
| Way | Users moved | Copy took | Reads failed | Writes failed |
|---|---|---|---|---|
| switch, then copy | 35,775 (17.9%) | 12.8 s | 1,044 of 30,195 | 202 of 5,920 |
Every failure was such a 404 (the router counted 1,246: 1,044 + 202).
The number is predictable. At the switch, 17.9% of all users weren't on s5 yet; when the copy finished, none. If the copy runs at a steady pace, that's about half, 8.9%, on average. 1,000 reads a second for 12.8 s is about 12,760 reads, and 8.9% of them is about 1,140. The writes: 200 a second gives about 230. Measured: 1,044 and 202. (With rounder numbers, 9% of 12,800, it's about 1,150, the figure the lab's README uses.) The real copy goes shard by shard in batches, not perfectly evenly, so the model is a little off; it's the right size.
A dual ring
The second way keeps the old ring as a fallback until the copy is done: a dual ring. The router's rules, from service/app.py:
- A read goes to the user's shard on the new ring. If the row isn't there yet, it reads the user's shard on the old ring.
- A write updates the row on the new shard. If the row isn't there yet, the router first moves it: deletes it from the old shard and inserts it on the new one. Then it updates it. So writes only ever go to the new shard.
When the copy is done, the old ring is dropped.
| Way | Reads failed | Writes failed | Reads served by the old shard | Rows moved by a write |
|---|---|---|---|---|
| switch, then copy | 1,044 | 202 | ||
| dual ring | 0 | 0 | 1,037 | 198 |
Nothing failed. The 1,037 reads that found their row on the old shard are close to the 1,044 that failed the first time, and that's no coincidence: both runs replayed the same requests, so about the same requests asked for a row that wasn't on s5 yet. The fallback cost little: the reads' p99 (the 99th percentile, the latency only 1% of reads exceeded) was 2.1 ms, against 2.5 ms when switching first, one run each.
The router, for a read
- Read: ask the user's shard on the new ring
- Not there? Answer 404, “no such user here”
The router, for a write
- Write: update the row on the new shard
- Not there? Answer 404; the update is refused
Share of all users not yet where the new ring says · modelled: a steady copy
Modelled at 11.0 s: about 18,955 of the 35,775 moving users are still on their old shard, 9.5% of all users. So about 95 reads and 19 writes a second ask s5 for a row it doesn't have yet: they fail. So far about 821 reads and 164 writes.
The recorded run · copy took 12.8 s
The line and the shaded area are the steady-copy model (the README's and the video's): 17.9% of users missing at the switch, falling evenly to 0. The real copy goes shard by shard in batches of 2,000 rows with a 0.3 s pause, so the real line is a staircase. Every number under “recorded run” is measured: one run per way, both replaying the same requests (same random seeds).
The lab's README names a third way, not measured here: copy, then switch. Copy all the rows first, replay the writes made during the copy from the database's change log (change data capture), then switch at once.
Was any update lost?
Failing a request is bad. Losing money is worse. So after each run 03_resharding.py reads every one of the 200,000 users from all five shards and checks:
- final balance = starting balance + every update the client was told succeeded. An acknowledged update is one the router answered "done" to.
- No user is missing (on no shard), and none is on two shards.
| Way | Updates acknowledged | Users with a wrong balance | Missing | On two shards |
|---|---|---|---|---|
| switch, then copy | 5,718 | 0 | 0 | 0 |
| dual ring | 5,920 | 0 | 0 | 0 |
Both ways: not one user wrong. In the first way, the 202 failed writes were refused and the client was told so: 5,718 + 202 = 5,920. Only the 5,718 updates that were acknowledged had to be there, and they were. A refused write isn't a lost write; a lost write would be one the client was told succeeded that isn't in the balance.
A doubling bug
The check exists for a reason. Here's the race when a write moves a row during the dual-ring copy:
- A write for user 42 finds no row on
s5. - In that split second, the copy job copies user 42's row to
s5(and then deletes it from the old shard). - The router's move takes the row out of the old shard and inserts it on
s5, where it's already there.
The first version of the router inserted with an upsert (INSERT ... ON CONFLICT DO UPDATE SET balance = balance + EXCLUDED.balance: insert, or if the row already exists, add the new balance to it). In this race it would add the two balances together and double the user's money. The fix is ON CONFLICT DO NOTHING: if the row is already there, leave it. That's safe because writes never go to the old shard during the move, so both copies are always equal.
The bug was found in review and fixed before any run, so no data shows it. Had it run and a write hit that split second, the balance check would have shown that user as over. The lab's README adds what would still break the fix: a second router that never got the new ring would write to the old shard, and the copies would differ. Rings have to change everywhere at once, which is why routers usually read the shard map from a coordination service.
IDs without a central counter
New users need new IDs. One database can just count: 1, 2, 3 (an auto-increment column). With five shards, each one counting on its own would hand out the same numbers, and one shared counter would put a single database on every insert's path.
So each machine makes its own: a Snowflake ID, the layout Twitter published in 2010. It's one 64-bit number, built in snowflake.py from three parts:
- 41 bits of time: milliseconds since an epoch, a fixed starting moment (1 January 2024 here).
- 10 bits of machine number: up to 1,024 machines, each with its own.
- 12 bits of counter, for IDs made in the same millisecond: up to 4,096 per millisecond per machine.
(The top bit stays 0, so the ID is a positive number.) Two machines never clash, as long as each has its own number. One machine never repeats itself, as long as its clock only moves forward: each ID is either in a new millisecond, or the next counter value in the same one. On the laptop's real clock one Python process made 3.8 million IDs a second, all unique and in order, and hit the 4,096-in-one-millisecond cap.
The clock steps back
But clocks step backwards. A server's clock drifts, and the service that keeps it in sync (NTP, the Network Time Protocol) may correct it by jumping it back; a virtual machine moved to another host can land on a clock that's behind.
04_ids.py tests this on a clock the test controls (FakeClock in snowflake.py): it moves forward 1 ms every 20 reads, so the generator makes 20 IDs a millisecond, and the test jumps it back every 20,000 IDs, 9 times in 200,000. Two generators: one that trusts the clock, and a fixed one.
| Clock steps back by | Trusts the clock: duplicates | Fixed: duplicates | Fixed: waited, all 9 jumps |
|---|---|---|---|
| 1 ms | 180 | 0 | 1 ms |
| 5 ms | 900 | 0 | 37 ms |
| 50 ms | 9,000 | 0 | 442 ms |
The trusting generator repeated exactly the IDs of the milliseconds it re-entered. After a 5 ms jump it lives through 5 milliseconds it already used, and its counter starts from 0 again in each: 20 IDs × 5 ms × 9 jumps = 900. For 50 ms: 1,000 per jump, 9,000 in all. Every one is the same ID handed out twice: two rows that would clash, or worse, two rows on different shards with the same ID that nothing notices.
The bug is one line in the trusting generator:
if ms == self.last_ms:
self.seq = (self.seq + 1) & MAX_SEQ # same millisecond: next counter value
else:
self.seq = 0 # the bug: also taken when ms < last_ms
The fix remembers the last millisecond it used. If the clock is behind it, it waits until the clock passes it, then carries on with the next counter value. If the clock is too far behind (more than max_wait_ms, 50 ms by default and 100 ms in this test), it refuses to make IDs rather than wait that long. No duplicates; the price is the wait. The waits are a little less than the jumps (442 ms for nine 50 ms jumps, not 450): the first jump waited 50 ms and the other eight 49 each, because in this test the clock ticks forward on the same read that notices the jump. The wait here is clock time on the fake clock, not measured real time.
The lab's test tests/test_snowflake.py checks that the trusting generator does duplicate after a step back, and the fixed one doesn't.
Are IDs in time order?
IDs start with the time, so do they sort in time order? 04_ids.py gives 4 machines 200,000 events, 20 a millisecond in all, and sets their clocks apart: evenly spread over 0, 1, 10 or 100 ms. It sorts the IDs and compares each with the next: is the event behind the bigger ID really later?
| Machine clocks spread over | Neighbours in the wrong real order | Worst: a newer ID for an earlier event, by |
|---|---|---|
| 0 ms (perfect) | 14.5% | 1.0 ms |
| 1 ms | 14.8% | 1.7 ms |
| 10 ms | 14.9% | 10.8 ms |
| 100 ms | 14.8% | 67.6 ms |
Even with perfect clocks, about 15% were out of order. Inside one millisecond, IDs from machine 0 come before machine 1's, whatever the real order. About 20 events a millisecond from 4 machines, sorted by machine: roughly 3 of every 20 neighbours change machine, and at each change the next ID is that machine's earliest event in the millisecond, usually earlier than the one before it.
Clock differences don't change how many are swapped; they make the swaps further off. With clocks up to 100 ms apart, an ID could be newer than its neighbour while its event happened 67.6 ms earlier.
A Snowflake ID: one 64-bit number, made on the machine itself
Time is milliseconds since an epoch (1 January 2024 here), and it comes first, so IDs sort roughly by time. Up to 1,024 machines, and up to 4,096 IDs per machine per millisecond. The top bit stays 0, so the ID is a positive 64-bit integer.
The first of nine jumps · simulation: the lab's snowflake.py ported, 20 IDs per millisecond
After the jump the clock reads milliseconds this generator has already used, and its counter starts from 0 again in each one: the red stretch repeats IDs it already gave out. 20 IDs a millisecond × 5 ms × 9 jumps = 900 duplicates.
Do IDs sort in time order? 4 machines, 20 events a millisecond
Worst gap for each clock spread (recorded). The share out of order hardly moves: 14.5–14.9%.
Why about 15% even with perfect clocks · one millisecond, illustration
The same millisecond's 20 IDs in ID order: machine 0's first, then machine 1's, and so on (m = machine, # = real order of the event). Each time the machine changes, the next ID is that machine's earliest event, usually earlier than the one before it: 3 of 20 neighbours here (outlined in red), about 15%. With clocks up to 100 ms apart, about as many are out of order (14.8%), but by up to 67.6 ms.
The jump chart is a simulation: the lab's snowflake.py and its controlled clock ported line for line and run on the same 200,000 IDs, so the simulated duplicates match the recorded ones; it shows the first jump. The one-millisecond strip is an illustration of the mechanism with made-up events; the shares and worst gaps are the recorded ones (one run, 200,000 events).
So sort by Snowflake ID for "roughly by time", never for "which happened first". The lab's README lists the alternatives: random UUIDs (unique by probability, no order, 128 bits), UUID version 7 (time plus random bits, roughly ordered, 128 bits, no machine numbers to hand out), or one counter per shard with a stride (shard k hands out k, k + N, k + 2N…).
Caveats
- One run per way, on a busy laptop. The counts are one run each; the 1,044 against 1,037 match because both runs replayed the same requests, not because the runs are precise.
- The copy estimate is a model. It assumes an even copy; the real job went shard by shard in batches of 2,000 with pauses, and the measured failures came in about 10% under the model (1,044 reads against 1,141, 202 writes against 228).
- One router. The dual ring is safe because a single router sends every write to the new shard. With several routers, all must switch rings together; the README suggests testing a second router that never got the new ring as an exercise, but it isn't measured.
- The doubling bug never ran. It's described from the lab's README and a comment in
service/app.py; it was fixed before any run, so there's no measurement of it. - The ID results are computed, not measured on real clocks. The clock is controlled by the test, 20 IDs a millisecond, with jumps chosen to show the effect; the waits are clock time on that fake clock. Only the 3.8 million IDs a second ran on the real clock.
- Not covered: copy-then-switch with change data capture, and how real systems hand out machine numbers (a registry or a lease, checked at startup), are in the README but not measured.
The checklist
- Use a ring with virtual nodes, or a fixed set of slots, not the remainder. Adding a shard should move about one in N+1 keys, all to the new shard, not four in five.
- Estimate the move before you run it. Users to move, copy time, request rate: half the moved share times the requests during the copy is how many would miss if you switch first.
- Keep the old ring as a fallback during the copy. Read the old shard on a miss, and move a row before a write updates it, so writes only ever go to the new shard.
- Make the row move idempotent. If the row is already on the new shard, do nothing; never add.
- Check every balance against what clients were told. Final = initial + acknowledged updates, nobody missing, nobody on two shards: that's how you know no confirmed update was lost or doubled.
- Make IDs locally, with a unique machine number per generator, handed out by a registry and checked at startup.
- Never let an ID generator go back in time. Remember the last millisecond; wait if the clock is a little behind, refuse if it's far behind.
- Don't use ID order for "which happened first". It's only roughly time.
Practice: move the rows, and keep the IDs unique
Write the lab's logic: the ring from partitioner.py (checked against the lab's own placements of users 1–20,000), the remainder rule, the steady-copy estimate, the router's reads and writes for both ways, the row move that does nothing when the copy job got there first, the balance check, and both Snowflake generators on the lab's controlled clock. The tests use the recorded numbers: 3,529 of the first 20,000 users move to s5 and 15,977 would under the remainder; the estimate gives 1,141 reads and 228 writes against the 1,044 and 202 measured; and a trusting generator makes 20 duplicates per millisecond it re-enters.
Quiz
1.Four shards become five. With consistent hashing (64 marks per shard), which users move?
2.The router switched to the new ring at once, then a copy job moved the rows over 12.8 s. Why did 1,044 reads fail?
3.What does the dual ring do with a write for a user whose row is still on the old shard?
4.During the dual-ring move, the copy job may already have put a row on the new shard when a write moves it. What should the move do?
5.A Snowflake generator that trusts the clock makes 20 IDs a millisecond. Its clock steps back 50 ms, nine times. How many duplicate IDs?
6.Four machines make Snowflake IDs with perfectly synchronised clocks. Do IDs sorted by ID come out in real time order?
Check your understanding
Try each question before opening its answer.
Why does adding a fifth shard move about one user in five with consistent hashing, but four in five with the remainder of the hash?
On the ring, the new shard's marks take over only the stretches just before them, so only the users there move, and all of them to the new shard: 35,775 of 200,000 here. With the remainder, a user stays only if their hash gives the same remainder divided by 4 and by 5, which is true for 4 values in 20; the lab's modulo rule would move 159,822, most of them between the old shards.
You switch the router to the new ring and then copy the rows for 12.8 s, at 1,000 reads a second. About how many reads fail, and why?
About 1,140. At the switch 17.9% of users aren't on the new shard yet, falling to 0 as the copy runs: about 8.9% on average, of about 12,760 reads. Each one asks the new shard for a row it doesn't have yet and gets a 404. The lab measured 1,044 reads and 202 writes failed.
What are the dual ring's two rules, and why do they keep both copies of a row equal?
A read tries the new shard and falls back to the old one; a write that finds no row on the new shard moves it there first, then updates it. Writes only ever change the new shard, so a row that briefly exists on both shards has the same balance on both. In the lab: 0 failures, 1,037 reads from the old shard, 198 rows moved by a write.
The switch-first run had 202 failed writes. Were they lost updates?
No. They were refused, and the client was told so. The balance check compares every user's final balance with the starting balance plus the updates the client was told succeeded: 5,718 of them, all present, and 5,718 + 202 = 5,920 writes sent. A lost update would be one acknowledged as done that isn't in the balance.
Moving a row uses "insert, and if it's already there, add the balances". What goes wrong, and what's the fix?
If the copy job put the row on the new shard in the split second before the move, the insert finds it there and adds the old balance to it, doubling the user's money. The fix is to do nothing when the row is already there: during the move nothing writes to the old shard, so the two copies are the same row. The lab's first version had this bug and fixed it before any run; the balance check would have shown that user as over.
A Snowflake generator's clock steps back 5 ms, nine times, while it makes 20 IDs a millisecond. How many duplicates, and how does the fix avoid them?
900: after each jump it re-lives 5 milliseconds it already used and restarts its counter in each, so it repeats 20 × 5 IDs, nine times. The fix remembers the last millisecond it used and waits until the clock passes it (37 ms of waiting in all here), or refuses to make IDs if the clock is too far behind.
Can you use Snowflake ID order to decide which of two events happened first?
No. Inside one millisecond the machine number decides the order, so even with perfect clocks 14.5% of neighbouring IDs were in the wrong real order, and with clocks 100 ms apart an ID could be newer than its neighbour while its event happened 67.6 ms earlier. ID order is "roughly by time", good for sorting a feed, not for deciding what happened first.
Next up: Chapter 20, full-text search. Every query so far was by key: give the user ID, get the row. Next, queries that aren't by key at all: finding every document that contains some words, with an inverted index.