Skip to content
dbexplore

Vacuum

REPACK, pg_repack or VACUUM FULL

For the DBA with a bloated table and three ways to shrink it, who wants to know whether to rewrite it at all, and with which tool.

PostgreSQL 19 added REPACK (CONCURRENTLY). When a rewrite is worth it, what each of the three options locks and costs, and when plain vacuum is enough.

Reference page, revised in place. Last updated .

Rewrite a bloated table only once whatever bloated it has stopped, and only when the space you would get back is more than the room the table needs to work in. If it passes both tests and runs on PostgreSQL 19, use REPACK (CONCURRENTLY) with a short lock_timeout and a retry, at a time when no write transaction on the server runs longer than that timeout. On 18 and earlier the usual online tool is the pg_repack extension, and that is where our advice has the least to stand on. In our view most bloated tables fail one of the two tests, and a vacuum that keeps up does more for them than any rewrite.

The three rewrites side by side

All three build a fresh copy of the table and its indexes without the dead space, then swap it in. They differ in what they lock while copying and what they need from the table.

What differs VACUUM FULL, or plain REPACK REPACK (CONCURRENTLY) pg_repack
Where it runs Every version; REPACK from 19, which deprecates VACUUM FULL but keeps it for compatibility 19 onwards, in core An extension plus a client program; its documentation lists 9.5 to 18
Lock while copying ACCESS EXCLUSIVE, start to finish SHARE UPDATE EXCLUSIVE SHARE UPDATE EXCLUSIVE (ACCESS SHARE before 1.5.3)
Exclusive lock The whole run The final swap Briefly at setup, and again to swap and drop
Changes made meanwhile None possible, everything waits Captured by logical decoding Captured by a trigger into a log table
The table must have Nothing special Replica identity DEFAULT with a primary key, or USING INDEX; FULL and NOTHING are refused A primary key, or a non-partial unique index on a NOT NULL column
An invalid index on the table VACUUM FULL goes ahead and rebuilds the index, still invalid, in our tests on 14 and 19; REPACK refuses the table Refused Refused by default since 1.5.2
Who may run it VACUUM FULL: MAINTAIN from 17 (before that the owner), and a database owner or superuser on any version. REPACK: MAINTAIN only MAINTAIN only; owning the database is not enough Superusers, or owners with --no-superuser-check

The sources are the REPACK reference, the VACUUM reference and its 16 edition, and the pg_repack documentation. What a concurrent run looks like from the inside, phase by phase and lock by lock, is on the PostgreSQL 19 REPACK page. This page is about whether to type it.

Will the space stay returned?

A rewrite is worth doing when it returns space that will not be used again, and a table that bloated once will bloat again unless whatever produced the dead rows has changed. The routine vacuuming chapter frames the goal as a steady state: each table occupies its minimum size plus whatever gets used up between vacuum runs, and shrinking it below that has little point if it will just grow again.

We measured how fast it grows again. A table of 800,000 live rows was rewritten down to its live data, then put through cycles that each updated a fifth of its rows, 160,000 of them, followed by a manual VACUUM:

When Heap Free space, pgstattuple_approx
Straight after the rewrite 184 MB
After cycle 1 221 MB 18%
After cycles 2 to 5 221 MB, unchanged 17 to 18%

The table regained a fifth of its size in one cycle and then held it, with vacuum reusing the same free space every time. Before the rewrite it had been 460 MB, so of the 276 MB the rewrite freed, 239 MB stayed freed and 37 MB was working room the table took straight back. The size of that working room is set by how many rows change between two vacuums, which here we fixed at a fifth and vacuumed by hand the moment each cycle ended. Under autovacuum the room is at least the rows changed before the trigger fires, plus whatever changes while the worker is queued or running. Either way it is not bloat. A table whose free space is about the share of rows that change between vacuums has nothing to give back for good, and rewriting it buys a smaller number on a dashboard until the next cycle.

So the first check is the one autovacuum and bloat covers: why the dead rows piled up. A vacuum that never reached the table, a transaction holding back the horizon, and a one-off purge all leave bloat behind, and only the last is cured by a rewrite alone. Fix the first two before spending the I/O.

Putting a number on what a rewrite would return

