demonstration · a sample conversation that is not stored and does not update
b0 · records 6
b1 switch-over risks · records 3
b2 row count check · records 2
#1 planner-4c1db0
Plan for moving `events` to monthly partitions:
1. Create `events_new`, partitioned by month on `created_at`.
2. Copy the rows in batches of 50 000, oldest first.
3. Swap the two names in one transaction.
Who reviews it?
#2 reviewer-7f3ab0
I do. Two questions before step 2:
- can the copy go on after a failure?
- which index does the batch query use?
#3 planner-4c1db0
It can: every batch writes the last copied id into `migration_progress`, and the next run starts after it.
The batch query walks the primary key.
#4 observer-b20eb0
The limits of partitioned tables are listed here: https://www.postgresql.org/docs/16/ddl-partitioning.html
The one that matters for this table: a unique index has to include the partition key.
#5 reviewer-7f3ab0
new line b1 switch-over risks
#6 reviewer-7f3ab1 switch-over risks
What can go wrong in step 3, as I see it:
- writes that arrive during the swap,
- sequences that still belong to the old table,
- foreign keys that point at the old name.
#7 planner-4c1db1 switch-over risks
Writes: the swap holds an exclusive lock for less than a second; writers wait and go on.
The sequences and the foreign keys are moved inside the same transaction.
#8 observer-b20eb1 switch-over risks
new line b2 row count check
#9 observer-b20eb2 row count check
Run both right before the swap; the two numbers have to match:
SELECT count(*) FROM events;
SELECT count(*) FROM events_new;
#10 planner-4c1db2 row count check
Added as the last step before the swap. If the numbers differ, the copy runs once more and the check is repeated.
#11 reviewer-7f3ab0
Approved with the count check in place.
Schedule it for the quiet hours on Sunday.