Tolgahan Bora,when to repack a PostgreSQL table

Your PostgreSQL Table Is Bloated. Is Repacking Worth the Risk?

A busy PostgreSQL table can accumulate space that ordinary vacuuming does not return to the operating system. Rewriting it may recover that space, but the rewrite itself competes with production traffic and eventually needs a strong lock.

PostgreSQL 19, released on November 19, 2026, adds native REPACK (CONCURRENTLY). That changes the available tools, not the decision: measure what you can gain, fix the cause of recurring bloat, and budget for the rewrite before choosing a command. (postgresql.org)

First, decide what problem you are solving

Repack when the expected benefit is worth the temporary disk, I/O, write-amplification, and lock risk—not merely because a table is large.

Plain VACUUM normally makes space from dead row versions reusable inside the table. It usually does not shrink the file, except when empty pages at the end can be truncated. That reusable space may be valuable if updates will soon fill it again. A rewrite is more compelling after a one-off mass deletion, when the table is unlikely to regrow and returning space matters. (postgresql.org)

For a slow query, establish a baseline with a representative EXPLAIN (ANALYZE, BUFFERS) and production latency observations. A smaller table may help some scans, but a rewrite is not a substitute for checking the query, indexes, and planner statistics. Treat improved latency as a hypothesis to test, not a promised result.

Measure the table before proposing a rewrite

Start with inexpensive estimates and sizes. Replace the schema and table name with your own:

SELECT
  schemaname,
  relname,
  pg_size_pretty(pg_relation_size(relid)) AS heap_size,
  pg_size_pretty(pg_indexes_size(relid)) AS indexes_size,
  pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
  n_live_tup,
  n_dead_tup,
  last_autovacuum,
  last_autoanalyze
FROM pg_stat_user_tables
WHERE relid = 'public.orders'::regclass;

The heap and index sizes are separate; total size also includes associated storage such as TOAST. n_dead_tup is an estimate of dead rows, not a byte-level bloat measurement. A low value does not prove the table file is compact: vacuum may already have made space reusable without shrinking it. (postgresql.org)

If the decision still matters, investigate physical space with pgstattuple or pgstattuple_approx, subject to your provider's extension support and permissions. The full pgstattuple scan can be expensive on a large table; the approximate function avoids scanning some pages. Check indexes separately with pgstatindex for B-trees. These measurements are not a perfect simultaneous snapshot while writes continue. (postgresql.org)

Also inspect old transactions, replication slots, and vacuum behavior before changing anything. If cleanup is being held back or autovacuum cannot keep pace, a rewrite without addressing that cause can leave you back where you started. Do not use repacking as your wraparound-prevention plan; PostgreSQL recommends vacuum for that job. (postgresql.org)

Pick the smallest operation that solves the problem

For example, after a large historical-data deletion, a table may retain a large file even after vacuum has cleaned dead rows. If the remaining workload will not reuse that space, reclaiming it may justify a rewrite. If the same deletion and regrowth happen every week, first question whether repeatedly shrinking the file achieves anything useful.

PostgreSQL 19: native REPACK is concurrent, not consequence-free

On an eligible PostgreSQL 19 table, the targeted syntax is:

REPACK (CONCURRENTLY) public.orders;

Run it as a standalone command, not inside a transaction block. Concurrent mode uses logical decoding to capture changes while it copies the table and indexes. It holds a less restrictive lock for most of the operation, then needs ACCESS EXCLUSIVE for the final catch-up and file swap. The final lock duration can depend on changes accumulated while waiting. DDL on the table can cause the operation to fail. (postgresql.org)

There are important eligibility checks: the table needs a primary key or index-based replica identity; concurrent mode cannot target a partitioned parent or an unlogged table; and a repack replication slot must be available. Check the documentation for the full list and your provider's support. The calling role needs MAINTAIN privilege. (postgresql.org)

There is also a less obvious correctness risk: the documentation warns that concurrent repacking is not MVCC-safe. A concurrent transaction using a snapshot taken before the repack started can see the table as empty after the repack commits. Identify long-running snapshot-based jobs and test their behavior before scheduling the rewrite. (postgresql.org)

Earlier versions: evaluate pg_repack separately

pg_repack is a separate extension and client, not the PostgreSQL 19 SQL command. It records concurrent changes with a trigger and log table, copies the table, catches up, and swaps the result. It needs brief ACCESS EXCLUSIVE locks at setup and swap, and blocks conflicting table DDL during the operation. The project documents a primary-key or qualifying unique-index requirement. (pgxn.org)

Its default lock-conflict behavior deserves particular attention: after its wait timeout, it can cancel conflicting queries and eventually terminate backends. For a production plan where skipping is preferable to disrupting sessions, evaluate --no-kill-backend with a deliberately short --wait-timeout. Rehearse the exact installed version and provider configuration; these flags do not remove the need for a strong lock. (pgxn.org)

Budget for the peak, then define an abort point

For native REPACK, PostgreSQL documents free space of at least the table plus its indexes for the temporary copy. Concurrent changes need additional on-disk storage; index-ordered rewrites can also need a sort file. The pg_repack documentation recommends additional free space of roughly twice the target table and index size. These are planning floors or project guidance, not substitutes for a rehearsal under representative write traffic. Check each relevant tablespace, WAL/archive capacity, and replica headroom. (postgresql.org)

Before starting, agree on:

  1. A stop threshold: for example, a free-space floor, replica-lag limit, or application latency ceiling chosen for your system.
  2. A lock plan: identify long transactions, pause conflicting DDL, and decide how long a pending exclusive lock is tolerable.
  3. A cancellation and recovery plan: rehearse cancellation and inspect the installed tool's cleanup guidance. Cancellation is not a promise of instantaneous resource recovery.
  4. A verification plan: compare table and index sizes, representative query behavior, replica health, and autovacuum activity afterward. Run or schedule ANALYZE as appropriate; native REPACK supports an ANALYZE option for a single non-partitioned table. (postgresql.org)

My default is to postpone if I cannot state the expected benefit and the abort condition in advance. A smaller file is useful; a predictable production system is more useful.

FAQ

Does VACUUM remove PostgreSQL table bloat?

Plain VACUUM removes eligible dead row versions and makes their space reusable. It generally does not compact the whole table or return that space to the operating system. (postgresql.org)

Can I repack without blocking writes?

Concurrent approaches allow normal reads and writes during most of the work, but both native REPACK (CONCURRENTLY) and pg_repack need an ACCESS EXCLUSIVE lock for a final swap. Waiting for that lock can affect other sessions. (postgresql.org)

Should I upgrade to PostgreSQL 19 just to repack?

Not automatically. A major upgrade is a separate migration decision with its own testing and cutover requirements. Evaluate the tools supported on your current version and environment before treating an upgrade as the maintenance fix. (postgresql.org)