A PostgreSQL payroll ledger table doubled on disk after a one-off backfill and must stay writable during payroll runs; how would you shrink it with pg_repack, and what can go wrong?
answer
- a shadow table plus a change log
- a trigger captures concurrent writes
- two brief exclusive moments
- primary key or unique NOT NULL key
- about double the disk again
basics
~20 spg_repack copies the table while a trigger logs concurrent writes, builds the copy's indexes, replays the log, then swaps the copy in under a brief ACCESS EXCLUSIVE lock. It needs a primary or unique NOT NULL key and about double the disk.
solid answer
~50 sFirst confirm with `pgstattuple` that the space is really bloat and that its cause has stopped; a one-off backfill qualifies. `VACUUM FULL` and `CLUSTER` would hold `ACCESS EXCLUSIVE` for the whole rewrite, blocking payroll, so use the `pg_repack` extension: `pg_repack --no-order --table=public.payroll_ledger --dbname=payroll`. It briefly takes `ACCESS EXCLUSIVE` to add a trigger and a log table, copies the rows into a new table, builds its indexes, replays the logged changes, then briefly takes the lock again to swap the tables. In between, version 1.5.3 holds only `SHARE UPDATE EXCLUSIVE`, so DML continues while DDL and vacuum on that table wait. It needs a primary key or unique `NOT NULL` key and free disk of about twice the table plus indexes. The risks: lock waits, where by default it cancels and then terminates blockers after `--wait-timeout`; a long copy transaction; and leftovers after an interrupted run.
code
bash · 8 lines# The extension must exist in the target database
psql --dbname=payroll -c 'CREATE EXTENSION IF NOT EXISTS pg_repack;'
# Preview, then repack the one table online without reordering it
pg_repack --dry-run --no-order --table=public.payroll_ledger --dbname=payroll
pg_repack --no-order --table=public.payroll_ledger --dbname=payroll \
--wait-timeout=30 --no-kill-backend --jobs=2go deeper
Recall that pg_repack is an extension that rebuilds a bloated table while it stays readable and writable, unlike VACUUM FULL, which locks the table for the whole run.
Explain the trigger-and-log-table design: copy, build indexes, replay changes, swap, with exclusive locks only at the start and the end, and why it needs a primary or unique NOT NULL key.
Show the operational plan: measure first, check disk and WAL headroom, set wait-timeout and no-kill-backend deliberately, watch the long copy transaction, and know how to clean up an interrupted run.
Ask whether recurring rewrites signal a design fault, such as unbatched backfills or too little vacuum headroom, and set policy so online rewrites stay rare and planned.
## Why the core commands do not fit A one-off backfill that touched every row of `payroll_ledger` left a new version of each row and, once vacuum ran, about half of the heap empty. Normal inserts will reuse that space only slowly, so a rewrite is justified, but the table must stay writable while payroll runs post entries. | | `VACUUM FULL` | `CLUSTER` | `pg_repack` | |---|---|---|---| | Ships with PostgreSQL | Yes | Yes | No: a third-party extension plus a client program | | Lock held during the copy | `ACCESS EXCLUSIVE` | `ACCESS EXCLUSIVE` | `SHARE UPDATE EXCLUSIVE` | | Reads and writes during the copy | Blocked | Blocked | Allowed | | Row order | Physical | Index order | Physical, cluster index, or `--order-by` columns | | Key requirement | None | A clusterable index | Primary key, or unique index on `NOT NULL` columns | | Extra disk (rule of thumb) | About the table's size | Up to twice the table plus indexes | About twice the table plus indexes | Core PostgreSQL 18 has no online table rewrite. `pg_repack` 1.5.3, which supports PostgreSQL 9.5 through 18, is the established tool for it. ## How a full-table repack works 1. Under a brief **`ACCESS EXCLUSIVE`** lock it creates a log table in the `repack` schema and a trigger, `repack_trigger`, that records every `INSERT`, `UPDATE` and `DELETE` on the original table. 2. In one transaction it creates a new table and copies all current rows into it. 3. It builds the indexes on the new table; `--jobs` builds them in parallel over extra connections. 4. It replays the changes accumulated in the log table, repeating until only a few remain (`--switch-threshold`, default 100). 5. Under a second brief **`ACCESS EXCLUSIVE`** lock it applies the last changes and swaps the tables, indexes and TOAST tables in the system catalogs. 6. It drops the original and, unless `--no-analyze` is given, runs `ANALYZE`. Between the two exclusive moments, version 1.5.3 holds a **`SHARE UPDATE EXCLUSIVE`** lock on the table (earlier releases held only `ACCESS SHARE`). `SELECT`, `INSERT`, `UPDATE` and `DELETE` run normally, while `ALTER TABLE`, `VACUUM`, `ANALYZE` and `CREATE INDEX CONCURRENTLY` on that table wait. ## Before you run it - Create the extension in the target database (`CREATE EXTENSION pg_repack`); the client binary and the server library must be the same version, or it stops with a version-mismatch error. - Run it as a superuser, or as the table owner with `--no-superuser-check` where the platform allows that. - Check the key: a table without a primary key or a unique `NOT NULL` key is rejected. - Only permanent, ordinary tables are repacked; temporary and unlogged tables are not. - Confirm free disk for about twice the table plus its indexes, and WAL headroom: the copy and the index builds are WAL-logged, so standbys and the archive absorb them too. - Rehearse with `--dry-run`, and still pick a quiet hour even though writes stay allowed. ## What can go wrong - **Lock acquisition.** Each exclusive lock is requested with a short `lock_timeout` and retried, so `pg_repack` does not sit in the lock queue holding up other sessions. After `--wait-timeout` seconds (default 60) it cancels the conflicting queries with `pg_cancel_backend()`, and after twice that it terminates their sessions with `pg_terminate_backend()`. `--no-kill-backend` makes it skip the table instead, the safer choice when a long payroll report must not be killed. - **Write-heavy tables.** If changes arrive faster than replay applies them, the log never drains. `--apply-count` and `--switch-threshold` tune the catch-up, but on a very hot table the run belongs in a quieter period. - **A long copy transaction.** The copy runs in a single transaction whose snapshot holds back dead-tuple cleanup across the database for as long as it lasts, so watch the other hot tables while it runs. - **An interrupted run.** A killed client or a crash leaves the trigger, the log table and possibly an invalid index behind; the next run warns that `repack_trigger` already exists. Cleaning up means `DROP EXTENSION pg_repack CASCADE`, then `CREATE EXTENSION pg_repack`, and dropping any left-over temporary index by hand. ## Afterwards Measure again with `pgstattuple`: `table_len` should have fallen to roughly the live data plus normal free space. Then fix the cause, so the next backfill runs in batches with vacuum between them instead of rewriting the whole ledger in one statement.
- Why might pg_repack refuse to rebuild a PostgreSQL table at all?The usual reasons: the table has neither a primary key nor a unique index on `NOT NULL` columns (`must have a primary key or not-null unique keys`); the extension is not created in that database; the client and library versions differ; or the table is temporary or unlogged. Ordering by a GiST index is also unsupported.
- Does PostgreSQL 18 ship a built-in online alternative to pg_repack?No. In PostgreSQL 18, `VACUUM FULL` and `CLUSTER` both hold `ACCESS EXCLUSIVE` for the whole rewrite, and nothing in core rewrites a table while allowing writes. The PostgreSQL 19 beta adds a `REPACK` command with a `CONCURRENTLY` option that combines both, but it is beta, not a released feature, so a production answer today still means `pg_repack`.
- What does pg_repack do by default if a long-running report holds a lock on the PostgreSQL table when it needs its exclusive lock?It keeps retrying with a short `lock_timeout`, so it does not queue ahead of other sessions. After `--wait-timeout` seconds (60 by default) it cancels the conflicting queries, and after twice that it terminates their backends. With `--no-kill-backend` it gives up on that table instead and leaves it unrepacked, the safer setting when the blocker is work you cannot lose.
- pg_repack never takes an ACCESS EXCLUSIVE lock at any point
- pg_repack is built into PostgreSQL 18 and needs no installation
- pg_repack can rebuild any table, with or without a primary key
- An online rewrite needs no more free disk than the bloat it removes
- An interrupted pg_repack always removes its own trigger and log table
Assumes PostgreSQL 18 with pg_repack 1.5.3; core 18 has no online table rewrite, and the REPACK command exists only in the PostgreSQL 19 beta.