Goal
A table or index has grown far beyond its live data. Autovacuum has caught up, but the space isn't returned to the operating system, and sequential scans and backups are slower than they should be. VACUUM FULL would fix it, but it holds an ACCESS EXCLUSIVE lock for the whole rewrite, which blocks everything.
pg_repack rebuilds the table into a new copy while the application keeps reading and writing. It captures changes with a trigger and swaps the files at the end. It only needs an exclusive lock for a short time at the start and at the end.
This runbook covers the checks, the run itself, monitoring and recovery from a failed run.
How pg_repack works (and where it can hurt)
- Takes a brief
ACCESS EXCLUSIVElock to create a log table and a trigger on the original table. - Copies the rows into a new table, holding only a lock that blocks DDL. Reads and writes continue, and the trigger logs every change.
- Builds the indexes on the new table.
- Replays the logged changes, then takes
ACCESS EXCLUSIVEagain briefly to apply the last changes and swap the files. - Drops the old table.
The risks come from those steps:
| Risk | Why | Mitigation |
|---|---|---|
| Disk fills up | It needs a full copy of the table and its indexes, plus WAL | Check free space before you start (at least 2x table + indexes) |
| Lock queue pile-up | A long transaction blocks the exclusive lock, and new queries queue behind it | Clear long transactions first, set --wait-timeout |
| Sessions killed | After the wait timeout it cancels, then terminates, blocking backends | Use --no-kill-backend on sensitive systems |
| Replica lag | The copy and index builds generate a lot of WAL | Run off-peak, watch lag, throttle with one table at a time |
| DDL blocked | DDL on the table waits until the run finishes | Freeze deploys that touch the table |
Step 1: Confirm the bloat is real
Check the sizes first:
SELECT relname,
pg_size_pretty(pg_relation_size(relid)) AS table_size,
pg_size_pretty(pg_indexes_size(relid)) AS index_size,
pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 20;
To measure free space inside a table, use pgstattuple. The approximate version is much cheaper on large tables:
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT table_len, approx_free_space, approx_free_percent, dead_tuple_percent
FROM pgstattuple_approx('public.orders');
-- Index bloat for a B-tree index
SELECT avg_leaf_density, leaf_fragmentation
FROM pgstatindex('public.orders_customer_id_idx');
As a rule of thumb, repack when free space is a large share of the table (for example, over 30-40%) and it's not being reused by new rows. If only an index is bloated, REINDEX INDEX CONCURRENTLY (PostgreSQL 12 and later) is simpler and doesn't need pg_repack.
Tip
If dead tuples are still high, fix vacuum first. Repacking a table whose vacuum is blocked by a long transaction or an old replication slot just means it bloats again.
Step 2: Pre-checks
Primary key or unique index
pg_repack needs a primary key or a unique index on NOT NULL columns. Find tables that don't qualify:
SELECT c.oid::regclass AS table_name
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND NOT EXISTS (
SELECT 1 FROM pg_index i
WHERE i.indrelid = c.oid AND i.indisprimary);
Tables without a primary key either need a suitable unique index or can only be repacked with --only-indexes.
Disk space
df -h /var/lib/postgresql
You need room for the new table, its indexes and the WAL produced. On managed services, check free storage in the console or metrics and turn on storage autoscaling if the service has it.
Long transactions and replication slots
SELECT pid, usename, state, now() - xact_start AS xact_age, left(query, 80) AS query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start
LIMIT 10;
A transaction that's been open for hours will block the final swap. Deal with it before you start.
Extension and client versions
The extension must be installed in the target database, and the pg_repack client version must match the extension version:
CREATE EXTENSION IF NOT EXISTS pg_repack;
SELECT extversion FROM pg_extension WHERE extname = 'pg_repack';
pg_repack --version
If the versions differ, the run fails straight away with an error saying the program doesn't match the database library. Install the matching client package, or update the extension with ALTER EXTENSION pg_repack UPDATE.
On Amazon RDS and Aurora, pg_repack is a supported extension. Run the client from an EC2 host or bastion as a user with rds_superuser, and add --no-superuser-check (-k). On Azure Flexible Server, add pg_repack to the azure.extensions server parameter before running CREATE EXTENSION, then check the provider's documentation for required roles. Extension availability varies by version, so check your service's supported extensions list.
Step 3: Dry run
export PGHOST=db01.internal PGPORT=5432 PGUSER=dba PGDATABASE=appdb
pg_repack --dry-run --table=public.orders --echo
--dry-run (-N) shows what would be done without changing anything. --echo (-e) prints the SQL it would send.
Step 4: Run it
Repack one table, with a lock wait timeout and two parallel index builds:
pg_repack --table=public.orders \
--jobs=2 \
--wait-timeout=60 \
--no-kill-backend
What the options do:
--table(-t): repack only this table. Repeat it for more tables. Without--table, it repacks every eligible table in the database, which is rarely what you want in production.--jobs(-j): parallel connections for index builds. Each one adds CPU and I/O load.--wait-timeout(-T): seconds to wait for the exclusive lock (the default is 60).--no-kill-backend(-D): if the lock can't be acquired in time, skip the table instead of cancelling or terminating the sessions in the way.
Caution
Without
--no-kill-backend, pg_repack cancels conflicting queries after--wait-timeoutand terminates their backends after twice that time. On a busy OLTP system that means failed application transactions. Only leave it off if you've agreed this with the application owner.
Other useful variants:
# Rebuild only the indexes of a table (works without a primary key)
pg_repack --table=public.orders --only-indexes
# Rebuild a single index
pg_repack --index=public.orders_customer_id_idx
# Skip the physical reordering (faster; equivalent to VACUUM FULL)
pg_repack --table=public.orders --no-order
Step 5: Monitor while it runs
Watch locks and waiting sessions on the table:
SELECT a.pid, a.state, a.wait_event_type, a.wait_event,
now() - a.query_start AS running_for, left(a.query, 80) AS query
FROM pg_stat_activity a
WHERE a.pid IN (
SELECT pid FROM pg_locks WHERE relation = 'public.orders'::regclass)
ORDER BY a.query_start;
Watch replica lag on the primary:
SELECT application_name, state,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS replay_lag
FROM pg_stat_replication;
If lag reaches your limit or disk drops below your threshold, stop the client with Ctrl+C and follow Step 7.
Step 6: Verify
SELECT pg_size_pretty(pg_total_relation_size('public.orders')) AS total_size;
SELECT approx_free_percent
FROM pgstattuple_approx('public.orders');
ANALYZE public.orders;
Compare with the sizes you recorded in Step 1. Run ANALYZE so the planner has fresh statistics for the rebuilt table.
Step 7: Clean up after a failed or cancelled run
If the run fails or you cancel it, objects can be left behind: a trigger on the original table and work tables in the repack schema. A leftover trigger keeps logging every write, which slows the table down and fills a log table.
SELECT tgname FROM pg_trigger WHERE tgrelid = 'public.orders'::regclass AND tgname LIKE 'repack%';
SELECT relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'repack';
The documented clean-up is to drop and recreate the extension, which removes its schema, work tables and triggers:
DROP EXTENSION pg_repack CASCADE;
CREATE EXTENSION pg_repack;
Warning
Make sure no other pg_repack run is active in that database before you drop the extension.
CASCADEremoves the objects of every in-flight run. Check for invalid indexes afterwards withSELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;.
Prevent it next time
- Tune autovacuum per table (
autovacuum_vacuum_scale_factor,autovacuum_vacuum_cost_limit) for large, update-heavy tables so bloat doesn't build up. - Alert on transactions open longer than your threshold and on inactive replication slots. Both stop vacuum from cleaning up.
- Use partitioning for tables you purge by date, so you drop partitions instead of deleting rows.
- Track table and index sizes weekly, and schedule repacks as planned maintenance with a change ticket, not as an emergency.
- Keep the pg_repack client package in step with the extension version on every server.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get