Advanced partitioning
hard 30 minRunning a partitioned database means keeping it balanced.
Video lesson · Chapter 1 of 5
One shard runs hot under a balanced total
Theory
Read or listen first. About 1 min.
What it is
Advanced partitioning is what happens after the first split. Data grows unevenly, traffic moves, machines are added, and some questions need every partition. The work is to notice, plan, change and check, without stopping.
Four subjects cover most of it: rebalancing (split, merge, move), hot spots, cross-shard queries (scatter-gather), and composite keys (two rules together).
Why it exists
No key stays perfect. A small customer becomes a giant, a post goes viral, a year of data arrives. One partition then sets the limit for the whole system, while the others have room.
Moving data costs disk, network and care. Done badly, a rebalance is itself an outage: it adds load to the machine that is already too busy. So it must be slow, checked and possible to undo.
A short history
1997
Karger and colleagues introduce consistent hashing, made for relieving hot spots on the web.
2006
Google's Bigtable paper describes tablets, ranges of rows that are the unit of spreading and balancing load.
2010
MongoDB 1.6 calls its sharding ready for production. Work on Vitess starts at YouTube to grow MySQL.
2012
Google publishes Spanner, a globally spread database with transactions over its parts.
Words to know
- Rebalancing
- Moving data so that partitions or machines carry a fair share.
- Split and merge
- Cutting one partition into two, and joining two small neighbours.
- Hot spot
- A partition with far more traffic or data than the others.
- Hot key
- One single key with too much traffic. Splitting between keys cannot help.
- Salting
- Adding a small extra part to a key so that its rows spread out.
- Scatter-gather
- Ask every partition, collect the answers, merge them.
- Composite key
- A partition key made of several fields or several rules.
- Saga
- A chain of local transactions, each with a step that undoes it.
How it works
Step through the idea, or press Play.
Monitor and detect. Size, requests and response time per partition, and the hottest keys
Understand it
Start here
The crowded aquarium
An aquarium has three tanks. One is too full. Moving fish is easy to say, but the fish must stay alive and the visitors must still be able to look. And one problem cannot be solved by moving fish at all.
To count all fish in the building, ask each tank and add up. That is scatter-gather.
The idea
Four jobs after the first split
Hot spots
Uneven traffic or size overloads some partitions.
Rebalancing
Redistribute when partitions become uneven.
Cross-shard queries
Questions that need several partitions.
Composite sharding
Two keys or two rules together.
The loop you run for ever
Detect
Is it really unbalanced?
Measure per partition: rows, bytes, requests per second, processor, and the slowest 1% of requests. Size and traffic are different. A small partition can be the busiest.
Four shards
| Shard | Records | Load |
|---|---|---|
| 1 | 1,500 | 85% |
| 2 | 400 | 25% |
| 3 | 350 | 20% |
| 4 | 500 | 30% |
A simple rule: more than 1.5 times the average
Rebalance
Split, merge, move
| Operation | When | Example | Data copied |
|---|---|---|---|
| Split | A partition is too large or too hot | 150 GB becomes 75 GB and 75 GB | About half, if one half goes to another machine |
| Merge | Neighbours are small and quiet | 5 GB and 8 GB become 13 GB | The smaller one |
| Move | A machine is too busy, partitions are fine | Partition 7 goes to machine 3 | The whole partition |
Split where the data divides in two, not in the middle of the key interval. If shard 1 owns keys 0 to 9,999 and 90% of its rows lie above 8,000, cutting at 5,000 leaves one side with less than a tenth of the rows.
Splitting while serving
A split, step by step
Who starts it?
| Automatic | Started by people | |
|---|---|---|
| Trigger | Size or load limits | A person or a schedule, in quiet hours |
| Good | Little daily work | Full control of time and speed |
| Risk | May move data at the worst moment | Forgotten until it hurts |
| Examples | MongoDB balancer, CockroachDB ranges | Vitess Reshard workflow, self-built systems |
A common middle way: the system proposes, a person approves. An automatic system can mistake a slow machine for a hot one, move data, and make it slower still.
Speed
Moving without hurting
How long does a move take?
- 1
Limit the speed
Slow down when response times rise.
- 2
One at a time
Limit how many moves touch one machine.
- 3
Start early
At 60% full there is room to copy. At 95% the copy itself breaks things.
- 4
Check
Compare counts and checksums, and read from both for a while.
- 5
Keep a way back
Replicate from new to old for a while, so that the switch can be undone.
Hot spots
Four causes
Sequential keys
Ids 1001, 1002, 1003 under a range rule all go to the last shard.
Time patterns
This month is read and written far more than last year.
Popular entities
A celebrity, a viral post: one id with millions of reads.
Skewed values
One region holds 60% of the users.
Which cure?
Hot spots
Four cures and their price
| Cure | How | Price |
|---|---|---|
| Add randomness (salting) | Write post 42 as 42#0 to 42#3 | A read must collect all the pieces |
| Cache | Answer hot reads from memory | Slightly old data; does not help writes |
| Split | Cut the partition in two | Useless for one key |
| Better key | More values, or one more field | Most effective, and a full migration |
One hot post, treated twice
Salt only the keys that are hot. Salting everything turns every read into several. A calculated suffix, such as a hash of the order id modulo 4, lets you find one known row again. A random suffix does not.
Cross-shard
Scatter, execute, gather, merge
One shard (fast)
- Users where user_id is 123
- The key is in the question
- Routed to exactly one shard
All shards (slower)
- Count of users where age is above 25
- No key in the question
- Every shard must look
Counting over four shards
- 1
Scatter
The coordinator sends the question to all shards at once.
- 2
Execute
Each shard works on its own data.
- 3
Gather
The answers come back, some sooner, some later.
- 4
Merge
The coordinator combines them and replies. Like a post office that sends a question to every house, collects the replies and counts.
Not every answer can be merged from the parts. Counts and sums can be added. An average needs the sum and the count of each shard. A median or the number of distinct values needs more: raw values, or a sketch that can be merged.
Never average the averages
Sorting and pages: for rows 1,001 to 1,010 in order, each shard must send its first 1,010 rows, because any of them may belong to the answer. With 4 shards that is 4,040 rows for 10. Use a cursor: each shard continues after the last key seen and sends at most 10 rows.
Four problems of crossing shards
| Problem | What happens | Answer |
|---|---|---|
| Latency | Slowest shard plus merging | Timeouts, small fan-out, precomputed results |
| Sorting, pages | Too many rows are sent | Cursors instead of offsets |
| Joins | Rows travel between machines | Same key for related tables, or copied fields |
| Transactions | Several machines must agree | Two-phase commit, or a saga |
Two-phase commit in one picture
Composite
Two keys together
Region first, then a hash of the user
// MongoDB: a compound shard keysh.shardCollection("db.orders", { tenant_id: 1, created_at: 1 })Two common pairs
| Pair | Good for | Watch |
|---|---|---|
| Tenant, then time | Ranges of time inside one tenant, and splitting a large tenant | The newest range of a busy tenant |
| Region, then hash | Short distance, even spread inside the region | Regions of different size |
Single or composite?
| Single key | Composite key | |
|---|---|---|
| Complexity | Simple | Higher |
| Queries served well | One kind | Those that name the first part, or all parts |
| Spread | Limited by the key's values | More even, large values can be split |
| Rebalancing | Simpler | More to plan |
Change
When the key itself is wrong
Sometimes no split helps, because the key is wrong. Then build a second layout beside the first.
- 1
New layout
Create shards with the new key.
- 2
Write to both
Or stream every change from old to new.
- 3
Fill in history
Copy old rows at a limited speed. Newer rows must win over the copy.
- 4
Compare
Read from both, answer from the old, log differences.
- 5
Switch reads, then writes
A small share first. Keep the old layout until you are sure.
Some stores do this for you: MongoDB can refine a key by adding fields at its end, and since version 5.0 can reshard a collection with a new key. Streams of changes are in change data capture.
Worked example
A recipe site goes viral
Assume recipes are hashed over 16 shards, each good for 2,000 requests a second. Normal traffic is 6,000 a second. One recipe suddenly gets 8,000 reads and 400 likes a second.
Before and after a cache
Splitting the shard would have helped nobody: the viral recipe is one key. The cache costs at most one second of old data. Related ideas: consistent hashing, sharding, data replication, and for answers during a network split the CAP theorem.
Summary
The whole topic in one minute.
Keep partitions balanced by splitting what is too large, merging what is too small, and moving partitions between machines. Copy first, stream changes, check, switch the map, and clean up later.
A hot partition can be split, a hot key cannot: cache it, copy it or salt it. Questions without the key are as slow as the slowest partition. Composite keys let one owner's data stay together and still spread a large owner out.
- Monitor, detect, plan, execute, verify, and again.
- Split at the middle of the data, merge only neighbours, move whole partitions.
- Copy, stream, check, switch, clean up later, all at a limited speed.
- A hot partition can be split. A hot key must be cached, copied or salted.
- Scatter-gather is as slow as the slowest shard, and averages cannot be averaged.
- Composite keys keep an owner together and let large owners spread.