Partitioning and sharding
Split a table inside one server first, then across servers; pick the key that decides which queries stay cheap, and move data without stopping writes
You shard a users table across 4 Postgres nodes with node = hash(user_id) mod 4. Traffic grows and you add a fifth node, now using mod 5. Roughly what fraction of users must move to a different node?
Everything so far in this course assumed one primary. Replication copied it; failover replaced it. Neither made it bigger. A single Postgres primary on a large cloud instance handles a lot (tens of thousands of write transactions per second, several terabytes) and most companies never outgrow one. The ones that do hit one of four walls: write throughput, data size per node, vacuum and wraparound on very large tables, or the blast radius of a single machine.
There are two tools, and you should reach for them in order. Partitioning splits a table into pieces inside one server. It costs little, fixes the vacuum and retention problems, and does nothing for write throughput. Sharding splits data across servers. It fixes all four walls and changes your application, your transactions and your operations. This chapter does both on the shop, with Postgres declarative partitioning and then Citus.
Partitioning inside one server
Declarative partitioning makes one logical table out of many physical ones. The parent holds no rows; each row is routed to the partition whose bounds contain its partition key:
CREATE TABLE orders_by_month (LIKE orders INCLUDING DEFAULTS INCLUDING CONSTRAINTS)
PARTITION BY RANGE (created_at);
CREATE TABLE orders_2026_10 PARTITION OF orders_by_month
FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
Three strategies exist. RANGE suits time and other ordered keys, LIST suits a small set of values (country, tenant tier), and HASH (MODULUS 8, REMAINDER 3) spreads rows evenly when no natural range exists.
What it buys:
- Retention for free. Dropping a month is
DROP TABLE orders_2023_11orALTER TABLE ... DETACH PARTITION ... CONCURRENTLY: a catalogue change that takes milliseconds and creates no dead tuples. The equivalentDELETEwrites a WAL record and a dead tuple per row, then needs a vacuum. - Smaller, hotter indexes. Recent partitions are small, their indexes fit in memory, and old partitions are read rarely.
- Vacuum per partition. Autovacuum works on each partition separately, so the freeze work that threatens wraparound happens in pieces, and an old partition that never changes can be frozen once and forgotten.
- Partition pruning. A query with
WHERE created_at >= '2026-10-01'skips the other partitions, at plan time for constants and at execution time for parameters and joins.EXPLAINshows the survivors, andSubplans Removed: Nfor runtime pruning.
What it costs:
- No global index. Each partition has its own indexes, so a
PRIMARY KEYorUNIQUEconstraint must include the partition key.PRIMARY KEY (id)fails;PRIMARY KEY (id, created_at)works and enforces uniqueness of the pair, not ofid. Ifidmust be unique on its own you need a sequence you trust or a separate lookup table. - Queries without the key touch every partition.
WHERE customer_id = 42on a table partitioned by month scans 36 index probes instead of one. Partitioning on the column your hot queries do not filter by makes them slower. - Planning overhead. Hundreds of partitions are fine; many thousands slow planning and lock acquisition for queries that cannot prune at plan time. Monthly partitions for ten years is 120; daily for ten years is 3650, and you will feel it.
- The default partition trap. A
DEFAULTpartition catches rows that fit no other partition. Creating a new partition then has to scan the default to prove none of its rows belong in the new range, under a lock. Pre-create partitions ahead of time (a cron job orpg_partman) and keep the default empty or absent.
Partitioning does not add a single write per second of capacity: every row still goes through one WAL, one checkpointer and one machine’s disks. For that you need more machines.
Sharding: the key decides everything
Sharding puts different rows on different servers. The shard key (Citus calls it the distribution column) decides which server holds a row, and it is the most consequential decision in the design, because it sorts every query into one of two classes:
- Queries that name one key value go to one shard. They cost what they cost on a single server, and the cluster’s capacity is the sum of its nodes.
- Queries that do not go to every shard. They cost as much as the cluster is wide, and adding nodes makes them more expensive, not less.
So you choose the key to make your most frequent and most latency-sensitive queries the first kind. For a multi-tenant SaaS that is the tenant: Notion’s workspace, Slack’s team. For the shop it is the customer: a customer’s orders, items and payments live together, and “show my orders” and “place an order” each touch one shard. The queries that lose are the ones across customers: “best-selling products this week”, “all orders shipped yesterday”. Those become fan-out queries, or move to an analytics system fed by replication.
Then you make the rest of the schema follow the key. A child table must carry the shard key so it lands on the same shard as its parent. order_items has order_id but no customer_id; sharded by customer, it needs customer_id added, and its primary key becomes (customer_id, id). Tables that every shard needs and that are small and slow-changing (products, currencies, countries) become reference tables, copied in full to every node so joins against them stay local.
A good key has high cardinality (many more values than shards), roughly even load per value, and is present in nearly every query. A bad key fails one of these: country has 30 values and one of them is 20% of the shop; created_at puts all of today’s writes on one shard; a tenant id where one tenant is half the traffic gives you one hot shard no matter how many you add.
Placement: why shards outnumber nodes
Once a row has a key, something maps the key to a server. The naive map, hash(key) mod N, works until N changes, then moves about (N-1)/N of everything. The two working answers both decouple keys from nodes.
The first is consistent hashing: nodes and keys hash onto a ring, each key belongs to the next node clockwise, and adding a node moves only the keys in the arc it takes over. With one point per node the arcs are wildly uneven; with many virtual points per node they even out. Cassandra and DynamoDB place data this way.
CONSISTENT HASHING (ring of 2^32 positions)
ADD_NODE(n): for i in 0..V-1: insert token (hash(n + "#" + i), n)
keep tokens sorted by position
LOOKUP(key): h = hash(key)
i = first token with position ≥ h (binary search)
if none: i = 0 (wrap around)
return tokens[i].node (the successor)
Adding a node: each new token takes the keys between its predecessor
token and itself, all from that token's old successor. Expected
moves: K / (N+1). Every moved key goes to the new node.
hash(key) mod N instead: going from N to N+1 nodes keeps a key only
when h mod N = h mod (N+1), so about N/(N+1) of all keys move.
One token per node: arc lengths are uneven, the largest of N arcs
is about (ln N)/N of the ring, so one node carries far more than K/N.
V tokens per node: each node's share is a sum of V arcs, and the
spread shrinks roughly like 1/√V. Run HASH MOD N and count the keys that move when E joins: nearly all of them. Run RING, 1 TOKEN PER NODE and the movement drops to about a fifth, but one node owns a third of the ring. FIX: RING + VNODES gives each node many tokens, and both load and movement come out close to fair. The exercise makes you find how many tokens it takes, and the answer, that the imbalance shrinks only with the square root of the token count, is why systems use hundreds.
At 20 tokens per node the busiest node still carries about 1.4× the average. Raise VNODES PER NODE until the busiest node is within 1.25× the average both before and after E joins. Watch how uneven the improvement is from one setting to the next.
GOAL: max load ≤ 1.25 × average, before and after E joins
The second answer, and the one relational sharding systems use, is a fixed number of virtual shards with a lookup table. Hash every key into one of S shards, where S is fixed forever and much larger than the node count, and keep a table of which node holds each shard. Citus defaults to 32 shards per table (citus.shard_count), Notion chose 480, Vitess maps keys to a 64-bit keyspace id and assigns ranges of it. Adding a node moves whole shards to it; no key ever changes shard, so there is nothing to rehash. Pick S with many divisors (480 divides evenly by 2, 3, 4, 5, 6, 8, 10, 12, 15, 16, 20, 24, 30, 32…) so it spreads evenly over many cluster sizes.
function shardFor(key, nodes) {
return nodes[hash(key) % nodes.length]; // N changes → almost every key moves
}const BUCKETS = 1024; // fixed forever
const bucketOf = (key) => hash(key) % BUCKETS;
// bucketTable: bucket -> node, stored in config (Redis Cluster slots, Couchbase vBuckets)
function shardFor(key) { return bucketTable[bucketOf(key)]; }
// add a node: move whole buckets to it, nothing else changes
// write-hot key (a counter): salt it so writes land in many buckets
const writeKey = `${key}#${rand(16)}`; // reads fan out to all 16 and sum
// read-hot key: salting does not help (every read hits all 16);
// replicate it or cache it in front: write all copies, read one Watch HASH MOD N against FIX: VIRTUAL BUCKETS: same keys, same new node, a fraction of the movement. Then run HOT KEY, where one key carries 40% of requests. Adding nodes does nothing for it, because a single key lives on a single shard, and FIX: SALT THE HOT KEY shows the only way out for a write-hot key: split it into sub-keys and pay with a fan-out on read. In a database that means a tenant too big for one shard has to be split by a second key, or moved to its own dedicated node, which Citus supports by isolating a tenant into its own shard.
Rewrite assign so adding a node moves only about 1/(N+1) of the keys, and no node gets more than 2× its share. You cannot keep a table between calls. Hash each key to one of a fixed number of virtual buckets, then give each bucket to the node with the highest hash(bucket + node) (rendezvous hashing). Adding a node only takes the buckets it now wins.
Citus: sharding inside Postgres
Citus is a Postgres extension that turns a group of Postgres servers into one database. One coordinator holds the metadata and accepts queries; workers hold the shards, each an ordinary Postgres table such as orders_102041. You talk SQL to the coordinator:
SELECT create_reference_table('products');
SELECT create_distributed_table('customers', 'id');
SELECT create_distributed_table('orders', 'customer_id', colocate_with => 'customers');
Tables distributed on the same key type with the same shard count are co-located: shard 7 of customers and shard 7 of orders cover the same hash range and live on the same worker. A join between them on the distribution key runs on each worker locally, in parallel, with no data crossing the network.
The coordinator’s planner sorts queries:
- Router queries pin one key (
WHERE customer_id = 51), go to one shard, and support everything Postgres does, including transactions and foreign keys between co-located tables. - Multi-shard queries go to every shard in parallel, and the coordinator merges results. Aggregates are pushed down where possible (each shard computes a partial
countand the coordinator sums them). Joins between non-co-located tables need data shuffled between workers, which Citus does only if you turn oncitus.enable_repartition_joins, and which is slow. - Multi-shard writes in one transaction use two-phase commit across workers, the protocol the distributed transactions chapter covers, with automatic recovery of prepared transactions left behind by a crash.
Citus constraints follow from the design. Primary keys and unique constraints must include the distribution column, the same rule as partitioning for the same reason: no global index. The customers.email unique constraint cannot survive sharding by id; you enforce it with a separate table distributed by email, or in the application. And the coordinator is a single point of failure unless you replicate it, which Citus clusters do with ordinary streaming replication and Patroni (Patroni has built-in Citus support).
Rebalancing without stopping writes
Adding a worker gives it nothing until you move shards to it. Citus’s rebalancer plans moves to even out the cluster (by disk size or by shard count) and executes them in the background:
SELECT citus_add_node('w3', 5432);
SELECT * FROM get_rebalance_table_shards_plan();
SELECT citus_rebalance_start();
SELECT state, details FROM citus_rebalance_status();
Each move is a small replication project. Citus creates the shard (and its co-located shards) on the target, copies the existing rows, then streams changes from the source with logical replication until the target is caught up. At cutover it blocks writes to that shard group briefly, applies the last changes, flips the metadata so the coordinator routes to the new node, and drops the source later. Writes see a pause of well under a second per move, not an outage. That is why the lab runs the workers with wal_level = logical, and why tables need a primary key or replica identity to be moved online.
Vitess does the same thing for MySQL with different names. VTGate routes queries using a vindex that maps a column to a keyspace id; resharding uses VReplication to copy and catch up, then switches reads, then writes, with a reverse stream kept ready so you can switch back. Notion did it by hand: dual writes from the application, a backfill, verification by comparing reads, then a cutover. Every working online migration has the same four phases: copy, catch up, verify, switch, with a way back.
What sharding takes away
Write the list down before you shard, because each item becomes application code:
- Cross-shard transactions are two-phase commits: slower, and blocking while a coordinator is down.
- Global uniqueness on anything but the shard key.
- Global sequences. Citus coordinates sequence ranges so ids do not collide, and in your own sharding you need a generator: per-shard ranges, ids that embed the shard number (Instagram’s approach), or UUIDv7.
- Consistent backups across shards. Each node’s backup is consistent with itself, not with the others. Citus can create a named restore point on all nodes at once (
citus_create_restore_point) for point-in-time recovery to the same moment. - Schema changes on N nodes. Citus propagates DDL; a home-grown setup needs a migration runner that handles one shard failing halfway.
- Operations multiply. Thirty-two primaries means thirty-two sets of replicas, failovers, vacuums and upgrades. Notion’s team spent most of its effort on the migration and the tooling, not the sharding logic.
The lab stack
labs/databases/citus.yaml is a separate compose project, atlas-citus: a coordinator coord (host port 5450) and two workers w1, w2, all citusdata/citus:14.2.0-pg17, with a third worker w3 behind the grow profile. All run with wal_level=logical, and trust authentication inside the compose network so the coordinator can reach workers without passwords. The shop’s own db from compose.yaml stays up as the data source for the partitioning steps and for loading Citus.
P> is psql on the shop (docker compose exec db psql -U atlas shop); C> is psql on the Citus coordinator (docker compose -f citus.yaml exec coord psql -U atlas shop).
1. Partition orders by month and watch pruning.
P> CREATE TABLE orders_by_month (LIKE orders INCLUDING DEFAULTS INCLUDING CONSTRAINTS)
PARTITION BY RANGE (created_at);
P> ALTER TABLE orders_by_month ADD PRIMARY KEY (id);
P> ALTER TABLE orders_by_month ADD PRIMARY KEY (id, created_at);
P> DO $$
DECLARE m date;
BEGIN
FOR m IN SELECT generate_series(date '2023-11-01', date '2026-10-01', interval '1 month')::date LOOP
EXECUTE format('CREATE TABLE orders_%s PARTITION OF orders_by_month FOR VALUES FROM (%L) TO (%L)',
to_char(m, 'YYYY_MM'), m, (m + interval '1 month')::date);
END LOOP;
END $$;
P> INSERT INTO orders_by_month SELECT * FROM orders;
P> ANALYZE orders_by_month;
P> EXPLAIN (COSTS OFF) SELECT count(*) FROM orders_by_month WHERE created_at >= '2026-10-01';
P> EXPLAIN (COSTS OFF) SELECT * FROM orders_by_month WHERE id = 4242;ADD PRIMARY KEY (id) fails with unique constraint on partitioned table must include all partitioning columns. The second succeeds. The loop creates 36 partitions and the insert routes 200 000 rows into them. The first plan scans only orders_2026_10: pruning at plan time. The second plan has 36 index scans under an Append, one per partition, because id alone says nothing about which month the row is in.2. Drop a month the cheap way.
P> \timing on
P> SELECT count(*) FROM orders_2023_11;
P> ALTER TABLE orders_by_month DETACH PARTITION orders_2023_11 CONCURRENTLY;
P> DROP TABLE orders_2023_11;
P> BEGIN; DELETE FROM orders_by_month WHERE created_at < '2024-01-01'; ROLLBACK;
P> DROP TABLE orders_by_month;DELETE of the next month (rolled back) takes tens to hundreds of milliseconds at this scale and would leave a dead tuple per row; at scale 1 or on a real table it is seconds to hours. DETACH ... CONCURRENTLY cannot run inside a transaction block, which is why it is on its own line.3. Start Citus and register the nodes.
docker compose -f citus.yaml up -d
docker compose -f citus.yaml psC> SELECT citus_set_coordinator_host('coord', 5432);
C> SELECT citus_add_node('w1', 5432);
C> SELECT citus_add_node('w2', 5432);
C> SELECT nodename, nodeport, noderole FROM pg_dist_node ORDER BY nodeid;citus_add_node returns a node id. pg_dist_node lists coord, w1 and w2, all primary; the coordinator has group 0 and holds no shards by default.4. Create the schema and hit the key rule.
C> CREATE TABLE products (id bigint PRIMARY KEY, sku text NOT NULL UNIQUE, name text NOT NULL,
category text NOT NULL, price_cents int NOT NULL, created_at timestamptz NOT NULL);
C> CREATE TABLE customers (id bigint PRIMARY KEY, email text NOT NULL, name text NOT NULL,
country char(2) NOT NULL, created_at timestamptz NOT NULL);
C> CREATE TABLE orders (id bigint PRIMARY KEY, customer_id bigint NOT NULL, status text NOT NULL,
total_cents int NOT NULL, created_at timestamptz NOT NULL, shipped_at timestamptz);
C> SELECT create_reference_table('products');
C> SELECT create_distributed_table('customers', 'id');
C> SELECT create_distributed_table('orders', 'customer_id', colocate_with => 'customers');
C> ALTER TABLE orders DROP CONSTRAINT orders_pkey, ADD PRIMARY KEY (customer_id, id);
C> SELECT create_distributed_table('orders', 'customer_id', colocate_with => 'customers');
C> CREATE TABLE order_items (customer_id bigint NOT NULL, id bigint NOT NULL, order_id bigint NOT NULL,
product_id bigint NOT NULL, qty int NOT NULL, unit_price_cents int NOT NULL, PRIMARY KEY (customer_id, id));
C> SELECT create_distributed_table('order_items', 'customer_id', colocate_with => 'orders');
C> SELECT table_name, nodename, count(*) FROM citus_shards GROUP BY 1, 2 ORDER BY 1, 2;orders fails: distributed relations cannot have UNIQUE, EXCLUDE or PRIMARY KEY constraints that do not include the partition column. The same rule as step 1, for the same reason. With (customer_id, id) it succeeds. citus_shards shows 16 shards of each distributed table on each worker (32 in all, the default) and one shard of products on every node.5. Load the shop into the cluster.
Copy each table from the shop. order_items picks up customer_id from its order on the way:
for t in products customers orders; do
docker compose exec -T db psql -U atlas shop -c "\copy $t TO STDOUT" \
| docker compose -f citus.yaml exec -T coord psql -U atlas shop -c "\copy $t FROM STDIN"
done
docker compose exec -T db psql -U atlas shop -c "\copy (SELECT o.customer_id, i.id, i.order_id, i.product_id, i.qty, i.unit_price_cents FROM order_items i JOIN orders o ON o.id = i.order_id) TO STDOUT" \
| docker compose -f citus.yaml exec -T coord psql -U atlas shop -c "\copy order_items FROM STDIN"C> SELECT count(*) FROM orders;
C> EXPLAIN SELECT * FROM orders WHERE customer_id = 51;
C> EXPLAIN SELECT count(*) FROM orders WHERE status = 'paid';
C> \timing on
C> SELECT o.id, sum(i.qty * i.unit_price_cents) FROM orders o JOIN order_items i
ON i.customer_id = o.customer_id AND i.order_id = o.id
WHERE o.customer_id = 51 GROUP BY o.id ORDER BY o.id LIMIT 5;
C> SELECT p.category, sum(i.qty) FROM order_items i JOIN products p ON p.id = i.product_id
GROUP BY 1 ORDER BY 2 DESC LIMIT 3;COPY counts match the shop: 5000 products, 50 000 customers, 200 000 orders, about 600 000 items. The first plan is a Custom Scan (Citus Adaptive) with Task Count: 1 and one Node: host=w1 or w2: a router query. The second shows Task Count: 32: every shard, in parallel. The customer join runs in a few milliseconds on one worker; the category report fans out to 32 shards, each joining against its local copy of products.6. Add a worker and rebalance under load.
In terminal 2, start a write load of new orders across all customers:
docker compose -f citus.yaml exec coord bash -c "cat > /tmp/w.sql <<'SQL'
\set c random(1, 50000)
\set id random(10000000, 2000000000)
INSERT INTO orders VALUES (:id, :c, 'placed', 1000, now(), NULL);
SQL
pgbench -U atlas -n -c 4 -T 180 -P 5 -f /tmp/w.sql shop"In terminal 1:
docker compose -f citus.yaml --profile grow up -d w3C> SELECT citus_add_node('w3', 5432);
C> SELECT * FROM get_rebalance_table_shards_plan();
C> SELECT citus_rebalance_start();
C> SELECT state, details->'tasks' AS tasks FROM citus_rebalance_status();
C> SELECT citus_rebalance_wait();
C> SELECT nodename, count(*) FROM citus_shards WHERE table_name = 'orders'::regclass GROUP BY 1 ORDER BY 1;w1 and w2 to w3, one row per shard per co-located table (orders, customers and order_items shards move together). The rebalance runs in the background and citus_rebalance_status reports running, then finished. pgbench keeps printing a few hundred to a few thousand tps every 5 seconds, with short dips as each shard group cuts over, and normally no failed client. Afterwards orders is spread roughly a third per worker; the exact counts depend on the rebalance strategy’s view of shard sizes.CREATE TABLE items_by_order (LIKE order_items, PRIMARY KEY (order_id, id));, distribute it with create_distributed_table('items_by_order', 'order_id', colocate_with => 'none'), copy the rows in with INSERT INTO items_by_order SELECT * FROM order_items, and run the step 5 customer join against it with ON i.order_id = o.id. Citus refuses: the tables are not co-located and the join is not on both distribution columns. SET citus.enable_repartition_joins = on; and re-run: it works, through a repartition that shuffles rows between workers, and takes orders of magnitude longer than the co-located version. That gap is what a wrong shard key costs on every query that crosses it. Tear down with docker compose -f citus.yaml down -v.The shop's single Postgres primary is at 70% CPU at peak with 8000 write transactions per second, 3 TB of data, orders growing 60% a year. Autovacuum on order_items runs for 20 hours. Ninety per cent of queries filter by customer; the merchandising team runs hourly cross-customer reports on the same database. What do you do in the next six months?
- BOOK Designing Data-Intensive Applications, chapter 6: Partitioning Martin Kleppmann, 2017
Key-range against hash partitioning, skew and hot spots, secondary indexes in a partitioned system, and rebalancing strategies, including why mod N is wrong. The vocabulary this chapter uses. Read: the whole chapter; it is short.
- POST Sharding Postgres at Notion Garrett Fidalgo, 2021
The incident in the Why from the inside: why they sharded, how they chose 480 shards and the workspace key, and how they migrated with dual writes and verification. The part on choosing a shard count is worth copying.
- DOC Citus documentation: Concepts
Coordinator and workers, distributed, reference and local tables, shards, co-location and query execution, in one page. Then read 'Choosing Distribution Column' in the same docs before you pick a key.
- DOC Vitess documentation: Concepts
The MySQL counterpart: keyspaces, keyspace ids, shards, VTGate and the topology service. Read Keyspace ID and Shard to see the fixed-virtual-shard idea under different names, and MoveTables for online data movement.
- DOC PostgreSQL 17: Table Partitioning
Declarative partitioning, pruning, limitations and best practices, including the guidance on partition counts and the cost of a default partition. Section 5.12.6 on best practices is the part to reread.
- PAPER Consistent Hashing and Random Trees Karger, Lehman, Leighton, Panigrahy, Levine, Lewin, 1997
The paper that introduced consistent hashing, for web caches. Read it for the ring and the virtual-copies argument; skip the random-trees half. Read: sections 1 and 4.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.