Part 1 · Declarative partitioning: range, list and hash
One big table, several small ones
A ride app records every trip, and a few years in, the trips table holds several crore rows. Most queries ask about this week or this city, yet every index and every vacuum has to deal with the whole table.
Partitioning splits one logical table into several physical pieces, called partitions, inside the same database server. You still write SELECT and INSERT against the one table name. PostgreSQL decides which piece holds a row when it is written and which pieces to read when it is queried. This is called declarative partitioning, because you declare the rule and the server applies it.
The PostgreSQL documentation is careful about when this pays off. It says the benefits are normally worthwhile only when a table would otherwise be very large, and gives a rule of thumb that the table should be bigger than the physical memory of the server. It also names a second benefit that has nothing to do with queries: dropping a partition with DROP TABLE, or detaching one, is far faster than a bulk DELETE, and it avoids the vacuum work that a big delete leaves behind. Keeping the last 18 months of trips and discarding older months becomes one cheap command.
Partitioning is not the same as sharding. Every partition here lives on one server, uses its memory and its disk, and is protected by the same write-ahead log. Sharding, which starts in the third lesson, puts the pieces on different servers. Partitioning makes one server cope with a big table; sharding spreads a table past what one server can hold.
Three ways to split
Every partitioned table has a partition key: the column, or columns, whose value decides the partition. PostgreSQL offers three methods.
Method
The rule
Typical key
Typical use
Range
Each partition takes a span of values, from an inclusive lower bound to an exclusive upper bound
A date
Time series and logs, where old months are dropped
List
Each partition lists the values it holds
A city or a country code
Data that is read and managed by a known category
Hash
Each partition takes the rows whose hash of the key has a given remainder after dividing by a modulus
An identifier such as a rider id
Spreading rows evenly when no natural range or list exists
Range
The ruleEach partition takes a span of values, from an inclusive lower bound to an exclusive upper bound
Typical keyA date
Typical useTime series and logs, where old months are dropped
List
The ruleEach partition lists the values it holds
Typical keyA city or a country code
Typical useData that is read and managed by a known category
Hash
The ruleEach partition takes the rows whose hash of the key has a given remainder after dividing by a modulus
Typical keyAn identifier such as a rider id
Typical useSpreading rows evenly when no natural range or list exists
The range rule is worth reading twice. The documentation says each range's bounds are inclusive at the lower end and exclusive at the upper end, so one partition can end where the next begins without any value being counted twice. A month partition for February runs FROM ('2026-02-01') TO ('2026-03-01'), and a trip on 1 March belongs to the March partition.
A hash partition is declared with a modulus and a remainder. With a modulus of 3 you create three partitions, with remainders 0, 1 and 2, and every row goes to exactly one of them. Hashing balances the partitions in the long run, but it destroys order: neighbouring rider ids land in different partitions, so a range of riders is spread across all of them.
Each partition is a table of its own with the same columns as the parent, and the next lessons use that fact when they attach and detach partitions. A row that matches no partition is rejected unless you also create a default partition to catch everything else.
Pruning in a real plan
Splitting a table only helps queries that can skip partitions. The planner does this by comparing the query's WHERE clause with each partition's bounds, and leaving out any partition that cannot hold a matching row. This is partition pruning. The documentation adds that pruning is driven only by the constraints that the partition key implies, never by the presence of indexes, and that it depends on enable_partition_pruning, which is on by default.
The first run creates a trips table partitioned by month, loads 300 invented trips spread over January to March 2026, and counts rows per partition. Results are printed with the helper from the SQL chapter, and the plans are printed by a small plan function that runs EXPLAIN (COSTS OFF) and wraps long lines at 72 columns so that they fit on this page.
ts
exportasyncfunction plan(
db: PGlite,
sql: string,
params: unknown[] = []
) {
for (const l of wrap(`EXPLAIN ${sql.replace(/\s+/g, ' ')}`))
console.log(l)
const r = await db.query<{ 'QUERY PLAN': string }>(
`EXPLAIN (COSTS OFF) ${sql}`,
params
)
for (const row of r.rows)
for (const l of wrap(row['QUERY PLAN'])) console.log(l)
}
ts
const db = new PGlite()
console.log(
(
await db.query<{ v: string }>('SELECT version() AS v')
).rows[0].v.split(' on ')[0]
)
await db.exec(`
CREATETABLE trips (
trip_id bigint NOT NULL,
rider_id int NOT NULL,
city text NOT NULL,
trip_date date NOT NULL,
fare numeric(8,2) NOT NULL
) PARTITION BY RANGE (trip_date);
CREATETABLE trips_2026_01 PARTITION OF trips FOR VALUES
FROM ('2026-01-01') TO ('2026-02-01');
CREATETABLE trips_2026_02 PARTITION OF trips FOR VALUES
FROM ('2026-02-01') TO ('2026-03-01');
CREATETABLE trips_2026_03 PARTITION OF trips FOR VALUES
FROM ('2026-03-01') TO ('2026-04-01');
INSERT INTO trips (trip_id, rider_id, city, trip_date, fare)
SELECT i, 1 + (i * 7) % 50,
(ARRAY['Pune','Chennai','Jaipur'])[1 + i % 3],
DATE '2026-01-01' + (i % 90),
50 + (i * 13) % 400FROM generate_series(1, 300) AS i;
`)
Now the same table is asked two questions. The first filters on the partition key, the second on a column that is not the key.
ts
console.log('-- pruning on the range key')
await plan(
db,
`SELECT count(*) FROM trips WHERE trip_date >= '2026-02-01'
AND trip_date < '2026-03-01'`
)
console.log('-- no condition on the partition key')
await plan(db, `SELECT count(*) FROM trips WHERE city = 'Pune'`)
console.log('-- a value that fits no partition')
try {
await db.query(
`INSERT INTO trips (trip_id, rider_id, city, trip_date, fare)
VALUES (1000, 1, 'Pune', '2026-07-01', 90)`
)
} catch (e) {
const x = e as { message: string }
console.log('ERROR ' + x.message)
}
text
EXPLAIN SELECT count(*) FROM trips WHERE trip_date >= '2026-02-01' AND
trip_date < '2026-03-01'
Aggregate
-> Seq Scan on trips_2026_02 trips
Filter: ((trip_date >= '2026-02-01'::date) AND (trip_date <
'2026-03-01'::date))
-- no condition on the partition key
EXPLAIN SELECT count(*) FROM trips WHERE city = 'Pune'
Aggregate
-> Append
-> Seq Scan on trips_2026_01 trips_1
Filter: (city = 'Pune'::text)
-> Seq Scan on trips_2026_02 trips_2
Filter: (city = 'Pune'::text)
-> Seq Scan on trips_2026_03 trips_3
Filter: (city = 'Pune'::text)
-- a value that fits no partition
ERROR no partition of relation "trips" found for row
The February query reads one partition, trips_2026_02, and the plan does not mention the other two. The query on city has no condition the planner can use against the date bounds, so it appends all three partitions and filters each one. The same count over the same table costs three scans instead of one purely because of what the WHERE clause names. The last statement shows a value that fits no partition: the insert for July fails with no partition of relation "trips" found for row, which is the signal that a new partition must be created before that month arrives.
List and hash partitions
List partitioning follows the same pattern with a different rule. This run creates a table split by city, with a partition for Pune, one for Chennai and Bengaluru together, and a default partition for the rest. The 300 trips are copied in, and the counts show where each landed.
ts
// list partitionsawait db.exec(`
CREATETABLE trips_by_city (
trip_id bigint NOT NULL, rider_id int NOT NULL, city text NOT NULL,
fare numeric(8,2) NOT NULL
) PARTITION BY LIST (city);
CREATETABLE trips_pune PARTITION OF trips_by_city FOR
VALUES IN ('Pune');
CREATETABLE trips_south PARTITION OF trips_by_city FOR
VALUES IN ('Chennai', 'Bengaluru');
CREATETABLE trips_other PARTITION OF trips_by_city DEFAULT;
INSERT INTO trips_by_city (trip_id, rider_id, city, fare)
SELECT trip_id, rider_id, city, fare FROM trips;
`)
console.log('-- list partitions, with a default partition')
show(
(
await db.query(
`SELECT tableoid::regclass::text AS partition, count(*) AS trips
FROM trips_by_city GROUP BY tableoid ORDER BY 1`
)
).rows
)
await plan(
db,
`SELECT count(*) FROM trips_by_city WHERE city = 'Chennai'`
)
text
partition | trips
------------+------
trips_other | 100
trips_pune | 100
trips_south | 100
(3 rows)
EXPLAIN SELECT count(*) FROM trips_by_city WHERE city = 'Chennai'
Aggregate
-> Seq Scan on trips_south trips_by_city
Filter: (city = 'Chennai'::text)
Jaipur trips went to the default partition because no list names Jaipur, and trips_south holds only Chennai trips because this data has no Bengaluru trips. A query for Chennai reads only trips_south. A default partition is a safety net, not a place to leave data for long: when a city gets its own partition later, rows already in the default partition that belong to it have to be moved out.
Hash partitioning needs only a modulus and a remainder per partition.
ts
// hash partitionsawait db.exec(`
CREATETABLE trips_by_rider (
trip_id bigint NOT NULL, rider_id int NOT NULL, city text NOT NULL,
fare numeric(8,2) NOT NULL
) PARTITION BY HASH (rider_id);
CREATETABLE trips_h0 PARTITION OF trips_by_rider FOR
VALUES WITH (MODULUS 3, REMAINDER 0);
CREATETABLE trips_h1 PARTITION OF trips_by_rider FOR
VALUES WITH (MODULUS 3, REMAINDER 1);
CREATETABLE trips_h2 PARTITION OF trips_by_rider FOR
VALUES WITH (MODULUS 3, REMAINDER 2);
INSERT INTO trips_by_rider (trip_id, rider_id, city, fare)
SELECT trip_id, rider_id, city, fare FROM trips;
`)
console.log('-- hash partitions')
show(
(
await db.query(
`SELECT tableoid::regclass::text AS partition, count(*) AS trips
FROM trips_by_rider GROUP BY tableoid ORDER BY 1`
)
).rows
)
ts
await plan(
db,
`SELECT count(*) FROM trips_by_rider WHERE rider_id = 42`
)
await plan(
db,
`SELECT count(*) FROM trips_by_rider WHERE rider_id > 40`
)
await db.close()
text
partition | trips
----------+------
trips_h0 | 108
trips_h1 | 78
trips_h2 | 114
(3 rows)
EXPLAIN SELECT count(*) FROM trips_by_rider WHERE rider_id = 42
Aggregate
-> Seq Scan on trips_h0 trips_by_rider
Filter: (rider_id = 42)
EXPLAIN SELECT count(*) FROM trips_by_rider WHERE rider_id > 40
Aggregate
-> Append
-> Seq Scan on trips_h0 trips_by_rider_1
Filter: (rider_id > 40)
-> Seq Scan on trips_h1 trips_by_rider_2
Filter: (rider_id > 40)
-> Seq Scan on trips_h2 trips_by_rider_3
Filter: (rider_id > 40)
Equality on the hash key prunes to one partition, because PostgreSQL can compute the hash of 42 and know its remainder. A range condition, rider_id > 40, cannot be answered from remainders, so every partition is read. The row counts, 108, 78 and 114, are not equal: with only 300 rows and 50 riders the hash cannot balance perfectly, and it improves as the data grows. Notice what each method gave up. Range keeps order but lets one hot month hold all the writes. List groups by meaning but depends on a list you maintain. Hash spreads load but answers only equality questions well.
Check yourself
A query filters trips on city = 'Pune', but the table is range-partitioned by trip_date. How many partitions does it read, and why?
All of them: the condition is not on the partition key, so no partition can be ruled out.
The run showed an Append of all three monthly partitions, each with the filter applied.
Why does rider_id = 42 prune a hash-partitioned table to one partition while rider_id > 40 does not?
The hash of 42 gives one remainder, so one partition can hold it.
A range of ids has members in every remainder, so every partition must be read.
What happens when you insert a row that no partition accepts, and how can a default partition change that?
Without a default partition the insert fails with no partition of relation found for row.
A default partition accepts the row, but rows left there have to be moved if a matching partition is created later.
Part 2 · Living with partitions: attach, detach, retention and unique keys
The monthly routine
A partitioned table is not a set-and-forget design. New months need partitions before data arrives, and old months need to leave. Two commands do most of the work: ATTACH PARTITION adds an existing table as a partition, and DETACH PARTITION turns a partition back into an ordinary table.
Attaching has a cost to plan for. The documentation says ATTACH PARTITION takes only a SHARE UPDATE EXCLUSIVE lock on the partitioned table, which does not block normal reads and writes the way CREATE TABLE ... PARTITION OF does. But the table being attached is scanned to check that every row fits the new partition's bounds, and that scan holds an ACCESS EXCLUSIVE lock on the table being attached. The reference page for ALTER TABLE explains how to avoid the scan: add a valid CHECK constraint that allows only rows in the partition's range before you attach, and PostgreSQL uses it to prove the rows fit. The documentation recommends dropping the redundant constraint afterwards.
So the safe monthly routine is to create the next month's table on its own, load it, add the matching CHECK, attach it, and drop the CHECK. Readers of the parent table are not held up while the data is being loaded, because the table is not yet part of the parent.
Detaching and dropping
Retention is the reverse. A plain DETACH PARTITION needs an ACCESS EXCLUSIVE lock on the parent, which blocks every query on the table for the duration. The CONCURRENTLY form needs only SHARE UPDATE EXCLUSIVE on the parent. The ALTER TABLE page describes how: it uses two transactions internally, waits for other transactions that use the parent to finish in between, and then completes. It adds two restrictions: CONCURRENTLY cannot run in a transaction block, and it is not allowed if the table has a default partition. If a concurrent detach is cancelled halfway, DETACH PARTITION ... FINALIZE completes it, and only one partition per table can be pending detach at a time.
After a detach the old month is an ordinary table that still holds its rows. You can archive it, export it, or drop it. Dropping is the cheap delete the first lesson promised: no row-by-row work and no dead tuples for vacuum to clean. The partitioning page adds that a DROP TABLE on a partition takes an ACCESS EXCLUSIVE lock on the parent, so the retention routine is a concurrent detach first and a drop of the detached table second.
The unique key rule
Uniqueness is where partitioning bites. The documentation says that a unique or primary key constraint on a partitioned table must include all the partition key columns, and must not use expressions or function calls in the key. The documentation also gives the reason: the individual indexes that make up the constraint can only enforce uniqueness within their own partitions, so the partition structure itself has to guarantee that there are no duplicates in different partitions. Requiring the partition key in the constraint means two rows with the same key value always land in the same partition, where one index can catch the duplicate.
The consequence matters for design. With trips partitioned by date, trip_id alone cannot be the primary key. The key has to be (trip_id, trip_date), and that pair does not stop the same trip_id appearing on two different dates. The application, or an id generator that never repeats, must supply that guarantee.
The whole routine in one run
The script below loads two months of trips, then walks through each step: the failing primary key, the working one, the duplicate id that the pair allows, attaching a prepared March table, an attach that fails because a row is out of range, detaching concurrently inside and outside a transaction, and finally dropping the old month.
ts
const db = new PGlite()
const err = (e: unknown) => {
const x = e as { code?: string; message: string }
return`ERROR ${x.code} ${x.message}`
}
const count = async () =>
show(
(
await db.query(
`SELECT tableoid::regclass::text AS partition, count(*) AS trips
FROM trips GROUP BY tableoid ORDER BY 1`
)
).rows
)
await db.exec(`
CREATETABLE trips (
trip_id bigint NOT NULL, rider_id int NOT NULL, city text NOT NULL,
trip_date date NOT NULL, fare numeric(8,2) NOT NULL
) PARTITION BY RANGE (trip_date);
CREATETABLE trips_2026_01 PARTITION OF trips FOR VALUES
FROM ('2026-01-01') TO ('2026-02-01');
CREATETABLE trips_2026_02 PARTITION OF trips FOR VALUES
FROM ('2026-02-01') TO ('2026-03-01');
INSERT INTO trips (trip_id, rider_id, city, trip_date, fare)
SELECT i, 1 + (i * 7) % 50,
(ARRAY['Pune','Chennai','Jaipur'])[1 + i % 3],
DATE '2026-01-01' + (i % 59), 50 + (i * 13) % 400FROM generate_series(1, 200) AS i;`)
ts
console.log('-- unique key without the partition key')
try {
await db.exec('ALTER TABLE trips ADD PRIMARY KEY (trip_id)')
} catch (e) {
console.log(err(e))
}
console.log('-- unique key with the partition key')
await db.exec('ALTER TABLE trips ADD PRIMARY KEY (trip_id, trip_date)')
console.log('PRIMARY KEY (trip_id, trip_date) added')
console.log(
'-- what that key does not stop: trip_id 1 again, on another date'
)
await db.query(`INSERT INTO trips
(trip_id, rider_id, city, trip_date, fare)
VALUES (1, 9, 'Pune', '2026-02-20', 75)`)
show(
(
await db.query(
`SELECT trip_id, trip_date::text AS trip_date FROM trips
WHERE trip_id = 1 ORDER BY trip_date`
)
).rows
)
text
ERROR 0A000 unique constraint on partitioned table must include all
partitioning columns
-- unique key with the partition key
PRIMARY KEY (trip_id, trip_date) added
-- what that key does not stop: trip_id 1 again, on another date
trip_id | trip_date
--------+-----------
1 | 2026-01-021 | 2026-02-20
(2 rows)
The first error is the unique rule in action: unique constraint on partitioned table must include all partitioning columns. Adding trip_date to the key works, and the two-row result shows trip id 1 on 2 January and again on 20 February, both accepted. The dates print without a time because the column is date.
ts
console.log('-- load a new month on its own, then attach it')
await db.exec(`
CREATETABLE trips_2026_03 (LIKE trips INCLUDING DEFAULTS
INCLUDING CONSTRAINTS);
INSERT INTO trips_2026_03 (trip_id, rider_id, city, trip_date, fare)
SELECT1000 + i, 1 + i % 50, 'Pune', DATE '2026-03-01' + (i % 31),
80FROM generate_series(1, 20) AS i;
ALTER TABLE trips_2026_03 ADD CONSTRAINT trips_2026_03_range
CHECK (trip_date >= DATE '2026-03-01'
AND trip_date < DATE '2026-04-01');
ALTER TABLE trips ATTACH PARTITION trips_2026_03
FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');
ALTER TABLE trips_2026_03 DROP CONSTRAINT trips_2026_03_range;`)
await count()
ts
console.log('-- attach a table holding a row outside its range')
await db.exec(
`CREATETABLE trips_2026_04 (LIKE trips INCLUDING DEFAULTS
INCLUDING CONSTRAINTS)`
)
await db.query(
`INSERT INTO trips_2026_04 (trip_id, rider_id, city, trip_date,
fare) VALUES (2000, 3, 'Pune', '2026-05-02', 60)`
)
try {
await db.exec(
`ALTER TABLE trips ATTACH PARTITION trips_2026_04 FOR VALUES
FROM ('2026-04-01') TO ('2026-05-01')`
)
} catch (e) {
console.log(err(e))
}
ts
console.log('-- DETACH CONCURRENTLY inside a transaction block')
await db.exec('BEGIN')
try {
await db.exec(
'ALTER TABLE trips DETACH PARTITION trips_2026_01 CONCURRENTLY'
)
} catch (e) {
console.log(err(e))
}
await db.exec('ROLLBACK')
console.log('-- DETACH CONCURRENTLY on its own')
await db.exec(
'ALTER TABLE trips DETACH PARTITION trips_2026_01 CONCURRENTLY'
)
await count()
console.log(
'-- the detached table is an ordinary table that still holds its rows'
)
show(
(await db.query(`SELECT count(*) AS rows FROM trips_2026_01`)).rows
)
console.log('-- retention: drop it')
await db.exec('DROP TABLE trips_2026_01')
await count()
await db.close()
text
partition | trips
--------------+------
trips_2026_01 | 116
trips_2026_02 | 85
trips_2026_03 | 20
(3 rows)
-- attach a table holding a row outside its range
ERROR 23514 partition constraint of relation "trips_2026_04" is violated
by some row
-- DETACH CONCURRENTLY inside a transaction block
ERROR 25001 ALTER TABLE ... DETACH CONCURRENTLY cannot run inside a
transaction block
-- DETACH CONCURRENTLY on its own
partition | trips
--------------+------
trips_2026_02 | 85
trips_2026_03 | 20
(2 rows)
-- the detached table is an ordinary table that still holds its rows
rows
----
116
(1 row)
-- retention: drop it
partition | trips
--------------+------
trips_2026_02 | 85
trips_2026_03 | 20
(2 rows)
The attach of trips_2026_03 succeeded, and the counts show its 20 rows now belong to the parent. The attach of trips_2026_04 failed with SQLSTATE 23514, partition constraint of relation "trips_2026_04" is violated by some row, because one of its rows has a May date. PostgreSQL refuses to put the table in the tree rather than hold a row that its own bounds exclude. The concurrent detach inside a transaction failed with SQLSTATE 25001 and the message cannot run inside a transaction block; run on its own it worked, the 116 January rows stayed in the detached table, and DROP TABLE finished the retention step. On this machine all of this ran on a tiny table, so the run says nothing about how long a real attach takes: that depends on whether the scan is skipped.
Default partitions, and the CHECK left behind
The default partition from the first lesson changes both commands. The documentation says that when a table has a default partition, defining a new partition scans the default partition to prove that it holds no row that belongs to the new one, and that this scan holds an ACCESS EXCLUSIVE lock on the default partition. The same trick as before avoids it: a CHECK constraint on the default partition that excludes the new range. DETACH ... CONCURRENTLY is not allowed at all. The script puts a March trip in a default partition and tries both, then removes the default partition and detaches properly.
ts
const err = (e: unknown) => {
const x = e as { code?: string; message: string }
return`ERROR ${x.code} ${x.message}`
}
const db = new PGlite()
await db.exec(`
CREATETABLE trips (
trip_id bigint NOT NULL, trip_date date NOT NULL
) PARTITION BY RANGE (trip_date);
CREATETABLE trips_2026_01 PARTITION OF trips FOR VALUES
FROM ('2026-01-01') TO ('2026-02-01');
CREATETABLE trips_2026_02 PARTITION OF trips FOR VALUES
FROM ('2026-02-01') TO ('2026-03-01');
CREATETABLE trips_default PARTITION OF trips DEFAULT;
INSERT INTO trips (trip_id, trip_date) VALUES
(1, '2026-01-10'), (2, '2026-02-10'), (3, '2026-03-05');`)
console.log('-- the March trip landed in the default partition')
show(
(
await db.query(
`SELECT tableoid::regclass::text AS partition,
count(*)::int AS trips
FROM trips GROUP BY tableoid ORDER BY 1`
)
).rows
)
console.log(
'-- attach March while the default partition holds a March row'
)
await db.exec('CREATE TABLE trips_2026_03 (LIKE trips)')
try {
await db.exec(
`ALTER TABLE trips ATTACH PARTITION trips_2026_03
FOR VALUES FROM ('2026-03-01') TO ('2026-04-01')`
)
} catch (e) {
console.log(err(e))
}
console.log('-- DETACH CONCURRENTLY with a default partition')
try {
await db.exec(
'ALTER TABLE trips DETACH PARTITION trips_2026_01 CONCURRENTLY'
)
} catch (e) {
console.log(err(e))
}
text
ERROR 23514 updated partition constraint for default partition
"trips_default" would be violated by some row
-- DETACH CONCURRENTLY with a default partition
ERROR 55000 cannot detach partitions concurrently when a default
partition exists
ts
console.log('-- without a default partition, it works')
await db.exec('DROP TABLE trips_default')
await db.exec(
'ALTER TABLE trips DETACH PARTITION trips_2026_01 CONCURRENTLY'
)
console.log('-- and leaves a CHECK on the detached table')
show(
(
await db.query(
`SELECT count(*)::int AS check_constraints
FROM pg_constraint
WHERE conrelid = 'trips_2026_01'::regclass AND contype = 'c'`
)
).rows
)
await db.close()
text
-- and leaves a CHECK on the detached table
check_constraints
-----------------
1
(1 row)
The attach failed with SQLSTATE 23514, updated partition constraint for default partition "trips_default" would be violated by some row: the March trip sitting in the default partition belongs in the new partition, so PostgreSQL refuses until that row is moved. The concurrent detach failed with SQLSTATE 55000, cannot detach partitions concurrently when a default partition exists. The last query shows one more detail from the ALTER TABLE page, which the run confirms: a concurrent detach adds a CHECK constraint to the detached table that duplicates the old partition bound, so the detached table keeps the knowledge of what it used to hold. A team that wants both a safety net for stray dates and online retention has to choose: monitor the default partition and keep it empty, or leave it out and let a bad date fail loudly.
Check yourself
Why can the primary key of a table partitioned by trip_date not be just trip_id?
A unique constraint on a partitioned table must include every partition key column, and the run refused the key with 0A000.
The key (trip_id, trip_date) works, but it does not stop trip id 1 from appearing on two different dates.
What do you add before ATTACH PARTITION to avoid the validation scan, and what do you do after?
A valid CHECK constraint that allows only rows within the new partition's bounds, so PostgreSQL can skip the scan.
Drop the constraint afterwards, because it duplicates the partition constraint.
Name two restrictions on DETACH PARTITION ... CONCURRENTLY.
It cannot run inside a transaction block (the run failed with 25001).
It is not allowed when the partitioned table has a default partition (the run failed with 55000).
Part 3 · When to shard, and choosing a shard key
What sharding is, and what comes before it
Sharding splits a table across several database servers, called shards, so that each server holds only part of the rows and handles only part of the traffic. It is horizontal partitioning at the level of machines: the pieces no longer share memory, disk or a write-ahead log. The cost is large. A shard-aware application needs a way to find the right shard for every query, joins and foreign keys stop working across shards, and moving data between shards is an operation you must design.
That cost is why sharding comes late. Before it there are cheaper steps. A bigger machine, called vertical scaling, often buys years. Read replicas, from the replication chapter, take read traffic off the primary. Partitioning, from the first two lessons, keeps one big table manageable on one server. Caching and better indexes remove load before it reaches the database at all. Shard when writes or data volume exceed what one well-tuned server can take, not before. The Citus documentation, which describes a system that shards Postgres, says that choosing the distribution column for each table is one of the most important modelling decisions, and that a poor choice slows queries and limits what SQL works across nodes.
What makes a good shard key
The shard key is the column whose value decides the shard, the same idea as the partition key one level up. Four properties matter.
High cardinality. The key needs many distinct values. With eight cities and four shards, one shard can end up with nothing. The Citus guide recommends a high-cardinality column for real-time applications and warns against low-variety columns such as an order status.
Even load, not only even rows. Distinct values are not enough if a few of them carry most of the traffic. A fleet account that books thousands of trips makes one shard hot however well the hash spreads the other riders.
Queries stay on one shard. The best key is one that nearly every query supplies, so a request goes to a single shard. A trips table sharded by rider serves "my trips" from one shard; sharded by trip id it would have to ask every shard.
Stable over time. If a row's key can change, the row has to move shards. Immutable ids are safer than names or cities.
Measuring skew before committing
These properties can be measured before any server is split. The next script generates 20,000 trips with deliberate skew: 30 percent of trips belong to one rider, a fleet account, and at least 40 percent of trips are in one city. It hashes four candidate keys onto four shards and prints how many rows each shard would hold. The hash is the same stable function used by the router in the next lesson, a 32-bit FNV-1a followed by a remainder. shardOf also refuses two inputs it cannot place, a shard count that is not a positive whole number and a key that is missing, because the next lesson shows what happens when a router guesses.
ts
exportfunction fnv1a(text: string): number {
let h = 0x811c9dc5
for (const byte ofnew TextEncoder().encode(text)) {
h ^= byte
h = Math.imul(h, 0x01000193) >>> 0
}
return h >>> 0
}
// a router must refuse what it cannot place, not guessexportfunction shardOf(key: string | number, shards: number): number {
if (!Number.isInteger(shards) || shards < 1)
thrownew RangeError(`bad shard count ${shards}`)
if (
key === null ||
key === undefined ||
key === '' ||
(typeof key === 'number' && !Number.isFinite(key))
)
thrownew TypeError(
`cannot route ${key === '' ? 'empty text' : key}`
)
return fnv1a(String(key)) % shards
}
ts
const db = new PGlite()
await db.exec(`
CREATETABLE trips (trip_id bigint PRIMARY KEY, rider_id int NOT NULL,
city text NOT NULL, trip_date date NOT NULL);
INSERT INTO trips (trip_id, rider_id, city, trip_date)
SELECT i,
CASE WHEN i % 10 < 3 THEN 1 ELSE 2 + (i * 7919) % 1999 END,
(ARRAY['Bengaluru','Pune','Chennai','Jaipur',
'Indore','Kochi','Nagpur','Surat'])
[CASE WHEN i % 10 < 4 THEN 1 ELSE 1 + i % 8 END],
DATE '2026-01-01' + (i % 90)
FROM generate_series(1, 20000) AS i;`)
const rows = (
await db.query<{
trip_id: string
rider_id: number
city: string
trip_date: Date
}>(
`SELECT trip_id::text AS trip_id, rider_id, city, trip_date
FROM trips`
)
).rows
const top = (
await db.query<{ rider_id: number; trips: number }>(
`SELECT rider_id, count(*)::int AS trips FROM trips
GROUP BY rider_id ORDER BY trips DESC, rider_id LIMIT 3`
)
).rows
show(top)
await db.close()
Reading the table row by row: trip_id gives a near-perfect spread, 5001, 5000, 4999 and 5000, but it fails the second property, because "my trips" would visit all four shards. rider_id has 2,000 distinct values and still puts 9,501 rows, nearly 2 times the average, on shard 0: the fleet account has 6,000 trips and all of them follow it. city is worst. It has only 8 distinct values, shard 1 receives none at all, and shard 0 holds 12,500 rows, 2.5 times the average. trip_date is even here, but it is a poor key for two reasons. Every write on a given day goes to one shard once the date is hashed, which is a hot shard in the making. And the Citus guide calls a timestamp as the distribution column the most common mistake in modelling time series data: hashing time scatters neighbouring times over the shards, while queries over time ask for ranges of it.
A key does not have to be a single column. Some designs combine two, such as a city and a rider id, so that rows for one city stay together while riders inside it still spread out. The price is the same as before: a query that supplies only one of the two parts cannot be routed to a single shard. Whatever the key, check it against the real distribution of the data before building on it, because a wrong key is painful to change once rows are spread over several servers.
No candidate is perfect. A production design usually chooses the key that keeps the most important query on one shard, here the rider, and then deals with the fleet account as a hot key in the last lesson.
Check yourself
Why is city a poor shard key for 8 cities and 4 shards, according to the run?
Eight distinct values hash unevenly: shard 1 received no rows and shard 0 received 12,500, 2.5 times the average.
Low cardinality also means a single big city can never be split across shards.
A key spreads rows perfectly but most queries do not supply it. Why is that a problem?
Every query without the key must be sent to every shard and the answers merged.
The run's trip_id key was perfectly even but would make "my trips" visit all four shards.
Name two steps to try before sharding.
A larger machine, read replicas, partitioning, better indexes or caching.
Shard only when writes or data exceed what one well-tuned server can take.
Part 4 · Routing: hash, range and directory
Three ways to find a shard
Once the table is split, every request needs a router: code that takes the shard key from the request and names the shard. The router may live in the application, in a library, or in a proxy such as Vitess, whose documentation says it computes the sharding key for each query and routes the query to the appropriate shards. Three routing methods cover most designs.
Method
How a key finds its shard
Good at
Weak at
Hash
Hash the key and take the remainder by the number of shards
Spreading keys evenly
Adding a shard moves most keys; range queries visit every shard
Range
A table of key ranges, each owned by a shard
Range queries; moving one range at a time
Hot ranges, such as the newest ids
Directory
A lookup table from key to shard
Any placement, including moving one key
The directory is one more thing to store, cache and keep correct
Hash
How a key finds its shardHash the key and take the remainder by the number of shards
Good atSpreading keys evenly
Weak atAdding a shard moves most keys; range queries visit every shard
Range
How a key finds its shardA table of key ranges, each owned by a shard
Good atRange queries; moving one range at a time
Weak atHot ranges, such as the newest ids
Directory
How a key finds its shardA lookup table from key to shard
Good atAny placement, including moving one key
Weak atThe directory is one more thing to store, cache and keep correct
These are the same three ideas as partitioning, now applied across servers. Real systems mix them: a directory of ranges, or hash buckets that are assigned to shards by a directory.
Where the router runs is a design choice too. In the application, the router is a few lines of code like the ones below, and every application server needs a connection to every shard it may reach. In a proxy, the application talks to one address and the proxy holds the connections, at the cost of one more hop and one more component to keep running. Either way, the router carries the shard map, and every copy of the router has to hold the same map. A copy with an old map sends requests to the wrong shard, which is why map changes are the delicate part of any resharding.
Three servers, one router
The lab starts three PostgreSQL servers on three ports, one per shard, each with the same trips table. The router is the stable hash from the last lesson: the shard is the remainder of the key's hash divided by the number of shards. The script routes eight riders, inserts three trips each, and reads one rider's trips from one shard. Then it asks for a rider that does not exist, adds 40 trips for rider 1, and routes by city to see which shards receive nothing.
// stop each server by its own data folder, then remove the foldersexportasyncfunction stopShards(
clients: pg.Client[],
count = PORTS.length
) {
for (const c of clients) await c.end().catch(() => {})
for (let i = 0; i < count; i++) {
try {
execFileSync(
`${bin}/pg_ctl.exe`,
['stop', '-D', dirOf(i), '-m', 'fast', '-w'],
{ stdio: 'ignore' }
)
} catch {
/* already stopped */
}
}
rmSync('./shards', { recursive: true, force: true })
}
exportconst TRIPS_DDL = `CREATETABLE trips (
trip_id bigint PRIMARY KEY, rider_id int NOT NULL, city text NOT NULL,
fare numeric(8,2) NOT NULL)`
ts
const shards = await startShards()
try {
for (const s of shards) await s.query(TRIPS_DDL)
const insert = (
rider: number,
city: string,
tripId: number,
fare: number
) =>
shards[shardOf(rider, shards.length)].query(
`INSERT INTO trips (trip_id, rider_id, city, fare) VALUES ($1, $2,
$3, $4)`,
[tripId, rider, city, fare]
)
const tripsOf = async (rider: number) => {
const s = shardOf(rider, shards.length)
const r = await shards[s].query(
`SELECT trip_id, city, fare FROM trips
WHERE rider_id = $1 ORDER BY trip_id`,
[rider]
)
console.log(`rider ${rider} -> shard ${s}: ${r.rowCount} trips`)
return r.rows
}
ts
console.log('-- where do riders 1 to 8 live?')
show(
[...Array(8)].map((_, i) => ({
rider_id: i + 1,
shard: shardOf(i + 1, 3),
}))
)
let id = 1for (let rider = 1; rider <= 8; rider++)
for (let k = 0; k < 3; k++)
await insert(rider, 'Pune', id++, 90 + k)
console.log('-- single-key read goes to one shard')
show(await tripsOf(5))
console.log('-- a rider that does not exist')
show(await tripsOf(999))
console.log('-- a hot key: rider 1 books 40 more trips')
for (let k = 0; k < 40; k++) await insert(1, 'Pune', id++, 100)
const counts = []
for (const [i, s] of shards.entries())
counts.push({
shard: i,
trips: Number(
(await s.query('SELECT count(*) AS n FROM trips')).rows[0].n
),
})
show(counts)
text
rider_id | shard
---------+------
1 | 12 | 13 | 24 | 15 | 26 | 27 | 08 | 1
(8 rows)
-- single-key read goes to one shard
rider 5 -> shard 2: 3 trips
trip_id | city | fare
--------+------+------
13 | Pune | 90.0014 | Pune | 91.0015 | Pune | 92.00
(3 rows)
-- a rider that does not exist
rider 999 -> shard 0: 0 trips
(0 rows)
-- a hot key: rider 1 books 40 more trips
shard | trips
------+------
0 | 31 | 522 | 9
(3 rows)
ts
console.log('-- routing by city: three cities, three shards')
const cityShard = ['Pune', 'Chennai', 'Jaipur'].map((c) => ({
city: c,
shard: shardOf(c, 3),
}))
show(cityShard)
const empty = [0, 1, 2].filter(
(s) => !cityShard.some((c) => c.shard === s)
)
console.log(
`shards that receive no city: ${empty.join(', ') || 'none'}`
)
} finally {
await stopShards(shards)
}
text
city | shard
--------+------
Pune | 1
Chennai | 1
Jaipur | 0
(3 rows)
shards that receive no city: 2
Rider 5 lives on shard 2, and the read goes to that shard only. Rider 999 does not exist: the router still computes shard 0, asks it, and gets zero rows. A hash router cannot tell "no such rider" from "a rider with no trips", which is acceptable here and wrong in a system where the absence itself needs reporting. The hot key probe shows rider 1 turning shard 1 into the busiest server, 52 trips against 3 and 9. Routing by city sent Pune and Chennai to shard 1 and Jaipur to shard 0, so shard 2 received nothing. All three outcomes come from the same router: the code is fine, the key is the problem.
Range and directory routing, and a range that moves
Range routing keeps an ordered list of key ranges. The second script uses three ranges of rider ids, 1 to 100, 101 to 200 and 201 to 300, one per shard. The map is checked when it is built, which the page after this one explains. The script probes four things in this lesson: an id outside every range, moving a range by editing the map alone, a map edit that overlaps another range, and a directory lookup for a rider the directory does not know. Copying the rows to their new shard is part of the same script and comes with resharding in the last lesson.
ts
const shards = await startShards()
try {
for (const s of shards) await s.query(TRIPS_DDL)
let ranges: Range[] = [
{ from: 1, to: 100, shard: 0 },
{ from: 101, to: 200, shard: 1 },
{ from: 201, to: 300, shard: 2 },
]
checkRanges(ranges, shards.length)
const byRange = (rider: number) => {
const r = ranges.find((x) => rider >= x.from && rider <= x.to)
if (!r) thrownew Error(`no range owns rider ${rider}`)
return r.shard
}
const put = (rider: number, tripId: number) =>
shards[byRange(rider)].query(
`INSERT INTO trips (trip_id, rider_id, city, fare) VALUES ($1, $2,
$3, $4)`,
[tripId, rider, 'Pune', 90]
)
constget = async (rider: number) => {
const s = byRange(rider)
const r = await shards[s].query(
'SELECT trip_id FROM trips WHERE rider_id = $1',
[rider]
)
console.log(`rider ${rider} -> shard ${s}: ${r.rowCount} trips`)
}
ts
await put(40, 1)
await put(120, 2)
await put(120, 3)
await put(250, 4)
console.log('-- range routing')
awaitget(120)
console.log('-- a rider outside every range')
try {
await put(400, 5)
} catch (e) {
console.log('ERROR ' + (e as Error).message)
}
console.log(
'-- move riders 101-150 to shard 2 by editing the map only'
)
ranges = [
{ from: 1, to: 100, shard: 0 },
{ from: 101, to: 150, shard: 2 },
{ from: 151, to: 200, shard: 1 },
{ from: 201, to: 300, shard: 2 },
]
checkRanges(ranges, shards.length)
awaitget(120)
text
rider 120 -> shard 1: 2 trips
-- a rider outside every range
ERROR no range owns rider 400
-- move riders 101-150 to shard 2 by editing the map only
rider 120 -> shard 2: 0 trips
ts
console.log('-- a map edit that overlaps another range is refused')
try {
checkRanges(
[...ranges, { from: 140, to: 160, shard: 0 }],
shards.length
)
} catch (e) {
console.log('ERROR ' + (e as Error).message)
}
text
ERROR 101-150 and 140-160 overlap
The rider 400 insert throws no range owns rider 400 instead of guessing a shard: a router should fail loudly on a key nobody owns. The moved-range probe is the dangerous one. Editing the map to give riders 101 to 150 to shard 2 made the lookup for rider 120 go to shard 2 at once, where it found 0 trips, while the 2 trips were still on shard 1. Until the rows are copied and the old copies deleted, the map and the data disagree and the application silently sees missing data. The overlapping edit was caught by the map check, which compares neighbouring ranges, instead of letting the first match in the list quietly win. How to move the rows safely, and what a crash in the middle of the copy does, comes with resharding in the last lesson.
Directory routing and what a router must refuse
A directory is the third method: an explicit table from key to shard.
ts
console.log('-- directory routing: a table of rider to shard')
const directory = new Map<number, number>([
[40, 0],
[120, 2],
[250, 2],
])
const where = (rider: number) => {
const s = directory.get(rider)
if (s === undefined)
thrownew Error(`rider ${rider} is not in the directory`)
return s
}
console.log(`rider 120 -> shard ${where(120)}`)
try {
where(777)
} catch (e) {
console.log('ERROR ' + (e as Error).message)
}
text
rider 120 -> shard 2
ERROR rider 777 is not in the directory
The directory lookup for rider 777 fails the same way a missing range does, which is the behaviour to want. Every router in this lesson has the same duty: when it cannot place a key, it should say so, and not choose a shard. The hash router was the weakest, and the first version of shardOf was a single line, fnv1a(String(key)) % shards. Run against bad inputs, that line returned NaN for a shard count of 0, which indexes nothing in the array of connections and fails later with an unrelated message, returned 0.5 for 2.5 shards, and sent an undefined key to a shard like any other: a bug that leaves a missing rider id in the application would write the trip to a shard, and nothing would ever find it again. The version above checks both inputs. The range map gets the same treatment with checkRanges.
ts
exporttype Range = { from: number; to: number; shard: number }
// a range map is valid when no range is backwards, every range names// a real shard and no two overlap; a gap fails on lookup insteadexportfunction checkRanges(ranges: Range[], shards: number): void {
if (ranges.length === 0) thrownew Error('the range map is empty')
const sorted = [...ranges].sort((a, b) => a.from - b.from)
for (const r of sorted) {
if (r.from > r.to)
thrownew Error(`range ${r.from}-${r.to} is backwards`)
if (!Number.isInteger(r.shard) || r.shard < 0 || r.shard >= shards)
thrownew Error(
`range ${r.from}-${r.to} names shard ${r.shard} of ${shards}`
)
}
for (let i = 1; i < sorted.length; i++) {
const [a, b] = [sorted[i - 1], sorted[i]]
if (b.from <= a.to)
thrownew Error(`${a.from}-${a.to} and ${b.from}-${b.to} overlap`)
}
}
-- hash router
shard count 0 (an empty shard map): RangeError: bad shard count 0
shard count 2.5: RangeError: bad shard count 2.5
key undefined: TypeError: cannot route undefined
key empty text: TypeError: cannot route empty text
key NaN: TypeError: cannot route NaN
key 1 and key "1": 11
key 1.0 as text and key 1: 01
-- range map
valid map: accepted
empty map: Error: the range map is empty
overlapping ranges: Error: 1-100 and 50-150 overlap
backwards range: Error: range 100-1 is backwards
range names shard 5 of 3: Error: range 1-100 names shard 5 of 3
Each refusal is a different message, so a log line says which input was wrong. Two lines in the output are not refusals. The key 1 and the key "1" go to the same shard because the key becomes text before hashing, but the text "1.0" and the number 1 go to different shards. Put every key into one canonical form before routing, for example a rider id always written as a whole number, because two spellings of one key are two keys to a hash. Gaps in a range map are allowed by the check and fail at lookup, which is why the first script printed no range owns rider 400.
Check yourself
What did the lookup for a rider that did not exist return, and why is that different from an unowned range?
The hash router computed a shard and got zero rows, so it cannot tell a missing rider from one with no trips.
A range or directory router can detect that no entry owns the key and raise an error.
In the run, what went wrong when the range map was edited before the rows were copied?
Rider 120 was looked up on shard 2 and returned 0 trips while its 2 trips were still on shard 1.
Copy the rows first, switch the map, then delete from the old shard.
A bug passes an undefined rider id to a router whose only line is the hash followed by a remainder. What happens, and what does shardOf do instead?
The hash of the text "undefined" gives a valid shard, so the trip is written there and nobody looks for it again.
shardOf throws a TypeError for a missing key and a RangeError for a shard count that is not a positive whole number.
Part 5 · Queries across shards
What stops working
A single-key query goes to one shard and behaves exactly as before. Everything else gets harder. A query without the shard key must be sent to every shard, a pattern called scatter-gather: scatter the same query to all shards in parallel, then gather and combine the partial answers in the application or in a coordinator. The Citus documentation states the problem directly: without co-location you cannot simply perform a join as on a single PostgreSQL node, and the work becomes multi-step.
Three guarantees that a single server gave for free disappear:
Joins across shards have to be done by the application, by pulling rows to one place, or avoided by keeping related rows on the same shard. Citus calls that last idea co-location: rows with the same distribution column value are always on the same machine, even across different tables.
Foreign keys only work inside one server. The Citus documentation lists foreign keys among the features that co-location makes possible, which tells you they stop working across shards.
Transactions that touch two shards are no longer ordinary transactions. They need a coordination protocol: the transactions chapter said that PostgreSQL's two-phase commit support is meant for an external transaction manager, not for application code, and that a prepared transaction holds its locks until it is resolved. Designs prefer to keep a unit of work on one shard.
PostgreSQL has a tool that reaches across servers, postgres_fdw, which presents tables on another server as foreign tables. This chapter names it as an option and does not run it.
Scatter-gather in a real run
The script loads 3,000 invented trips into the three shards, routed by rider. Then it asks one question without the shard key: revenue and trip count per city. The same SQL runs on every shard in parallel with Promise.all, each shard returns four rows, and the application adds the partial counts and sums.
ts
for (const s of shards)
await s.query(`CREATETABLE trips (
trip_id bigint PRIMARY KEY, rider_id int NOT NULL, city text
NOT NULL, fare numeric(8,2) NOT NULL)`)
// 3,000 trips routed by rider_idtype Row = { id: number; rider: number; city: string; fare: number }
const rows: Row[] = []
for (let i = 1; i <= 3000; i++)
rows.push({
id: i,
rider: 1 + ((i * i) % 47),
city: ['Pune', 'Chennai', 'Jaipur', 'Indore'][i % 4],
fare: 50 + ((i * 13) % 400),
})
for (let s = 0; s < 3; s++) {
const mine = rows.filter((r) => shardOf(r.rider, 3) === s)
await shards[s].query(
`INSERT INTO trips (trip_id, rider_id, city, fare)
SELECT * FROM unnest($1::bigint[], $2::int[], $3::text[],
$4::numeric[])`,
[
mine.map((r) => r.id),
mine.map((r) => r.rider),
mine.map((r) => r.city),
mine.map((r) => r.fare),
]
)
}
ts
console.log('-- scatter: one query to every shard, then gather')
const parts = await Promise.all(
shards.map((s) =>
s.query(
`SELECT city, count(*)::int AS trips, sum(fare)::numeric
AS revenue FROM trips GROUP BY city`
)
)
)
parts.forEach((p, i) => {
console.log(`shard ${i}:`)
show(p.rows.sort((a, b) => a.city.localeCompare(b.city)))
})
const merged = new Map<string, { trips: number; revenue: number }>()
for (const p of parts)
for (const r of p.rows) {
const m = merged.get(r.city) ?? { trips: 0, revenue: 0 }
m.trips += r.trips
m.revenue += Number(r.revenue)
merged.set(r.city, m)
}
shard 0:
city | trips | revenue
--------+-------+---------
Chennai | 159 | 38053.00
Indore | 160 | 40272.00
Jaipur | 160 | 40720.00
Pune | 160 | 41120.00
(4 rows)
shard 1:
city | trips | revenue
--------+-------+---------
Chennai | 272 | 67520.00
Indore | 271 | 67627.00
Jaipur | 271 | 67868.00
Pune | 270 | 66240.00
(4 rows)
text
shard 2:
city | trips | revenue
--------+-------+---------
Chennai | 319 | 80777.00
Indore | 319 | 79951.00
Jaipur | 319 | 78312.00
Pune | 320 | 78640.00
(4 rows)
merged:
city | trips | revenue
--------+-------+--------
Chennai | 750 | 186350
Indore | 750 | 187850
Jaipur | 750 | 186900
Pune | 750 | 186000
(4 rows)
Count and sum are easy to combine, because the total is the sum of the partial totals. An average is not: the average of shard averages is wrong unless you weight by counts, so a scatter query should return sums and counts and let the coordinator divide. Every shard did work for this query, and the slowest shard sets the response time, which is why scatter-gather reports are kept off the hot path.
Animated sceneOne shard for a key, every shard for a report0:16
Watch for a rider lookup reaching exactly one shard
Read it as steps
A rider lookup reaches one shard; a city report is sent to all three and merged.
The scene replays the two query shapes side by side. The single-key lookup touched one server. The report touched three, and its answer could not be produced until the slowest of the three replied.
Top-N and the wrong merge
Top-N queries look easy and are not. When rider ids decide the shard, one rider's trips all live on one shard, so each shard's top 3 riders can be merged into a correct global top 3. The run did exactly that.
ts
console.log('-- top 3 riders: top 3 per shard is enough here')
const tops = await Promise.all(
shards.map((s) =>
s.query(
`SELECT rider_id, count(*)::int AS trips FROM trips
GROUP BY rider_id ORDER BY trips DESC, rider_id LIMIT 3`
)
)
)
show(
tops
.flatMap((t) => t.rows)
.sort((a, b) => b.trips - a.trips || a.rider_id - b.rider_id)
.slice(0, 3)
)
If the data is spread differently, the same method is wrong. The next part of the script empties the shards and places trips as a hash on trip id would: rider 1 has 12 trips on each shard, 36 in total, while riders 2, 3 and 4 have 20 trips each on a single shard.
ts
console.log(
'-- trips spread by trip_id instead: a rider is on every shard'
)
for (const s of shards) await s.query('TRUNCATE trips')
const put = (s: number, id: number, rider: number) =>
shards[s].query(
`INSERT INTO trips (trip_id, rider_id, city, fare) VALUES ($1, $2,
'Pune', 90)`,
[id, rider]
)
let id = 1for (let s = 0; s < 3; s++)
for (let k = 0; k < 12; k++) await put(s, id++, 1)
for (let k = 0; k < 20; k++) await put(0, id++, 2)
for (let k = 0; k < 20; k++) await put(1, id++, 3)
for (let k = 0; k < 20; k++) await put(2, id++, 4)
const local = await Promise.all(
shards.map((s) =>
s.query(
`SELECT rider_id, count(*)::int AS trips FROM trips
GROUP BY rider_id ORDER BY trips DESC, rider_id LIMIT 1`
)
)
)
const naive = local
.flatMap((t) => t.rows)
.sort((a, b) => b.trips - a.trips || a.rider_id - b.rider_id)[0]
console.log(
`top-1 per shard: rider ${naive.rider_id} with ${naive.trips}`
)
ts
const all = await Promise.all(
shards.map((s) =>
s.query(
`SELECT rider_id, count(*)::int AS trips FROM trips
GROUP BY rider_id`
)
)
)
const sums = new Map<number, number>()
for (const t of all)
for (const r of t.rows)
sums.set(r.rider_id, (sums.get(r.rider_id) ?? 0) + r.trips)
const best = [...sums].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0]
console.log(`all counts summed: rider ${best[0]} with ${best[1]}`)
text
top-1 per shard: rider 2 with 20
all counts summed: rider 1 with 36
Taking the top rider on each shard and then the biggest of those picks rider 2 with 20, because rider 1 is never the leader on any single shard. Summing every rider's counts first gives rider 1 with 36, which is correct. A top-N over a key that is spread across shards needs complete per-key counts, or a bound on how much each shard must return, before the merge is safe.
No foreign keys across shards
The last probe of the script gives shard 0 a riders table containing rider 7 and gives shard 1 a trips table with a foreign key to its own riders table. A trip for rider 7 is inserted on shard 1.
ts
console.log('-- a foreign key cannot see another shard')
await shards[0].query(
'CREATE TABLE riders (rider_id int PRIMARY KEY, name text NOT NULL)'
)
await shards[0].query(
"INSERT INTO riders (rider_id, name) VALUES (7, 'Meena')"
)
await shards[1].query(
'CREATE TABLE riders (rider_id int PRIMARY KEY, name text NOT NULL)'
)
await shards[1].query('TRUNCATE trips')
await shards[1].query(
`ALTER TABLE trips
ADD CONSTRAINT trips_rider_fk FOREIGN KEY (rider_id)
REFERENCES riders (rider_id)`
)
try {
await shards[1].query(
`INSERT INTO trips (trip_id, rider_id, city, fare) VALUES (900, 7,
'Pune', 90)`
)
} catch (e) {
const x = e as { code: string; message: string }
console.log(`ERROR ${x.code} ${x.message}`)
}
text
ERROR 23503 insert or update on table "trips" violates foreign key
constraint "trips_rider_fk"
The insert fails with SQLSTATE 23503 even though rider 7 exists, because the constraint can only see the riders table on shard 1. Two designs avoid this. Keep a rider's trips on the rider's shard, so the foreign key never leaves a server. Or copy small, rarely changing tables, such as cities, to every shard; Citus calls these reference tables. For lookups by a column that is not the shard key, such as an email address that must be unique, a global lookup table is needed: a directory that maps the email to the owning shard, itself stored in one place or sharded by email.
Check yourself
Why is the average of each shard's average fare the wrong way to compute an overall average?
Shards hold different numbers of rows, so the shard averages must be weighted by counts.
Return a sum and a count from every shard and divide after merging.
In the run, why did top-1 per shard give rider 2 while the correct answer was rider 1?
Rider 1's 36 trips were split 12 per shard, so no shard saw rider 1 as its leader.
Rider 2 had 20 trips on one shard and won every local comparison.
How can a design keep foreign keys working in a sharded database?
Co-locate related rows on the same shard so the foreign key never crosses a server.
Copy small shared tables to every shard as reference tables.
Part 6 · Resharding and hot keys
Why adding a shard is hard
Every sharded system eventually needs more shards. The question is how many rows must move. With modulo routing, the shard is a remainder, and changing the divisor from 3 to 4 changes the remainder of most keys. Rows move even when the new shard is only supposed to take over a quarter of the data.
Consistent hashing avoids that. Shards and keys are both hashed onto a circle of values, and each key belongs to the next shard point clockwise. Adding a shard places new points on the circle, and only the keys between each new point and the one before it change owner. The Cassandra documentation describes partitioning all data across nodes with a hash function over a token ring, and the run below measures what that does to the number of keys that move. A virtual node is one of several points a single shard owns on the circle; more points per shard make the load more even.
Measuring what moves
The script routes 1 lakh rider keys by modulo with 3 shards and with 4, and counts the keys whose shard changed. It then does the same for a ring built with the same hash, with one point per shard and with 100 points per shard. It also counts keys that moved to a shard that already existed, which should be none: a good rebalance only moves keys onto the new shard.
ts
// modulo routinglet movedMod = 0,
wrongMod = 0const loadMod = [0, 0, 0, 0]
for (const k of keys) {
const a = shardOf(k, 3),
b = shardOf(k, 4)
loadMod[b]++
if (a !== b) {
movedMod++
if (b !== 3) wrongMod++
}
}
ts
// consistent hashing: shards own points on a ring, a key goes to the// next point clockwisefunction ring(shardCount: number, pointsPerShard: number) {
const points: { at: number; shard: number }[] = []
for (let s = 0; s < shardCount; s++)
for (let v = 0; v < pointsPerShard; v++)
points.push({ at: fnv1a(`shard-${s}#${v}`), shard: s })
points.sort((a, b) => a.at - b.at)
return (key: string) => {
const h = fnv1a(key)
let lo = 0,
hi = points.length
while (lo < hi) {
const mid = (lo + hi) >> 1if (points[mid].at < h) lo = mid + 1else hi = mid
}
return points[lo % points.length].shard
}
}
Modulo moved 74,952 of 1 lakh keys, 75.0 percent, and 49,953 of them moved between old shards that did not change at all. That is a lot of copying that does nothing useful. The ring with 100 points per shard moved 21,549 keys, 21.5 percent, all of them onto the new shard. That is about 3.5 times fewer. The ring with one point per shard moved only 3,900 keys, but the load afterwards was 4,773 / 30,557 / 60,770 / 3,900: with one point each, the shards own very different arcs, so the load is badly uneven. More virtual nodes smooth that, and the 100-point ring ended at 36,167 / 17,191 / 25,093 / 21,549, much closer to even though still not equal. The consistent hashing idea is covered further in the system design course.
Animated sceneKeys moved when a fourth shard arrives0:16
Keys moved for no gain: ≈ 53,400 (the price of dividing by the shard count)
Read it as steps
From the run: 1 lakh keys, modulo routing against a consistent-hashing ring.
Real systems do this copying while traffic continues. The Vitess documentation describes resharding as copying the data to the new shards and keeping it current while the existing shards continue to serve live reads and writes, followed by a cutover that it says causes a few seconds of read-only downtime. A hand-written copy job has none of that protection, and the next page shows what one crash does to it. The tools exist because getting this order right by hand, under load, is hard.
Copying the rows, and a job that crashes
Moving a range is a copy job, and a copy job can die halfway. This is the rest of the range-routing script from the routing lesson, where the map had already been edited to give riders 101 to 150 to shard 2. It copies their rows from shard 1 to shard 2 with a plain insert and stops, as a crash would. The restarted job runs the same copy again.
ts
const copyRows = async (repeatable: boolean) => {
const moved = await shards[1].query(
`SELECT trip_id, rider_id, city, fare FROM trips
WHERE rider_id BETWEEN 101 AND 150 ORDER BY trip_id`
)
for (const r of moved.rows)
await shards[2].query(
`INSERT INTO trips (trip_id, rider_id, city, fare)
VALUES ($1, $2, $3, $4)` +
(repeatable ? ' ON CONFLICT (trip_id) DO NOTHING' : ''),
[r.trip_id, r.rider_id, r.city, r.fare]
)
return moved.rows.map((r) => r.trip_id as string)
}
ts
console.log('-- copy the rows to the new shard')
const ids = await copyRows(false)
console.log(`copied ${ids.length} rows, then the job crashed`)
console.log('-- the restarted job copies again')
try {
await copyRows(false)
} catch (e) {
const x = e as { code: string; message: string }
console.log(`ERROR ${x.code} ${x.message}`)
}
console.log('-- with ON CONFLICT DO NOTHING the copy can be repeated')
await copyRows(true)
console.log('-- delete only the rows that were copied, then look up')
await shards[1].query(
'DELETE FROM trips WHERE trip_id = ANY($1::bigint[])',
[ids]
)
awaitget(120)
text
copied 2 rows, then the job crashed
-- the restarted job copies again
ERROR 23505 duplicate key value violates unique constraint "trips_pkey"
-- with ON CONFLICT DO NOTHING the copy can be repeated
-- delete only the rows that were copied, then look up
rider 120 -> shard 2: 2 trips
The plain copy cannot be repeated. Its second run failed on the first row with SQLSTATE 23505, a duplicate key, because the rows from the first run were already on shard 2, and a job that stops at the first error never gets as far as the delete. The repeatable copy adds ON CONFLICT (trip_id) DO NOTHING, so a row that is already there is left alone and the job can be run as many times as needed. The delete at the end names the copied ids instead of repeating the range condition: a row written to the old shard after the copy started is not in the list, so it is not deleted unseen. The script switched the map first only to show the gap that opens. The order to use is to copy first, switch the map, then delete from the old shard, with writes paused or logged for that key range. The lookup for rider 120 now finds its 2 trips on the new shard, where the map already pointed.
Hot keys
Resharding fixes uneven placement of many keys. It cannot fix one key that is too busy for any shard, such as the fleet account with 6,000 trips. The remedy is to give the hot key more than one location. Key splitting appends a small suffix to the key, here the trip number modulo 4, so the rider's writes spread over four keys. The second half of the same script shows it.
ts
console.log('-- a hot key and a split key')
const trips = Array.from({ length: 6000 }, (_, i) => ({
trip: i + 1,
rider: 1,
})).concat(
Array.from({ length: 6000 }, (_, i) => ({
trip: 6001 + i,
rider: 2 + ((i * 7) % 300),
}))
)
const count = (
keyOf: (t: { trip: number; rider: number }) => string
) => {
const per = [0, 0, 0, 0]
for (const t of trips) per[shardOf(keyOf(t), 4)]++
return per.join(' / ')
}
console.log(
'key = rider: ',
count((t) => `rider:${t.rider}`)
)
console.log(
'key = rider:#(trip%4): ',
count((t) =>
t.rider === 1 ? `rider:1#${t.trip % 4}` : `rider:${t.rider}`
)
)
console.log('reading rider 1 now asks four keys:')
for (const s of [0, 1, 2, 3])
console.log(` rider:1#${s} -> shard ${shardOf(`rider:1#${s}`, 4)}`)
With the plain key, one shard receives 7,500 of 12,000 trips. With the suffix, each of the four shards receives 3,000. The price is on the read side: all trips of rider 1 now live under four keys on four shards, so reading them needs four queries and a merge. That is the same trade as the scatter-gather lesson, accepted only for the few keys that need it. The DynamoDB developer guide describes the same technique, write sharding with a random or calculated suffix, and states the same cost: to read all items for a key you must query every suffix and merge the results.
Check yourself
In the run, how many of the 1 lakh keys moved with modulo routing when going from 3 to 4 shards, and how many with a 100-point ring?
74,952 with modulo, 75.0 percent, and 21,549 with the ring, 21.5 percent.
Modulo also moved 49,953 keys between shards that were not changing.
A copy job moving a range to a new shard crashes after copying and is started again. Why did the plain insert fail on the second run, and what makes the job safe to repeat?
The rows from the first run were already on the new shard, so the insert hit the primary key and failed with 23505.
ON CONFLICT DO NOTHING lets the repeat skip rows that are already there, and the delete names only the copied ids.
What does splitting a hot key cost?
Reading all of that key's rows needs one query per suffix and a merge.
It spreads writes, so it is only worth doing for the few keys that are too busy for one shard.