skip to content

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.

shard key =
map =
shards =
4
load =
busiest / average: 1.11×add shard 5: 392 of 500 users move (79% of events)

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.

the busiest shardthe average shard
model: shard placement is this figure's arithmetic; per-user event counts and hashint4 values are real output from the events dataset
500 users of the events dataset on n shards. pick a key and a map, then switch the load to last week's writes. the line marks the average shard; the busiest lights up when it's well above. the chip shows who moves when a shard is added.

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:

sqldb=events
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;
output, from postgres 18.6
SELECT 4
shardint4usersint8eventsint8
01215920
11235480
21256644
31316956
(4 rows)
sqldb=events
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;
output, from postgres 18.6
SELECT 3
user_idint4eventsint8pctnumeric
111344.5
24601.8
33851.5
(3 rows)

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

predict the output
a SaaS app shards by tenant_id. the dashboard query is: total revenue across all tenants for today. how many shards does it touch?
sql
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.

query =
  1. EXPLAIN (VERBOSE, COSTS OFF)
  2. SELECT count(*) FROM ev WHERE user_id = 17;
QUERY PLAN
  1. Aggregate
  2. Output: count(*)
  3. -> Foreign Scan on public.ev_shard1 ev
  4. 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.

real output, a postgres 18.6 server · fdw-shards
EXPLAIN (VERBOSE) of four queries on the sharded table. each Foreign Scan prints the Remote SQL it sends to its shard. with the shard key, one shard gets the query; without it, both do; and only a GROUP BY on the shard key lets each shard aggregate on its own.

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.

where a join can run, depending on how its two tables are placed. 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.