The fixture for the rest of this page is an invoice table that lost three rows in five to a purge and has been vacuumed since:

CREATE EXTENSION IF NOT EXISTS pgstattuple;
CREATE TABLE invoice_lines (
  line_id    bigint PRIMARY KEY,
  account_id int    NOT NULL,
  state      text   NOT NULL,
  note       text
);
INSERT INTO invoice_lines
SELECT g, g % 5000, 'open', repeat('n', 180) FROM generate_series(1, 600000) AS g;
CREATE INDEX invoice_lines_account_idx ON invoice_lines (account_id);
DELETE FROM invoice_lines WHERE line_id % 5 IN (1, 2, 3);
VACUUM ANALYZE invoice_lines;

You can rank every table in a database without installing anything. This estimate multiplies the planner’s row count by the average stored row width from pg_stats, adds the per-row cost of a tuple header and a line pointer, and scales for any fillfactor. Run it as the tables’ owner or a superuser, because pg_stats shows only the columns the current role can read:

SELECT c.oid::regclass                                   AS table_name,
       pg_size_pretty(pg_relation_size(c.oid))          AS heap_now,
       pg_size_pretty(pg_indexes_size(c.oid))           AS indexes_now,
       pg_size_pretty(est.live_bytes)                   AS heap_if_rewritten,
       round(100 * (1 - est.live_bytes
             / nullif(pg_relation_size(c.oid), 0)::numeric)) AS returnable_pct
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
CROSS JOIN LATERAL (
  SELECT (c.reltuples
          * (24 + 4 + sum(s.avg_width * (1 - s.null_frac)))
          * 100.0 / coalesce((SELECT option_value::int
                              FROM pg_options_to_table(c.reloptions)
                              WHERE option_name = 'fillfactor'), 100))::bigint AS live_bytes
  FROM pg_stats s
  WHERE s.schemaname = n.nspname AND s.tablename = c.relname
    AND NOT s.inherited
  HAVING count(*) > 0
) est
WHERE c.relkind = 'r'
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
  AND c.reltuples > 0
ORDER BY pg_relation_size(c.oid) - est.live_bytes DESC
LIMIT 20;

The HAVING drops tables that have never been analysed, which would otherwise look entirely empty and top the list. The estimate covers the main heap only, so TOAST is counted on neither side, it ignores alignment padding and page headers, and it is as fresh as the last ANALYZE. On the 800,000-row table it predicted a rewritten heap of 175 MB, and the rewrite produced 184 MB. Run again on that freshly rewritten table, it still reported 5% returnable.

Our rule of thumb is to ignore anything the estimate puts under about a fifth. The fifth comes from two places: the default autovacuum_vacuum_scale_factor of 0.2 lets a table carry roughly that share of dead rows before a vacuum is even due (less on a very large table, where autovacuum_vacuum_max_threshold caps it from 18), and our churn run settled at about the same share of free space. The 5% noise floor comes from one schema. A table with many narrow columns in an order that forces alignment padding will be underestimated by more, so it reads as more returnable than it is, which is one more reason to count before deciding.

For the tables at the top of that list, count instead of estimating. pgstattuple_approx skips the pages the visibility map marks all-visible and takes their free space from the free space map, according to the pgstattuple documentation. On our fixture it returned in about 2 ms against 83 ms for the full pgstattuple scan, and agreed with it to within a percentage point. Both need superuser, membership of pg_stat_scan_tables, or an explicit GRANT EXECUTE on the function. Free space and dead tuples together are what a rewrite would remove, less any fillfactor reserve, which a rewrite keeps free on purpose. A table at fillfactor 70 read 30% here both before and after we repacked it, so subtract 100 minus the fillfactor:

SELECT pg_size_pretty(table_len)                                  AS heap,
       round((approx_free_percent + dead_tuple_percent)::numeric) AS reclaimable_pct,
       pg_size_pretty(approx_free_space + dead_tuple_len)         AS reclaimable_now
FROM pgstattuple_approx('invoice_lines');

Then estimate the working room. The cumulative counters give the rows updated and deleted per vacuum since statistics were last reset, as a share of the live rows:

