ealeng

Episode 18 of 55 · Sharding

Sharding: consistent hashing, hot keys and one slow shard

Split a database across four shards with the simplest rule, add a fifth, and 80% of the keys have to move: the new shard needed 20%, the other 60% just swap between the old ones. A ring with many points per shard (consistent hashing) moved about 20%, all to the new shard. Then two problems no rule fixes, measured on real Postgres shards: one post getting 30% of all likes, and a query over every shard while one shard is busy.

Lab 10 · Partitioning and Sharding16 min read
Video transcript10:05

0:00Cold open

0:01

My database got too big for one machine, so I split it across four.

0:06

Then I planned to add a fifth. Before moving anything, I took a hundred thousand sample ids, placed by the simplest rule, and counted where each would go.

0:17

Eighty percent would have to move. Four out of five, for one new database.

0:23

The new shard only needed twenty percent. The other sixty would just swap between the four old ones, gaining nothing.

0:32

So how do you split data so that growing doesn’t mean moving almost everything?

0:39Intro

0:41

Hands-on system design, part eighteen.

0:44

Today: how to split one database across several, and two problems a better rule can’t fix.

0:51Meet Lucía

0:53

I’m Lucía, a platform engineer.

0:56

My service has two hundred thousand users, split across four Postgres databases. Each one is called a shard. Splitting data this way is called sharding.

1:07

Every request carries a user id. That’s the partition key, or just the key: a rule turns it into a shard, and a router in front sends the request there.

1:19

Think of filing cabinets. Each shard is a cabinet. The partition key is the name on a file. And the rule says which cabinet each name goes in.

1:30

Which rule you pick decides how many files you carry when you add a cabinet.

1:3601 · What you need

1:37

To run it yourself: Python with a few packages, and Docker for five Postgres shards, four plus one to add, and the router.

1:47

The quick tests run in a couple of seconds, without Docker.

1:52

And the first measurements need no databases at all. They only count where a hundred thousand keys would go. No cloud, and no API keys.

2:0302 · The remainder rule

2:04

The simplest rule: turn the key into a number, called a hash, divide it by the number of shards, and keep the remainder. That’s called modulo.

2:15

Say a key’s hash is thirteen. With four shards, thirteen divided by four leaves one. With five shards, it leaves three. A different shard, so the key moves.

2:27

Why so many? The remainders repeat every twenty numbers, because four times five is twenty. Out of each twenty hashes, only zero, one, two and three get the same remainder both ways. So four in twenty stay, and sixteen in twenty move.

2:44

Counted over a hundred thousand keys: eighty percent moved. The new shard only needed twenty. The other sixty percent just swapped between the four old shards.

2:5703 · A ring

2:58

A better rule: a ring, called consistent hashing. Picture every possible hash laid out in a circle, like a clock face.

3:07

Each shard gets a point on it, at the hash of its name. A key belongs to the next shard point clockwise.

3:15

In the filing-cabinet picture: each cabinet owns the stretch of the circle up to its point.

3:22

With one point per shard, these are the real stretches. s1 owns thirty-seven percent of the circle. s2, four percent.

3:32

Now add a fifth shard. Its point lands here, inside s3’s stretch. Will the new shard take an even share?

3:42

No. s5 took part of s3’s stretch, about ten percent of the keys, and nothing moved between the old shards. But the shards stayed lopsided.

3:5404 · Many points

3:55

The fix: give each shard many points around the circle. They’re called virtual nodes. Small stretches, many of them, average out.

4:05

First, one point each, counted over a hundred thousand keys. Ten percent moved, all to the new shard. But the busiest shard held one point eight five times the average: the average is twenty thousand keys, and s1 held thirty-seven thousand. One would be perfectly even.

4:25

Sixteen points per shard: twenty percent moved, still all to the new shard. The busiest held one point one four times the average.

4:35

Two hundred fifty-six points: twenty-one percent moved, and every shard held between eighteen and twenty-two percent. The share that moves is just the new shard’s share, so twenty-one means s5 got a little more than its fair share.

4:51

For a fifth shard, one key in five is the fair share: twenty percent. The remainder rule moved eighty.

5:0005 · In code

5:01

Both rules are a few lines of code.

5:05

The remainder rule: the key’s hash, modulo the number of shards.

5:11

The ring: each shard gets as many points as you ask for, each the hash of its name plus a number.

