Skip to content

pg_repack for online table and index rebuilds on PostgreSQL

Use pg_repack to reclaim bloat without long ACCESS EXCLUSIVE locks — install, plan a run, monitor progress, and handle the edge cases that trip up first-timers.

VACUUM FULL gives you back the disk an old workload bloated, but it takes an ACCESS EXCLUSIVE lock on the table — production stops until it finishes. pg_repack does the same thing online: it builds a new copy of the table, trickles in concurrent changes via triggers, then atomically swaps. This article covers the install, a clean run, the locks pg_repack does take, and the failure modes that bite when you run it on a busy database.

How to verify

Confirm the extension and check the most-bloated tables to prioritise:

sudo apt list --installed 2>/dev/null | grep postgresql-16-repack
psql -d app -c "CREATE EXTENSION IF NOT EXISTS pg_repack;"
psql -d app -c "SELECT extversion FROM pg_extension WHERE extname='pg_repack';"
psql -d app -c "SELECT schemaname, relname,
                       pg_size_pretty(pg_total_relation_size(oid)) AS total,
                       round((pg_relation_size(oid) -
                              pg_relation_size(oid, 'main') * 1.0) /
                              pg_relation_size(oid) * 100, 1) AS pct_bloat
                FROM pg_class c JOIN pg_namespace n ON n.oid = relnamespace
                WHERE relkind='r' AND nspname NOT IN ('pg_catalog','information_schema')
                ORDER BY pg_total_relation_size(oid) DESC LIMIT 20;"

For a more accurate bloat estimate use the pgstattuple extension or the pgwatch / pghero bloat queries.

What’s happening

pg_repack works in five phases. First it creates a log table and a trigger on the source table; the trigger records every INSERT/UPDATE/DELETE that happens during the run. Second it creates a new table with the same definition, then copies all rows from source via a snapshot. Third it builds indexes on the new table. Fourth it replays the log table — the changes that accumulated during steps 2 and 3 — until it catches up. Fifth it takes a brief ACCESS EXCLUSIVE lock to swap the relfilenodes; the swap is fast (sub-second) because it’s just a catalog rename.

The key promise: SELECTs and DML on the source table keep running through the whole operation. The cost: extra disk (you need room for two copies of the table plus indexes), trigger overhead during the run, and a long-running transaction holding a snapshot that prevents VACUUM from cleaning rows newer than the start of pg_repack.

A primary key (or REPLICA IDENTITY USING INDEX) is required — pg_repack needs a deterministic way to identify rows for the replay phase.

The procedure

  1. Install the OS package and the extension:

    sudo apt install postgresql-16-repack
    psql -d app -c "CREATE EXTENSION pg_repack;"

    The OS package ships both the server-side extension and the pg_repack CLI.

  2. Estimate disk and lock requirements. You need free disk equal to the table plus all its indexes (one full copy). Check current free space on the data volume and the table’s pg_total_relation_size. Reserve at least 1.5x as headroom.

  3. Run a dry-run first:

    pg_repack --dbname=app --table=public.orders --dry-run

    Catches missing primary keys, replica identity issues, and unsupported table types before you commit to a long run.

  4. Repack the table:

    pg_repack --dbname=app --table=public.orders --jobs=4 --no-superuser-check

    --jobs=4 parallelises the index-build phase. On a 200 GB table this can cut the run from 6 hours to 2. The CLI streams progress to stdout — note the LSN where the replay phase started and watch lag.

  5. For just rebuilding indexes (no table copy):

    pg_repack --dbname=app --table=public.orders --only-indexes

    This is the alternative to REINDEX INDEX CONCURRENTLY — pg_repack handles multiple indexes in one shot and rebuilds them atomically.

  6. Verify on completion:

    psql -d app -c "SELECT pg_size_pretty(pg_total_relation_size('orders'));"
    psql -d app -c "VACUUM (VERBOSE, ANALYZE) orders;"

    The size should drop substantially (10-90% depending on the bloat). Follow with a fresh ANALYZE so the planner has accurate stats on the new heap.

Common pitfalls

  • pg_repack holds a snapshot for the duration of the run — autovacuum cannot remove dead tuples newer than the start of pg_repack on any table. A 6-hour repack on a write-heavy database can balloon bloat elsewhere. Plan for off-peak or accept the tradeoff.
  • Triggers on the source table can interact unexpectedly with pg_repack’s log trigger — review existing triggers before running.
  • If pg_repack crashes or is killed mid-run, it leaves orphan tables (*_pg_repack_*) and the trigger in place. The --error-on-invalid-index option and a careful manual cleanup are necessary.
  • The brief ACCESS EXCLUSIVE at swap-time can deadlock if another session is waiting on a conflicting lock — set lock_timeout on the pg_repack session via PGOPTIONS to bail out cleanly.
  • pg_repack does not support GiST indexes that depend on regclass or certain expression indexes; the dry-run will tell you.

In the engagements we run, pg_repack is the default for any unplanned bloat reclamation on tables larger than 10 GB — VACUUM FULL is reserved for maintenance windows where the lock is acceptable. We pair pg_repack with autovacuum tuning (see vacuum strategies for large tables) so the underlying cause is addressed, not just the symptom. For the operating model behind a tuned Postgres footprint, see managed operations.