SELECT relname,
       n_live_tup,
       vacuum_count + autovacuum_count AS vacuums,
       round(100.0 * (n_tup_upd + n_tup_del)
             / nullif(vacuum_count + autovacuum_count, 0)
             / nullif(n_live_tup, 0), 1) AS changed_pct_per_vacuum
FROM pg_stat_user_tables
WHERE relname = 'invoice_lines';

On the fixture that figure is dominated by the purge, which is exactly the event a rewrite is meant to undo, so on a real table read it over a period of ordinary traffic, or sample the counters twice and take the difference. It includes HOT updates, whose old versions are usually pruned within the page, so treat it as an upper bound. Subtract the working room it implies from reclaimable_now, and what remains is the space you get to keep.

When plain vacuum already gives it back

One shape of bloat needs no rewrite. Vacuum returns space to the filesystem when the empty pages sit at the end of the file, which is where they are after the newest rows are deleted, as when a bad import is backed out:

CREATE TABLE import_batch (row_id bigint PRIMARY KEY, body text);
INSERT INTO import_batch SELECT g, repeat('b', 180) FROM generate_series(1, 200000) AS g;
DELETE FROM import_batch WHERE row_id > 80000;
SELECT pg_size_pretty(pg_relation_size('import_batch')) AS before_vacuum;
VACUUM import_batch;
SELECT pg_size_pretty(pg_relation_size('import_batch')) AS after_vacuum;

The file shrank by the deleted share, from 42 MB to 17 MB on 14, 18 and 19 alike. The truncation needs an ACCESS EXCLUSIVE lock, and the routine vacuuming chapter says it happens only when that lock can be easily obtained, so on a busy table it can quietly not happen. It is also skipped when someone has run VACUUM (TRUNCATE false) or set vacuum_truncate to false for the table, as the VACUUM reference describes. One reason to turn it off is that the lock, like every ACCESS EXCLUSIVE lock taken on the primary, conflicts with queries on hot standbys. The same number of deletes scattered through the file, as in invoice_lines, leaves every page partly used, and vacuum gives back nothing.

What a rewrite cost us, measured

We ran both forms of REPACK on PostgreSQL 19.0, in Docker on a laptop, against a 2,000,000-row version of the fixture: 460 MB of heap and 56 MB of indexes, three rows in five dead and vacuumed, 800,000 live. Sizes here are pg_size_pretty units, so a megabyte is 1,048,576 bytes.

There were three rounds, run one after another on the same server with warm caches. Each round rebuilt both tables, then ran the plain form and then the concurrent one. During each run a second session issued a SELECT count(*) on the table after a one-second pause; that pause separated launching the two sessions, so the true offset varied a little, and every duration below is psql’s own timing of the statement. A one-second probe lands in the copy, so it shows how each form treats readers while copying and says nothing about the swap. Separately, one pair of 25-second pgbench runs with two clients updating random rows by primary key watched throughput per second, and two more 22-second concurrent runs logged every update’s latency.

Measure REPACK REPACK (CONCURRENTLY)
Heap and indexes afterwards 184 MB and 22 MB 184 MB and 22 MB
Run time, median and range of three 7.3 s (4.8 to 9.8) 11.5 s (7.1 to 11.7)
The reader’s time, median and range 6.8 s (4.1 to 8.5) 0.31 s (0.21 to 0.56)
Updates during the run None completed until it finished, 10.8 s in the separate pgbench run Kept going at lower throughput; slowest single update 216 ms in one run and 338 ms in the other
WAL written, each of three runs 202 MB 222 MB
Peak growth of the database, three runs 201 to 206 MB 201 to 206 MB

Run times fell from round to round as caches warmed, so the medians mean less than the pairing: within each round the concurrent form took longer than the plain one. The same count took 0.17 and 0.20 seconds with nothing running in the two rounds where we measured that, so the concurrent form made the reader up to about three times slower without ever blocking it, while the plain form held it for whatever was left of the run. In the two logged runs, 24 of 16,266 and 19 of 16,250 updates took longer than 100 ms. They were spread across the whole run rather than bunched at the end, which reads as I/O contention from the copy on a laptop disk. With nothing else holding a lock on the table, the swap did not stand out. When something does, the swap waits behind it and new queries wait behind the swap, which the 19 REPACK page demonstrates.