5:18

To place a key: find the first point past the key’s hash, and return that point’s shard.

5:25

The router in the rest of this video uses sixty-four points per shard.

5:3206 · One hot post

5:33

So far we only counted keys. Real traffic is uneven: a few keys get a big share of it.

5:40

And a ring spreads keys, not traffic. One key always lives on one shard. In the cabinet picture: one file that everybody wants.

5:50

Now a real test, on the real shards and router. Three thousand likes a second for twenty seconds, thirty percent of them on one post, post forty-two. Here the key is the post id. That’s nine hundred likes a second.

6:06

Its counter is one row, on s1. So s1 got forty-seven percent of all likes: the thirty percent for post forty-two, plus its quarter of the rest, about seventeen. Nothing failed.

6:20

The slowest like in every hundred, for post forty-two, took twelve point eight milliseconds or more. For other posts: eight point one. Every like for it updates the same row, so they probably wait in line for that row. The test shows the delay, not the line itself.

6:3907 · Split the key

6:40

The fix: split the counter into sixteen rows, each with its own key: post forty-two, row zero, up to row fifteen. Each row lands wherever the ring puts it.

6:52

Each like adds one to a random row.

6:56

To read the count, add up all sixteen rows. The ring put six of them on s2, four on s1, four on s3 and two on s4. So a read now asks four shards instead of one.

7:1108 · Split, measured

7:12

Split sixteen ways, the likes spread out: twenty-one to thirty-one percent per shard. s2 got the most: it holds six of the sixteen rows, and the biggest stretch of the ring.

7:25

Post forty-two’s slowest like in every hundred took six and a half milliseconds, half as long. Other posts got faster too in this run, from eight point one to six point three, so part of that is run-to-run noise. The clear change: post forty-two is now as fast as the rest.

7:44

The typical like took the same both ways, under a millisecond. At nine hundred a second, one row kept up. Splitting helped the slowest likes.

7:5609 · One busy shard

7:57

Last: a query that isn’t by user id. The ten users with the biggest balances. No rule knows where they are, so the router checks every cabinet: it asks all four shards and merges the answers. That’s called scatter-gather.

8:13

Normally, a typical read by user id took under a millisecond. The top ten, slowest one in a hundred: six and four milliseconds, in the two runs.

8:25

Then I made s3 busy, with two heavy queries running on it. Reads by user id on s3 slowed to forty-seven and fifty-two milliseconds, slowest one in a hundred.

8:38

And the top ten, which asks all four shards?

8:43

Fifty-two and fifty-four milliseconds. Nine and fourteen times slower. It waits for every shard, so it’s as slow as the slowest one.

8:54

Reads on the other three shards slowed too. In run two, up to twenty-two milliseconds, from about three. In run one, barely: four to five. Nothing extra ran on them. My guess is the router and the laptop they share with s3, which this test doesn’t measure.

9:13Back to Lucía

9:14

So, three lessons.

9:17

Use a ring with many points per shard. Adding a fifth shard moved about one key in five, all to the new one. The remainder rule moved four in five.

9:28

Pick the partition key by how you query. A read by key asks one shard. A query the key can’t answer asks all of them, and waits for the slowest.

9:39

And when one key is hot, no rule can spread it. Split it yourself.

9:45

Next time: adding a shard while the service runs, and making IDs without a central counter.

9:52

For today: split the hot ones.Lucía: Split the hot ones.

9:56Summary

9:58

Use a ring with many points, pick the key by your queries, and split hot keys.

