AlgoViz

Advanced partitioning

hard 30 min

Running a partitioned database means keeping it balanced.

Video lesson · Chapter 1 of 5

One shard runs hot under a balanced total

0:00 / 4:21

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

  1. 1997

    Karger and colleagues introduce consistent hashing, made for relieving hot spots on the web.

  2. 2006

    Google's Bigtable paper describes tablets, ranges of rows that are the unit of spreading and balancing load.

  3. 2010

    MongoDB 1.6 calls its sharding ready for production. Work on Vitess starts at YouTube to grow MySQL.

  4. 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.

Step 1 of 3

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.

Moving fish while visitors watch
TANK 1TANK 2TANK 3Tank 1 is too full

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

ShardRecordsLoad
11,50085%
240025%
335020%
450030%
2,750 records in all. The load column is the processor use in this example.

A simple rule: more than 1.5 times the average

rˉ=27504=687.51.5 rˉ≈10311500>1031\bar r = \frac{2750}{4} = 687.5 \qquad 1.5\,\bar r \approx 1031 \qquad 1500 > 1031
Shard 1 is hot by this rule. The factor is a setting. Other teams use a difference of 30% from the average, or a size in gigabytes.

Rebalance

Split, merge, move

OperationWhenExampleData copied
SplitA partition is too large or too hot150 GB becomes 75 GB and 75 GBAbout half, if one half goes to another machine
MergeNeighbours are small and quiet5 GB and 8 GB become 13 GBThe smaller one
MoveA machine is too busy, partitions are finePartition 7 goes to machine 3The whole partition
Only neighbouring ranges can be merged. Joining keys 0 to 9 with 50 to 59 would claim everything in between.

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

Clients send traffic to a router with map version 8. Until the switch, the router uses shard 1, which holds keys 0 to 9999. Shard 1 sends a copy and then changes to new shard 5, which takes keys 5000 to 9999. After the switch the router sends those keys to shard 5.
Here the data is even, so the middle key 5000 is also the middle of the rows.

A split, step by step

Shard 1 keeps the moved rows until the new place is trusted. It refuses requests for them after the switch.

Who starts it?

AutomaticStarted by people
TriggerSize or load limitsA person or a schedule, in quiet hours
GoodLittle daily workFull control of time and speed
RiskMay move data at the worst momentForgotten until it hurts
ExamplesMongoDB balancer, CockroachDB rangesVitess Reshard workflow, self-built systems
MongoDB's balancer is on by default and starts when shards differ by at least three times the range size, which is 384 MB with the default of 128 MB. In Vitess an operator starts Reshard, compares with VDiff and then switches traffic.

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?

75 GB50 MB/s=75,000 MB50 MB/s=1,500 s=25 min\frac{75\ \text{GB}}{50\ \text{MB/s}} = \frac{75{,}000\ \text{MB}}{50\ \text{MB/s}} = 1{,}500\ \text{s} = 25\ \text{min}
50 MB/s is an assumed limit. The source must also keep serving, so the limit matters more than the wish to finish.
  1. 1

    Limit the speed

    Slow down when response times rise.

  2. 2

    One at a time

    Limit how many moves touch one machine.

  3. 3

    Start early

    At 60% full there is room to copy. At 95% the copy itself breaks things.

  4. 4

    Check

    Compare counts and checksums, and read from both for a while.

  5. 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?

Ask for the hottest keys first. The cure depends on the answer.

Hot spots

Four cures and their price

CureHowPrice
Add randomness (salting)Write post 42 as 42#0 to 42#3A read must collect all the pieces
CacheAnswer hot reads from memorySlightly old data; does not help writes
SplitCut the partition in twoUseless for one key
Better keyMore values, or one more fieldMost effective, and a full migration

One hot post, treated twice

Readers of post 42 are answered by a cache. Writers send likes to a counter service, which adds a suffix from 0 to 3, so the likes are spread over four shards as likes:42#0 to likes:42#3.
Reads stop at the cache. Likes are spread over four keys. A background job, not drawn, adds the four numbers and refreshes the cache every second.

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

A client asks a coordinator for a count. The coordinator asks four shards, which answer 1,500, 400, 350 and 500. The coordinator adds the counts.
1,500 + 400 + 350 + 500 = 2,750. Each shard counts only its own rows.
  1. 1

    Scatter

    The coordinator sends the question to all shards at once.

  2. 2

    Execute

    Each shard works on its own data.

  3. 3

    Gather

    The answers come back, some sooner, some later.

  4. 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

10×100+20×1101=1020101≈10.1not 10+202=15\frac{10 \times 100 + 20 \times 1}{101} = \frac{1020}{101} \approx 10.1 \qquad \text{not}\ \frac{10 + 20}{2} = 15
Shard A: 100 rows with average 10. Shard B: 1 row with average 20.

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

ProblemWhat happensAnswer
LatencySlowest shard plus mergingTimeouts, small fan-out, precomputed results
Sorting, pagesToo many rows are sentCursors instead of offsets
JoinsRows travel between machinesSame key for related tables, or copied fields
TransactionsSeveral machines must agreeTwo-phase commit, or a saga

Two-phase commit in one picture

After saying ready, a shard must hold its locks until it hears the decision. If the coordinator disappears, it waits. A saga avoids that wait and accepts that others see the middle.

Composite

Two keys together

Region first, then a hash of the user

The region keeps data near its users. The hash spreads each region evenly.
JavaScript
// MongoDB: a compound shard keysh.shardCollection("db.orders", { tenant_id: 1, created_at: 1 })
A query with tenant_id goes to few shards. A large tenant can be split by time. New rows of that tenant still meet at its newest range.

Two common pairs

PairGood forWatch
Tenant, then timeRanges of time inside one tenant, and splitting a large tenantThe newest range of a busy tenant
Region, then hashShort distance, even spread inside the regionRegions of different size

Single or composite?

Single keyComposite key
ComplexitySimpleHigher
Queries served wellOne kindThose that name the first part, or all parts
SpreadLimited by the key's valuesMore even, large values can be split
RebalancingSimplerMore to plan
The order of the parts matters. A query that names only the second part is a scatter query.

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. 1

    New layout

    Create shards with the new key.

  2. 2

    Write to both

    Or stream every change from old to new.

  3. 3

    Fill in history

    Copy old rows at a limited speed. Newer rows must win over the copy.

  4. 4

    Compare

    Read from both, answer from the old, log differences.

  5. 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

600016=375375+8000+400=8775>2000375+1+400=776\frac{6000}{16} = 375 \qquad 375 + 8000 + 400 = 8775 > 2000 \qquad 375 + 1 + 400 = 776
With a cache refreshed once a second, the shard sees 1 read a second for that recipe. Its 400 likes fit, so salting is not needed.

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.

Sources