The extra disk at peak matched the new copy, 184 MB of heap plus 22 MB of indexes. On this fixture that happened to be 40% of the old footprint because 40% of the rows were live; on yours it is roughly the live data plus rebuilt indexes plus any TOAST. The reference page asks for free space “at least equal to the sum of the table size and the index sizes”, which is the safe figure to plan to. Our sampling of pg_database_size could not see what lives outside the database directory: WAL in pg_wal, temporary sort files while indexes rebuild, and decoded changes the concurrent form stores on disk when other sessions write during the copy, which our sampled runs had none of. The WAL matched the new copy too, identical to within 0.1 MB across runs, with the concurrent form writing about a tenth more. All of it is streamed to every standby and, with archiving on, kept in the archive, so on a large table a rewrite can show up as replication lag and archive growth.

Running it on PostgreSQL 19

Before it copies a row, the concurrent form waits for two things: a lock on the table that conflicts with its own SHARE UPDATE EXCLUSIVE, which means DDL, another vacuum or ANALYZE, or an index build, and every transaction anywhere on the server that has been assigned a transaction ID, prepared transactions included. The progress reporting chapter says the initializing phase waits for the second, including any other REPACK (CONCURRENTLY), so a repack started while another is running waits for it, even on a different table. An ordinary reader or writer on the table does not stop the start. It stops the swap, after the whole copy, which is the expensive place to be stopped. A replica identity of FULL or NOTHING, or an invalid index, makes the command refuse outright. One block shows all of them, and the NULL pid rows in the first result are prepared transactions:

SELECT l.pid, l.mode, a.state, now() - a.xact_start AS open_for, left(a.query, 60) AS query
FROM pg_locks l
LEFT JOIN pg_stat_activity a ON a.pid = l.pid
WHERE l.database = (SELECT oid FROM pg_database WHERE datname = current_database())
  AND l.relation = 'invoice_lines'::regclass
  AND l.pid IS DISTINCT FROM pg_backend_pid()
ORDER BY a.xact_start NULLS FIRST;

SELECT pid, datname, backend_xid, now() - xact_start AS open_for, left(query, 60) AS query
FROM pg_stat_activity
WHERE backend_xid IS NOT NULL
  AND pid <> pg_backend_pid()
ORDER BY xact_start;

SELECT gid, database, prepared FROM pg_prepared_xacts ORDER BY prepared;

SELECT relreplident AS replica_identity,
       (SELECT string_agg(indexrelid::regclass::text, ', ')
        FROM pg_index WHERE indrelid = c.oid AND NOT indisvalid) AS invalid_indexes
FROM pg_class c
WHERE c.oid = 'invoice_lines'::regclass;

The reference page says an invalid index has to be dropped or rebuilt before REPACK will touch the table. Then run it with a bound on the wait. The ANALYZE option refreshes statistics in the same command, which the reference page advises because the planner keeps statistics about a table’s physical order:

SET lock_timeout = '5s';
REPACK (CONCURRENTLY, ANALYZE) invoice_lines;
RESET lock_timeout;
SELECT pg_size_pretty(pg_relation_size('invoice_lines')) AS heap,
       pg_size_pretty(pg_indexes_size('invoice_lines'))  AS indexes;

The timeout can fire in two places, at very different prices, and this is the weakest part of our advice for 19. In initializing it is cheap, since nothing has been copied, but any write transaction on the server that outlasts the timeout makes every attempt fail, so run it when nothing long is writing or set the timeout above your longest routine write transaction. At the swap it is expensive: the whole copy is thrown away, and the WAL the copy wrote has already gone to the standbys and the archive. The reference page warns in the same spirit that a repack can fail after most of the work is done, especially in the concurrent form on a busy table. The other choice is worse, though: while the repack waits for its exclusive lock, every new query on the table queues behind it, so the timeout is the cap on how long the application stalls. We keep it short, a few seconds, and retry from a loop with a pause between attempts, accepting that each retry repeats the copy:

for attempt in 1 2 3 4 5; do
  PGOPTIONS='-c lock_timeout=3s' \
    psql -X -d billing -c 'REPACK (CONCURRENTLY, ANALYZE) public.invoice_lines' && break
  sleep 300
done