Key takeaways

  • ✓Sharding splits one dataset across several databases, called shards. The partition key (here a user id or a post id) decides which shard a row lives on; a router in front sends each request there. The rule that turns a key into a shard decides how much data moves when you add a shard.
  • ✓The remainder rule (modulo: the key's hash divided by the number of shards, keep the remainder) moved 80.0% of 100,000 keys going from 4 shards to 5. Only 20% went to the new shard, which needed them; 59.8% swapped between the old shards and gained nothing. A hash keeps its shard only if its remainders by 4 and by 5 agree: 4 numbers in every 20.
  • ✓Consistent hashing puts shards on a ring of hash values; a key belongs to the next shard point clockwise. A new shard only takes the stretches just before its own points, so nothing moves between old shards. With one point per shard it moved 10.4%, all from one neighbour, and left the shards lopsided: one held 37% of the keys and another 4%, the busiest 1.85× the average.
  • ✓Many points per shard (virtual nodes) average out the stretches: 16 points moved 19.6% of keys, 256 points 21.3%, all to the new shard, which took a little from every old one; with 256, every shard held 18–22%. The share that moves is just the new shard's share: about 1 in N.
  • ✓No rule spreads one key. A post getting 30% of 3,000 likes a second put 47% of all likes on its shard, and every one updated the same row: its slowest like in 100 (p99) took 12.8 ms against 8.1 ms for other posts. Split into 16 rows on all four shards, the shards got 21–31% each and the hot post's p99 was 6.5 ms, level with other posts (6.3). Reading the count now asks 4 shards.
  • ✓A query the partition key can't answer asks every shard and waits for the slowest (scatter-gather). With one shard busy, a top-10 query over all four went from 5.9 and 3.8 ms at p99 to 52.2 and 54.0 ms in two runs: 9× and 14× slower. Reads by key on the busy shard slowed as much; reads on the other shards slowed a little in one run and a lot in the other.

A database got too big for one machine, so it was split across four, and a fifth was planned. Before moving anything, the lab counted where 100,000 sample ids would go under the simplest rule: 80% would have to move, for one new database that needed only 20%. This chapter measures how to split data so that growing doesn't mean moving almost everything, and then two problems that no splitting rule fixes: one key that gets a big share of the traffic, and one slow database that every query over all of them has to wait for.

The examples come from Lab 10 (Partitioning and Sharding) of the system design labs: Exercise 1 of 01_partitioning.py (where 100,000 keys go when a fifth shard is added, under each rule; counted offline, no databases) and 02_shards.py (real traffic on real shards: a hot post, and a query over every shard while one is busy). The rules themselves are in the lab's partitioner.py, and the router in service/app.py. The same lab's scripts on adding a shard while the service runs and on making IDs without a central counter (03_resharding.py and 04_ids.py) are the next chapter, resharding and Snowflake IDs. Two parts of 01_partitioning.py aren't covered in this track: Exercise 2 (how uneven the load is when some keys are much busier than others) and Exercise 3 (orders split by their date: all of today's writes land on one shard, while a "last 7 days" query asks only one).

The setup is the earlier chapters' laptop (an Apple M4 Max, Docker Desktop with 16 virtual CPUs): four Postgres 18.6 databases with one CPU each, plus an empty fifth, and a router in front of them, a Python web service (FastAPI) running as one process, all in Docker, with the load generator in Docker too. Other work kept the laptop busy (a load average, the number of processes wanting a core, of 5–12). The lab's 381 unit tests (the partitioning rules, the ID generator, the metrics) run in under 2 seconds without Docker; they all pass.

Filing cabinets

The service has 200,000 users, split across four Postgres databases. Each one is called a shard, and splitting data this way is called sharding (or partitioning). The lab names the shards s1 to s4; s5 is the fifth, empty one to add later.

Every request carries a user id. That's the partition key, or just the key: a rule turns it into a shard, and the router in front sends the request there. Any query that gives the key goes to one shard. Any query that doesn't has to go to all of them.

Think of filing cabinets. Each shard is a cabinet. The key is the name on a file. The rule says which cabinet each name goes in. And which rule you pick decides how many files you carry when you add a cabinet.

Rule 1: the remainder

The simplest rule: turn the key into a number, called a hash, divide it by the number of shards, and keep the remainder. That's modulo. In the lab's partitioner.py:

def shard(self, key):
    return self.shards[h64(key) % len(self.shards)]

h64 is the lab's hash: 64 bits of BLAKE2b, a standard hash function, so a key gets the same number in every process and every run. (Python's own hash() changes from one process to the next, so it can't decide where data lives.)

Say a key's hash is 13. With four shards, 13 ÷ 4 leaves 1. With five, 13 ÷ 5 leaves 3. A different shard, so the key moves. Why does that happen to so many? The remainders by 4 and by 5 repeat every 20 numbers, because 4 × 5 = 20. Out of each 20 hashes, only 0, 1, 2 and 3 get the same remainder both ways. So 4 in 20 stay, and 16 in 20 move.

