sharding
one table across many machines. shard keys, hot shards, and the query that has to ask everyone.
- address
- everything.scale.sharding
- part
- part 17, scale and distribution
- chapter
- chapter 5 of 10
- reading time
- 7 min
sharding splits one table's rows across several independent databases, by a shard key. a query that names the key goes to one shard; a query that doesn't goes to all of them and gets merged. the key decides everything: an even spread of load (or a hot shard), which joins stay local, and how painful it is to add a machine later.
the picture
you know how partitioning splits a table into pieces on one server? sharding is the same split with each piece on its own server, so the pieces stop sharing a CPU, a disk and a WAL. that's how writes scale past one machine, and it's also where every query starts needing a map.
think of a library that outgrew its building and moved into four branches (the shards). books are shelved by the author's surname (the shard key). ask for one author, and you know which branch to call. ask "every book published in 1999" and you're calling all four.
hashing spreads users evenly, but not their activity: user 1 alone has 1,134 events, and their shard carries all of them. and changing n reshuffles most users.
picking a shard key
a good shard key is one that almost every query includes, that spreads both data and traffic, and that keeps rows queried together on the same shard. three common shapes:
- hash of an id: even data, no range queries across shards, and every user's rows together. what most systems default to.
- range of an id or a name: neighbours stay together, so range scans hit one shard. skew lands wherever the busy ranges are.
- range of time: wonderful for retention, terrible for writes. every insert goes to the newest shard.
the events dataset makes the skew real. hashing spreads users evenly, but users aren't equally busy:
SELECT ((hashint4(user_id) % 4) + 4) % 4 AS shard,
count(DISTINCT user_id) AS users,
count(*) AS events
FROM events
GROUP BY 1
ORDER BY 1;| shardint4 | usersint8 | eventsint8 |
|---|---|---|
| 0 | 121 | 5920 |
| 1 | 123 | 5480 |
| 2 | 125 | 6644 |
| 3 | 131 | 6956 |
SELECT user_id, count(*) AS events, round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct
FROM events
GROUP BY user_id
ORDER BY events DESC, user_id
LIMIT 3;| user_idint4 | eventsint8 | pctnumeric |
|---|---|---|
| 1 | 1134 | 4.5 |
| 2 | 460 | 1.8 |
| 3 | 385 | 1.5 |
one user owns more than 4% of all events. no hash can split one key across shards, so that user's shard carries all of it. a hot key like that (a celebrity account, a big tenant) needs special handling: its own shard, or a key that splits it (user plus day).
SELECT sum(amount) FROM invoices WHERE created_at >= current_date;asking one shard, or all of them
postgres can do a small version of this with postgres_fdw: a partitioned table whose partitions are foreign tables on other servers. here the "servers" are two schemas reached over a loopback connection, so the plans are real and the network is pretend. ev_shard1 holds 13,531 events of 268 users, ev_shard2 holds 11,469 events of 232 users.
- EXPLAIN (VERBOSE, COSTS OFF)
- SELECT count(*) FROM ev WHERE user_id = 17;
- Aggregate
- Output: count(*)
- -> Foreign Scan on public.ev_shard1 ev
- Remote SQL: SELECT NULL FROM s1.events WHERE ((user_id = 17))
a query with the shard key goes to one shard, and the WHERE travels with it.
the last one is the honest surprise: a total across shards still ships every matching row back to be counted, because postgres_fdw doesn't push partial aggregates down to the remote side. purpose-built systems do (citus sends each worker the partial aggregate and combines the results), which is a big part of why they exist.
joins across shards
a join is cheap when both sides live on the same shard. so sharded schemas get designed around it:
hover a stage.
the same goes for constraints. a unique index or a foreign key is enforced inside one database; across shards, uniqueness only holds when the key includes the shard key (exactly the partitioning rule, for the same reason), and a transaction that writes to two shards needs two-phase commit to be atomic.
resharding
shards fill up, and you add one. with hash mod n, changing n changes almost every key's shard: going from 4 to 5 moves about 4 keys in 5. so real systems don't map keys to shards directly. they hash into a fixed, larger number of slots (or ranges, or a consistent-hashing ring) and move whole slots between machines, so adding a shard moves only its fair share. try both maps in the figure. the move itself is a copy plus catching up on changes made during the copy, often with logical replication, then a short pause to switch the map.
keylines
- sharding = partitions on separate machines, chosen by a shard key.
- queries with the key hit one shard; without it, all of them (scatter, gather).
- hash spreads keys, not load: hot keys stay hot.
- co-locate tables that join; copy small reference tables everywhere.
- map keys to many slots, not mod n, so resharding moves little.