We exercised both on 19.0 with a three-second timeout. A write transaction in a different database cancelled the run in initializing after three seconds, with nothing copied. An open transaction that had only read the table let the copy finish and then cancelled it, waiting for the exclusive lock. The 19 REPACK page shows the replication slot going with it.

The concurrent form has other costs. It needs a free slot under max_repack_replication_slots, five by default and changeable only at server start, and during initializing it switches on the extra WAL that logical decoding requires. It fails if more than about 104 million rows are updated or deleted while it runs, and it might fail to complete if another session runs DDL on the table meanwhile. It is not MVCC-safe: the concurrency caveats page says a transaction with a snapshot taken before the command committed, which had not touched the table before the command started, sees it empty afterwards.

Two costs apply to either form. Both take an ACCESS EXCLUSIVE lock at some point, and the hot standby chapter says such locks conflict with standby queries, which are cancelled once max_standby_streaming_delay is exceeded. And for wraparound purposes the reference page counts a repack as one long transaction, which holds back vacuum on every other table. On a very large table, watch the repacking backend’s backend_xid, and read transaction ID wraparound before scheduling it anywhere near a freeze deadline.

Partitioned tables need one more step, because the concurrent form refuses the parent:

CREATE TABLE meter_reads (read_id bigint, read_on date, reading int,
                          PRIMARY KEY (read_id, read_on)) PARTITION BY RANGE (read_on);
CREATE TABLE meter_reads_2026_10 PARTITION OF meter_reads
  FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
INSERT INTO meter_reads
SELECT g, date '2026-10-01' + (g % 31), g FROM generate_series(1, 100000) AS g;
REPACK (CONCURRENTLY) meter_reads;

The error carries a hint to run the command on individual partitions, and a leaf partition with its primary key is an ordinary table as far as the command is concerned:

REPACK (CONCURRENTLY) meter_reads_2026_10;

One partition at a time bounds the extra disk and the WAL to the size of the partition being rewritten, and the older partitions that have stopped changing are the ones where a rewrite’s return stays returned.

On 18 and earlier: the extension and its failure modes

Until a fleet is on 19, the usual online rewrite is pg_repack. pg_squeeze also exists and needs wal_level = logical below 19; we have not covered it here. Either is a different kind of dependency from a command in core. pg_repack is created as an extension in each database you want to process, its library has to be installed on the server, and the client program reports an error when its version does not match the server library or the extension in the database. Its documentation asks for about twice the size of the table and its indexes in free disk, and says DDL on the target cannot run while it works.

The default we would change first is what happens when it cannot get its lock. --wait-timeout defaults to 60 seconds, after which the documentation says it cancels the conflicting queries, and after twice the timeout it falls back to terminating those backends. REPACK under a lock_timeout gives up and leaves your sessions alone; pg_repack by default clears them out of its way. --no-kill-backend makes it skip the table instead, which is the behaviour we would want from any maintenance job:

pg_repack --dbname=billing --table=public.invoice_lines \
          --wait-timeout=30 --no-kill-backend

Since 1.2 a table with no clustering index is compacted without reordering by default, which is what --no-order would otherwise ask for. When a run dies part-way, the documented cleanup is to drop the extension with CASCADE and create it again, which removes the trigger and temporary objects it left on your table, and an invalid index left behind by an interrupted run has to be dropped by hand before the next attempt. Somebody on call has to know to do both. We have not run pg_repack for this page, since the stock image does not ship it, so everything in this section is its own documentation.

VACUUM FULL keeps a narrow place. On a table small enough that the whole rewrite takes a few seconds, holding an exclusive lock for those seconds in a quiet window is simpler than either online tool, and it needs no key and no extension. The plain column in our measurements shows the shape of that trade: the reader waited out the full run, and the full run grows with the table.

Whichever tool you use, the evidence that it worked arrives a cycle later. Record the table’s size the day after the rewrite and again a week on. If it has settled a working room above the rewritten size and stays there, the space was worth taking. If it is climbing back toward where it started, the cause was never fixed, and the next rewrite will buy you the same week.

Put every Postgres you run on autopilot.

We onboard teams in small batches. Tell us about your fleet and we will reach out when a seat opens. One email, no drip campaign.