The lab counted it over 100,000 keys (the ids 0 to 99,999): 80.0% moved. The new shard needed 20% of the keys, and got 20.2%. The other 59.8% just swapped between the four old shards, gaining nothing. In a real move, every one of those is a row copied over the network while the service runs.

Rule 2: a ring

A better rule: a ring, the idea behind consistent hashing. Picture every possible hash laid out round a circle, like a clock face. Each shard gets a point on it, at the hash of its name. A key belongs to the next shard point clockwise. In the cabinet picture: each cabinet owns the stretch of the circle up to its point.

Add a fifth shard, and its point lands somewhere on the circle. Only the keys on the stretch just before it change owner, and they all go to the new shard. Nothing moves between the old ones.

With one point per shard, the lab's ring is lopsided. s1 owns 37% of the circle, s2 only 4%. s5's point landed inside s3's stretch, and took about 10% of the keys: all from s3.

Many points per shard

The fix: give each shard many points around the circle, called virtual nodes. The ring's code, shortened from partitioner.py:

points = sorted((h64(f"{s}#{v}"), s) for s in shards for v in range(vnodes))

def shard(self, key):
    i = bisect.bisect_right(self.ring, h64(key))   # the first point past the key's hash
    return self.owner[i % len(self.ring)]          # past the last point, wrap round to the first

Each shard gets vnodes points, each at the hash of its name plus a number (s1#0, s1#1, …). Many small stretches average out. Toggle the points per shard and add s5:

Try it · The ringLab 10 · partitioner.py · the real points

Every possible hash laid out round a circle. Each shard has points on it; a key belongs to the next point clockwise, so each point owns the stretch of circle just before it.

s4s2s1s34 pointsclockwise from the top

Share of the ring · keys of 100,000

s137.1% · 37,083
s24.4% · 4,453
s326.9% · 26,652
s431.6% · 31,812

Tick: a fair share, 1/4.

One point per shard: where the points land is luck. s1 owns 37% of the circle and s2 only 4%, so s1 holds more than eight times as many keys.

Points are the lab's own: the BLAKE2b hash of "s1#0", "s1#1"… as in partitioner.py, drawn at their place on the ring. Shares are each shard's stretches added up; key counts are the 100,000 sample ids placed on this ring.

The lab counted each rule going from 4 shards to 5, over the same 100,000 keys:

Rule Keys moved Moved between old shards Busiest ÷ average after Keys on s1 / s2 / s3 / s4 / s5
remainder (modulo) 80.0% 59.8% 1.01 20 / 20 / 20 / 20 / 20%
ring, 1 point per shard 10.4% 0% 1.85 37 / 4 / 16 / 32 / 10%
ring, 16 points per shard 19.6% 0% 1.14 23 / 17 / 20 / 20 / 20%
ring, 256 points per shard 21.3% 0% 1.10 20 / 18 / 19 / 22 / 21%

"Busiest ÷ average" is the lab's imbalance measure: 1 is perfectly even. With five shards the average is 20,000 keys, and with one point per shard s1 held 37,083, so 1.85.

  • The remainder rule ends even, but almost every file changes cabinet on the way.
  • One point per shard moved only 10.4%, all to s5, but left the shards as lopsided as before.
  • 16 points moved 19.6%, still all to s5, and the busiest held 1.14× the average.
  • 256 points moved 21.3%, and every shard held between 18% and 22%. The share that moves is just the new shard's share, so 21.3% means s5 got a little more than its fair 20%. With 256 points, s5 took 5,000–6,000 keys from each of the old shards, instead of a big piece of one.

For a fifth shard, one key in five is the fair share. The remainder rule moved four in five. See every file's journey in the cabinets:

Try it · Add a fifth cabinetLab 10 · 01_partitioning.py Ex. 1 · 100,000 keys, counted offline

Each shard is a filing cabinet; each key is a file. Four cabinets hold 100,000 files, then a fifth is added. Pick the rule that says which cabinet a file goes in.

Files in each cabinet after adding s5 · coloured by the cabinet they were in before

5,009 files stayed in4,854 files came from s25,063 files came from s34,950 files came from s419,876s15,025 files stayed in5,006 files came from s15,047 files came from s34,921 files came from s419,999s25,001 files stayed in5,019 files came from s14,986 files came from s25,079 files came from s420,085s34,972 files stayed in4,920 files came from s15,083 files came from s24,884 files came from s319,859s45,015 files came from s15,118 files came from s25,047 files came from s35,001 files came from s420,181s5 (new)
was in s1 was in s2 was in s3 was in s4 files before s5 average, 20,000
Keys moved
80.0%
Between old shards
59.8%
Busiest ÷ average
1.01

Every cabinet ends up even, about 20,000 files, but look at the colours: each old cabinet now holds files from all the others. 80.0% moved. Only 20.2% went to s5, which needed them; the other 59.8% swapped between the four old cabinets and gained nothing.

Counted, not measured: the lab's own partitioner.py run over the ids 0–99,999 with 4 shards and then 5, the same count as the lab's recorded table (01_partitioning.json). Hover a block for its count.

The router in the rest of the lab uses 64 points per shard. On that ring, the 200,000 users went 49,110 / 56,513 / 45,383 / 48,994 to s1–s4. (Counted with the lab's code for this chapter, the same ring going to five shards moves 17.8% of the 100,000 sample keys: the fair 20% is an average over rings, and any one ring is a little off. The next chapter moves real rows on it.)

One hot post

So far the lab only counted keys. Real traffic is uneven: a few keys get a big share of it. And a ring spreads keys, not traffic. One key always lives on one shard. In the cabinet picture: one file that everybody wants.

Now a real test, on the real shards and router. 3,000 likes a second for 20 seconds, 30% of them on one post, post 42: that's 900 likes a second. The other 70% are spread evenly over 100,000 posts. Here the key is the post id, and each post's like count is one row, updated by every like:

INSERT INTO likes (key, n) VALUES ($1, 1) ON CONFLICT (key) DO UPDATE SET n = likes.n + 1

(That adds the row the first time, and adds 1 to it after that.) Post 42's row lives on s1. So s1 got 47% of all likes: the 30% for post 42, plus its share of the rest, about 17 points.

Post 42's counter Share of all likes on s1 / s2 / s3 / s4 Post 42's p50 Post 42's p99 Other posts' p99 Likes a second done Failed
one row 47 / 20 / 16 / 17% 0.68 ms 12.8 ms 8.1 ms 3,020 0
split into 16 rows 25 / 31 / 23 / 21% 0.68 ms 6.5 ms 6.3 ms 2,993 0

p50 is the median, the typical like; p99 is the time that the slowest 1 like in 100 exceeds. Nothing failed. The typical like took the same either way, under a millisecond. The slowest ones are where the hot post paid: 12.8 ms at p99, against 8.1 ms for other posts. Every like for it updates the same row, and Postgres lets only one update hold a row at a time, so they probably wait in line for that row. The test shows the delay, not the line itself: the lab didn't record lock waits.

Split the hot key

The fix changes the key. Split the counter into 16 rows, each with its own key: 42#0 up to 42#15 (post 42, row 0 to row 15). Each like adds one to a random row. To read the count, add up all 16. Each row lands wherever the ring puts it: six on s2, four on s1, four on s3 and two on s4. So a read now asks four shards instead of one.

Split 16 ways, the likes spread out: 21% to 31% per shard. s2 got the most: it holds 6 of the 16 rows and the biggest stretch of the ring. That's predictable: 30% × 6/16 for its rows, plus 70% × its 28.2% of the ring, is 31.0%, and it measured 31.1%.

Post 42's p99 fell to 6.5 ms, half of what it was. But other posts got faster too in this run, from 8.1 to 6.3 ms, so part of that is run-to-run noise. The clear change: post 42 is now as fast as the rest. And the count stayed exact: 18,239 likes counted for 18,239 sent with one row; 17,918 for 17,915 split (the three extra came from the other stream, which picks from all 100,000 posts, post 42 included).

At 900 likes a second, one row kept up. Splitting helped only the slowest likes. The lab also tried 6,000 likes a second, where one row's p99 reached 135 ms, but there the single router process ran out of CPU and every request slowed, so it measured the router, not the row, and isn't in the table.

Try it · Real traffic on real shardsLab 10 · 02_shards.py · 4 Postgres shards, 20 s runs

3,000 likes a second for 20 s: 30% on post 42 (900 a second), the rest spread over 100,000 posts. The key is the post id.

Each shard's share of all likes · post 42's rows on it

s147.2%1 row
s219.8%0 rows
s316.1%0 rows
s416.9%0 rows

Bar: measured. Tick: predicted from the ring, 30% × the rows it holds ÷ 1 + 70% × its stretch of the router's ring.

Post 42 p99
12.8 ms
Other posts p99
8.1 ms
Post 42 p50
0.68 ms
Failed
0

Every like for post 42 updates one row on s1, so s1 got 47% of all likes: the 30% for post 42 plus its share of the rest. The slowest like in a hundred (p99) for post 42 took 12.8 ms, against 8.1 ms for other posts. The typical like (p50) was under a millisecond either way.

Recorded, one run each (3,020 and 2,993 likes a second done). Count check: 18,239 likes counted for 18,239 sent unsplit; 17,918 for 17,915 split (the 3 extra came from the other stream, which can pick post 42 too).

One busy shard

Last: a query that isn't by user id. The ten users with the biggest balances. No rule knows where they are, so the router asks all four shards for their top ten and merges the answers. That's called scatter-gather. From the router:

rows = [r for part in await asyncio.gather(*(one(s) for s in shards)) for r in part]

asyncio.gather sends the four queries at once and waits until all of them have answered.

The test: 1,000 reads by user id a second (spread over all 200,000 users) and 100 top-10 queries a second, for 20 s. Then the same with s3 busy: two heavy queries running on it, each adding up 400 million numbers. Two rounds, in alternating order. p99 in ms, round 1 / round 2:

Normal s3 busy
read by user id, on s3 3.7 / 2.9 47.4 / 52.1
read by user id, worst of s1, s2, s4 4.3 / 2.8 5.2 / 22.4
top 10 over all 4 shards 5.9 / 3.8 52.2 / 54.0

Normally, a typical read by user id took under a millisecond (p50 0.56–0.62 ms), and the top ten's p99 was 5.9 and 3.8 ms. With s3 busy, reads on s3 slowed to 47 and 52 ms at p99. And the top ten, which asks all four shards, took 52.2 and 54.0 ms: 9 and 14 times slower. It waits for every shard, so it's as slow as the slowest one, every time. A read by key on s1 doesn't wait for s3 at all.

Reads on the other three shards slowed too. In round 2, up to 22.4 ms from 2.8, though nothing extra ran on them. In round 1, barely: 4.3 to 5.2. The likely cause is what they share with s3: the one router process and the laptop. The test doesn't measure that, so it's a guess.

Caveats

  • The key counts are counted, not measured. The rules ran over the ids 0–99,999 in Python, with no databases; recomputing them from the lab's partitioner.py gives the recorded numbers exactly. The hot post and the busy shard are real runs on real Postgres shards.
  • One laptop, one run per row for the likes, two rounds for the busy shard. Load averages of 5–12 from other work. Round 2's 22 ms on the quiet shards and the other posts' 8.1 → 6.3 ms show how much one run can move on its own.
  • The row lock is the likely reason, not a measured one. The lab recorded latencies, not lock waits. And at 900 likes a second on one row the effect is modest; the test that would show it bigger (6,000 a second) ran out of router CPU first.
  • The README rounds some numbers differently. For the busy shard, the lab's README gives medians across the two rounds: reads on the quiet shards "3.6 → 13.8 ms", which matches neither round (4.3 → 5.2 and 2.8 → 22.4), and s3 "49.7 ms", between 47.4 and 52.1. It also calls the top-10 slowdown "10×"; per round it was 9× and 14×. This chapter gives each round.
  • Where the shards share things, they aren't independent. One router, one Docker VM, one laptop. On separate machines, one busy shard would likely slow the others less; scatter-gather would still wait for it.
  • Not covered here: how uneven the load gets under skewed traffic, and splitting by time (Exercises 2 and 3 of 01_partitioning.py); moving rows to a new shard while the service runs, and IDs across shards (next chapter).

The checklist

  1. Use a ring with many points per shard (64–256), not the remainder rule. Adding a shard should move about 1 key in N, all to the new shard.
  2. Count before you move. Run your rule over a sample of keys, old shards and new, and look at how many move and where they go.
  3. Pick the partition key by how you query. A read by key asks one shard. A query the key can't answer asks all of them, and waits for the slowest.
  4. Find your hot keys before they find you: the share of traffic the top keys get, not just how many keys each shard holds.
  5. When one key is hot, split it yourself (or cache it, for reads, or give it a shard of its own). No rule spreads one key. Splitting costs reads that ask several shards.
  6. For queries over every shard, watch the slowest shard, not the average. Keep a second copy organized for those queries, or set a deadline and answer from the shards that made it.

Practice: rings, moves and a hot counter

Write the lab's rules from scratch: the remainder rule, the share of hashes that stay under it (4 in 20), a ring with points per shard, each shard's share of the ring, and the moves between two rules. The tests run them over the same 100,000 keys and check the recorded counts exactly (79,993 moved under modulo; 10,450 from s3 alone with one point per shard; 19,598 and 21,332 with 16 and 256). Then the hot post: where its 16 rows land on the router's 64-point ring, which shards a read asks, the shares of likes each shard should get (against the 47.2% and 31.1% measured), and what a scatter-gather waits for.

Try it · Practice in PythonRuns in your browser · ⌘/Ctrl + Enter to run
shard_practice.py95 lines

Quiz

Try it · Check your understanding0 of 6 answered
  1. 1.Four shards, the remainder rule (hash modulo the number of shards). You add a fifth. About what share of keys has to move?

  2. 2.On a consistent-hashing ring, a new shard's point lands on the circle. Which keys move?

  3. 3.With one point per shard, one shard held 37% of the keys and another 4%. What fixes it?

  4. 4.One post gets 30% of all likes, and its like counter is a single row. Why can't a better partitioning rule fix that?

  5. 5.The counter was split into 16 rows. What did that cost?

  6. 6.A top-10 query asks all four shards and merges the answers. One shard gets busy. What happens to the query's p99?

Check your understanding

Try each question before opening its answer.

Why did the remainder rule move 80% of keys when only 20% needed to go to the new shard?

A key's shard is its hash's remainder by the number of shards, so changing 4 to 5 changes the answer for almost every key. The remainders by 4 and 5 repeat every 20 numbers, and only 4 of those 20 give the same answer both ways. The lab counted 80.0% moved: 20.2% to the new shard and 59.8% between the four old ones, which gained nothing.

On a ring with one point per shard, adding a fifth moved only 10.4% of keys. Why is that not good news?

It moved little because the new point happened to land in a small stretch, all inside one old shard's. The shards stayed lopsided: one held 37% of the keys and another 4%, the busiest 1.85 times the average. With one point each, both the share that moves and the balance are luck.

What do virtual nodes change, and how many did the lab's router use?

Each shard gets many points on the ring instead of one, so it owns many small stretches, which average out. A new shard's points land all round the circle and take a little from every old shard. With 256 points, adding a fifth moved 21.3% of keys, all to the new shard, and every shard held 18–22%. The lab's router used 64 points per shard.

One post got 30% of all likes. Why did its shard get 47%, and not 30%?

That shard got the hot post's 30%, plus its normal share of every other post's likes: about a quarter of the other 70%, roughly 17 points. The rest of the likes spread by the ring like any keys.

Splitting the hot counter into 16 rows halved its p99, from 12.8 to 6.5 ms. Why doesn't the chapter credit the split with all of that?

Other posts also got faster in the split run, from 8.1 to 6.3 ms, though nothing changed for them, so part of the drop is run-to-run noise on a busy laptop. What the split clearly did: the hot post's p99 came level with the rest, and the shards' shares of likes evened out to 21–31%.

Why did one busy shard make the top-10 query 9 to 14 times slower at p99, but leave reads by user id on the other shards mostly alone?

The top-10 asks all four shards and waits for the last answer, so every one of them waits for the busy shard: 52.2 and 54.0 ms at p99, against 47.4 and 52.1 ms for reads on that shard itself. A read by user id asks one shard and never waits for the busy one. The quiet shards did slow in one run (to 22.4 ms), probably from the router and laptop they share, which the test doesn't measure.

You shard orders by customer. Which queries got cheap, and which got expensive?

Cheap: anything about one customer, which asks one shard. Expensive: anything across customers, like all orders yesterday or the top products this week, which has to ask every shard and wait for the slowest. If those matter, keep a second copy of the data organized for them, such as a table keyed by date.

Next up: Chapter 19, resharding and Snowflake IDs. This chapter counted which keys would move to a fifth shard. The next one moves them for real, while the service runs: what fails if you switch first and copy after, how a router that checks both rings fails nothing, and how to make IDs on every shard without a central counter.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.