Deep Engineering
Advanced·Published·75 MIN

Table bloat in PostgreSQL: what VACUUM gives back and what REPACK changes

UPDATE and DELETE free no space, VACUUM returns only the empty tail of the file to the system, and before PostgreSQL 19 the only built-in way to compact a whole table closed it for the entire run. REPACK (CONCURRENTLY) compacts it while reads and writes go on. Measured on PostgreSQL 19.0: where that holds, where the command still stops the service, and why an old snapshot sees an empty table afterwards.

Full technical treatment

TL;DR

  • In PostgreSQL, UPDATE writes a new row version and DELETE marks the old one. VACUUM frees the space but gives back to the system only empty pages at the end of the file: after deleting 90% of the rows scattered across the table, the file in our run stayed at 128.1 MiB; after deleting them from the end, it shrank to 12.8 MiB.
  • Under steady updates a table holds a steady size. Compacted by REPACK to 25.6 MiB, it was back at 28.0 MiB after one round of load. A rewrite pays off after a one-off event — a mass delete, a long transaction — not on a schedule. If only an index has bloated, REINDEX INDEX CONCURRENTLY is enough: 40.7 → 21.4 MiB without rewriting the table.
  • VACUUM FULL closes the table to reads and writes for its whole run. In our run that was 1.3 s for 384 MiB, 3.1 s for 768 MiB and 5.7 s for 1.5 GiB: the stall grows with the table. Plain REPACK closes it for the copy and the index rebuild, and deletes the old files after releasing the lock.
  • REPACK (CONCURRENTLY) from PostgreSQL 19 does the same under a lock that gets in the way of neither reads nor writes, and takes an exclusive one only for the last pass and the file swap. The slowest statement alongside it in our run was 106 ms at most at all three sizes, and no change made during the compaction was lost. That is an observation, not a guarantee: under the exclusive lock the command applies whatever has piled up.
  • The swap needs a lock that conflicts with everything. If a long transaction holds the table — a report, a dump, a forgotten BEGIN — the command waits for it, and every new statement on the table queues behind the command: in our run the reader and the writer stood still for 5.1 s. lock_timeout limits only the waiting: next to a long reader the refusal came after all the work, and the table stayed bloated; next to a writing transaction it came at the start.
  • REPACK (CONCURRENTLY) is not MVCC-safe: a transaction that took its snapshot before the compaction and had not touched the table sees it empty — 0 rows instead of a million. VACUUM FULL and plain REPACK do not do this.

Why should I care?

A table takes three times the space its rows need. VACUUM has run, no errors, and the file is the same size. That is not a fault: this is how PostgreSQL works. The space inside the file is free and new rows will take it, but it does not go back to the system.

Before PostgreSQL 19 the built-in remedy had a price nobody wanted to pay during working hours: VACUUM FULL rewrites the table into a new file and keeps it closed the whole time. On 19 November 2026 PostgreSQL 19 shipped the REPACK command. It replaces both VACUUM FULL and CLUSTER, and with the CONCURRENTLY option it rewrites a table without stopping reads and writes.

This article is about what is behind that. Where bloat comes from and when it needs treating at all. What CONCURRENTLY actually promises and where the command still stops the service. And what a transaction running next to it at that moment will see. Every claim is checked on PostgreSQL 19.0 under a read and write load.

How one long transaction keeps vacuum from removing dead rows has an article of its own — a job queue on PostgreSQL. Here that mechanism matters as a cause of bloat, not as the subject.

The model: UPDATE writes a new row version

language contractPostgreSQL 19, Routine Vacuuming; Database Page Layout

In PostgreSQL an UPDATE or DELETE of a row does not immediately remove the old version of the row. A table stores not rows but row versions, and each one's header records which transaction created it (t_xmin), which one last deleted, updated or merely locked it (t_xmax), and in t_ctid the address of this or a newer row version. Which version a query sees is decided by its snapshot together with how those transactions ended: versions created after the snapshot or deleted before it do not exist for it. This is a simplified model — further down you will see where t_xmax alone is not enough to tell.

You can see this on the page itself. Three rows, then an UPDATE of a column with no index and an UPDATE of the primary key; the page is read with the pageinspect extension, which shows every version whether anyone can see it or not:

measured observationbench/repack/versions.py, block 1, PostgreSQL 19.0. No timing here: the result is the contents of page 0 of the table and the number of index entries.
1. AN UPDATE WRITES A NEW ROW VERSION
-------------------------------------
  after INSERT of rows 1..3
     lp state     t_xmin  t_xmax t_ctid  hot
      1 normal       664       0 (0,1)   
      2 normal       664       0 (0,2)   
      3 normal       664       0 (0,3)   
    rows visible to SELECT: 3; line pointers on page 0: 3; entries in t_pkey: 3
  after UPDATE t SET v = v + 1 WHERE id = 2   (column v has no index; xid 665)
     lp state     t_xmin  t_xmax t_ctid  hot
      1 normal       664       0 (0,1)   
      2 normal       664     665 (0,4)   HEAP_HOT_UPDATED
      3 normal       664       0 (0,3)   
      4 normal       665       0 (0,4)   HEAP_ONLY_TUPLE
    rows visible to SELECT: 3; line pointers on page 0: 4; entries in t_pkey: 3
  after UPDATE t SET id = 30 WHERE id = 3     (id is the primary key; xid 666)
     lp state     t_xmin  t_xmax t_ctid  hot
      1 normal       664       0 (0,1)   
      2 normal       664     665 (0,4)   HEAP_HOT_UPDATED
      3 normal       664     666 (0,5)   
      4 normal       665       0 (0,4)   HEAP_ONLY_TUPLE
      5 normal       666       0 (0,5)   
    rows visible to SELECT: 3; line pointers on page 0: 5; entries in t_pkey: 4

The first UPDATE did not change row 2: it appended version 4. The old one got t_xmax = 665 — the number of the transaction that replaced it — and a link (0,4) to the new one. A query still sees three rows; the page already holds four.

The flags in the last column are HOT, heap-only tuple. The documentation allows it under two conditions. First, the update does not modify any columns referenced by the table's indexes, not including summarizing indexes. The only summarizing index method in the core PostgreSQL distribution is BRIN. Second, there is sufficient free space on the page containing the old row for the updated row. Then the index is left alone: it still points to version 2, which leads on to version 4. There are still three entries in t_pkey.

The second UPDATE changes the key, and HOT is impossible: the new version 5 got its own index entry, making four. One of them leads to a version that nobody will see again.

Both conditions are needed at once. Without room on the page there is no HOT even for an unindexed column — you will see that below, in the fillfactor run. And a BRIN index on the column does not get in HOT's way: a thousand rows with room on every page, an UPDATE of column v, and the only difference is the index on v:

measured observationbench/repack/versions.py, block 6, PostgreSQL 19.0.
6. HOT AND THE KIND OF INDEX ON THE UPDATED COLUMN
--------------------------------------------------
1000 rows, fillfactor 50 (room on every page), a primary key on id; one UPDATE v = v + 1
of every row; the only difference is the index on v
  index on v          HOT updates
  none           1000/1000 (100%)
  btree (v)           0/1000 (0%)
  brin (v)       1000/1000 (100%)

With a B-tree on v not a single update was HOT; with BRIN, all of them were. The summarizing index may still need updating, but it does not need a new entry for every row version.

t_xmax does not always mean a delete either. Row 2 was locked by SELECT … FOR UPDATE, and the delete of row 3 was rolled back:

measured observationbench/repack/versions.py, block 4, PostgreSQL 19.0.
4. T_XMAX IS NOT ALWAYS A DELETE
--------------------------------
t_xmax names the last transaction that deleted, updated or only locked the version;
whether the version is still visible depends on the infomask bits and on how that
transaction ended, not on t_xmax alone
  after SELECT ... WHERE id = 2 FOR UPDATE (xid 987, committed)
    and DELETE ... WHERE id = 3 (xid 988, rolled back), then one SELECT
     lp state     t_xmin  t_xmax t_ctid  xmax flags
      1 normal       986       0 (0,1)   HEAP_XMAX_INVALID
      2 normal       986     987 (0,2)   HEAP_XMAX_EXCL_LOCK,HEAP_XMAX_LOCK_ONLY
      3 normal       986     988 (0,3)   HEAP_XMAX_INVALID
    rows visible to SELECT: 3

Both versions have t_xmax set, and both are visible. What the number in t_xmax means is told by the header bits: HEAP_XMAX_LOCK_ONLY — the transaction only locked the row, HEAP_XMAX_INVALID — it did not commit. From here on, t_xmax appears only on versions that really were deleted or replaced.

What VACUUM does

Only a dead version can be removed — one that no open transaction can see. Removing it completely, together with its line pointer on the page and its index entries, is the job of VACUUM. Here is what it does to a page that still has room:

measured observationbench/repack/versions.py, block 2, PostgreSQL 19.0.
2. A DELETE MARKS VERSIONS, VACUUM FREES THEM
---------------------------------------------
  after DELETE of rows 2 and 3 (xid 670)
     lp state     t_xmin  t_xmax t_ctid  hot
      1 normal       669       0 (0,1)   
      2 normal       669     670 (0,2)   
      3 normal       669     670 (0,3)   
      4 normal       669       0 (0,4)   
    rows visible to SELECT: 2; line pointers on page 0: 4; entries in t_pkey: 4
  after VACUUM t
     lp state     t_xmin  t_xmax t_ctid  hot
      1 normal       669       0 (0,1)   
      2 unused         -       - -       
      3 unused         -       - -       
      4 normal       669       0 (0,4)   
    rows visible to SELECT: 2; line pointers on page 0: 4; entries in t_pkey: 2
  after INSERT of row 5
     lp state     t_xmin  t_xmax t_ctid  hot
      1 normal       669       0 (0,1)   
      2 normal       671       0 (0,2)   
      3 unused         -       - -       
      4 normal       669       0 (0,4)   
    rows visible to SELECT: 3; line pointers on page 0: 4; entries in t_pkey: 3

DELETE freed nothing: two versions got a t_xmax and stayed on the page, and so did the four index entries. VACUUM removed the versions and their index entries, and line pointers 2 and 3 became free. The next INSERT took the space right there.

Part of this work happens without VACUUM too. The documentation describes it for HOT chains: the intermediate versions can be completely removed during normal operation, including SELECTs, instead of requiring periodic vacuum operations. Page pruning is not limited to HOT. A run: seven rows of 1050 bytes fill the page almost to the end, two are deleted, and then the table is only read:

measured observationbench/repack/versions.py, block 5, PostgreSQL 19.0.
5. A NEARLY FULL PAGE IS PRUNED WITHOUT VACUUM
----------------------------------------------
7 rows with a 1050-byte note fill page 0 almost to the end; rows 2 and 3 are deleted;
then the table is only read, never vacuumed, until the last step
  free space on page 0 after the INSERT: 524 bytes
  page 0 right after DELETE of rows 2 and 3 (xid 993), before anything reads it: free 524 bytes
     lp state     t_xmin  t_xmax
      1 normal       992       0
      2 normal       992     993
      3 normal       992     993
      4 normal       992       0
      5 normal       992       0
      6 normal       992       0
      7 normal       992       0
  after one SELECT count(*) FROM t, no VACUUM: free 2700 bytes
     lp state     t_xmin  t_xmax t_ctid  hot
      1 normal       992       0 (0,1)   
      2 dead           -       - -       
      3 dead           -       - -       
      4 normal       992       0 (0,4)   
      5 normal       992       0 (0,5)   
      6 normal       992       0 (0,6)   
      7 normal       992       0 (0,7)   
    rows visible to SELECT: 5; line pointers on page 0: 7; entries in t_pkey: 7
  after VACUUM t: free 2700 bytes
     lp state     t_xmin  t_xmax t_ctid  hot
      1 normal       992       0 (0,1)   
      2 unused         -       - -       
      3 unused         -       - -       
      4 normal       992       0 (0,4)   
      5 normal       992       0 (0,5)   
      6 normal       992       0 (0,6)   
      7 normal       992       0 (0,7)   
    rows visible to SELECT: 5; line pointers on page 0: 7; entries in t_pkey: 5

A single SELECT was enough for the deleted versions' data to vanish from the page: free space went from 524 bytes to 2700. But line pointers 2 and 3 stayed — in the dead state — and the index still holds seven entries: it still refers to those pointers. Only VACUUM could free them, together with the index entries. So pruning delays bloat but does not replace vacuuming.

Plain vacuuming itself frees space only inside the file. The documentation says so directly:

language contractPostgreSQL 19, Routine Vacuuming — Recovering Disk Space

The standard form of VACUUM removes dead row versions in tables and indexes and marks the space available for future reuse. However, it will not return the space to the operating system, except in the special case where one or more pages at the end of a table become entirely free and an exclusive table lock can be easily obtained.

— PostgreSQL 19, Routine Vacuuming

How much space actually comes back

A million rows, 90% of them deleted — once scattered across the table, once from its end. Then VACUUM, then an insert of as many new rows with larger id values. Sizes here and below are in mebibytes (MiB, 1024 × 1024 bytes) and, unless stated otherwise, cover the main fork of the file: no TOAST, no free space map, no visibility map.

measured observationbench/repack/space.py, block 1, first two cases, PostgreSQL 19.0.
1. DELETE 90% OF THE ROWS: SCATTERED VERSUS AT THE END
------------------------------------------------------
1000000 rows (id bigint primary key, v bigint, note text of 80 chars);
table and s_pkey = main fork only, MiB = 1024 * 1024 bytes
  scattered: DELETE WHERE id % 10 <> 0
    freshly loaded                               rows  1000000   table  128.1 MiB   s_pkey  21.4 MiB
    after DELETE                                 rows   100000   table  128.1 MiB   s_pkey  21.4 MiB
    after VACUUM                                 rows   100000   table  128.1 MiB   s_pkey  21.4 MiB
      VACUUM VERBOSE: index "s_pkey": pages: 2745 in total, 0 newly deleted, 0 currently deleted, 0 reusable
      whole footprint now: pg_table_size 128.1 MiB (heap, TOAST, FSM, VM), pg_indexes_size 21.4 MiB, pg_total_relation_size 149.6 MiB
    after INSERT of as many new rows             rows  1000000   table  128.1 MiB   s_pkey  40.7 MiB
    after REINDEX INDEX CONCURRENTLY s_pkey      rows  1000000   table  128.1 MiB   s_pkey  21.4 MiB
  at the end: DELETE WHERE id > 100000
    freshly loaded                               rows  1000000   table  128.1 MiB   s_pkey  21.4 MiB
    after DELETE                                 rows   100000   table  128.1 MiB   s_pkey  21.4 MiB
    after VACUUM                                 rows   100000   table   12.8 MiB   s_pkey  21.4 MiB
      VACUUM VERBOSE: index "s_pkey": pages: 2745 in total, 2465 newly deleted, 2465 currently deleted, 0 reusable
    after INSERT of as many new rows             rows  1000000   table  128.1 MiB   s_pkey  40.7 MiB

The table behaves as documented. After the scattered delete every page kept a tenth of its rows, there were no empty pages at the end, and the file stayed at 128.1 MiB. But the new rows went into the freed space, and the insert did not grow the table by a single mebibyte. The delete from the end freed the whole tail, and VACUUM cut it off: 12.8 MiB.

The main fork is not the table's whole footprint on disk. The whole footprint line shows the rest: pg_table_size is the table with its TOAST and maps, pg_indexes_size is all its indexes, and pg_total_relation_size is the sum. Here TOAST and the maps weigh almost nothing, but in a table with long values the main fork can be the smaller part, and compaction shrinks that part, not necessarily the whole footprint.

The index is a different story, and one people rarely think about. In both cases it nearly doubled after the insert — from 21.4 to 40.7 MiB.

After the scattered delete the index pages did not empty out: each kept a tenth of its keys, and VACUUM deleted none of them (0 newly deleted). The new keys are larger than every old one, and in a B-tree their place is on the right, not in the half-empty pages on the left. There is free space in the index, but it does not suit these keys. The table does not need a rewrite for this: rebuilding the one index (REINDEX INDEX CONCURRENTLY, the last line of the first case) brought it back to 21.4 MiB without touching the table. In this mode PostgreSQL rebuilds the index without taking any locks that prevent concurrent inserts, updates, or deletes on the table.

After the delete from the end the pages did empty out, and VACUUM deleted 2465 of 2745. But 0 reusable: they cannot take new entries yet. Why is stated in the B-tree's design notes:

implementation detail · PostgreSQL 19.0src/backend/access/nbtree/README, tag REL_19_0, section Placing deleted pages in the FSM

A deleted page can only be put in the FSM to be recycled once there is no possible scan or search that has a reference to it.

— nbtree/README, REL_19_0

The wait is implemented through snapshots: waiting until all active snapshots and registered snapshots as of the page deletion are gone. What matters is not the number of VACUUM passes but whether such snapshots are gone. Two cases: VACUUM twice with no other snapshots, and the same while another session holds open a snapshot taken after the DELETE:

measured observationbench/repack/space.py, block 1, third and fourth cases, PostgreSQL 19.0.
  at the end again, VACUUM twice before the INSERT
    freshly loaded                               rows  1000000   table  128.1 MiB   s_pkey  21.4 MiB
    after DELETE                                 rows   100000   table  128.1 MiB   s_pkey  21.4 MiB
    after VACUUM                                 rows   100000   table   12.8 MiB   s_pkey  21.4 MiB
      VACUUM VERBOSE: index "s_pkey": pages: 2745 in total, 2465 newly deleted, 2465 currently deleted, 0 reusable
    after the second VACUUM                      rows   100000   table   12.8 MiB   s_pkey  21.4 MiB
      VACUUM VERBOSE: index "s_pkey": pages: 2745 in total, 0 newly deleted, 2465 currently deleted, 2465 reusable
    after INSERT of as many new rows             rows  1000000   table  128.1 MiB   s_pkey  21.5 MiB
  at the end, VACUUM twice, another session holds a snapshot taken after the DELETE
    freshly loaded                               rows  1000000   table  128.1 MiB   s_pkey  21.4 MiB
    after DELETE                                 rows   100000   table  128.1 MiB   s_pkey  21.4 MiB
    after VACUUM                                 rows   100000   table   12.8 MiB   s_pkey  21.4 MiB
      VACUUM VERBOSE: index "s_pkey": pages: 2745 in total, 2465 newly deleted, 2465 currently deleted, 0 reusable
    after the second VACUUM                      rows   100000   table   12.8 MiB   s_pkey  21.4 MiB
      VACUUM VERBOSE: index "s_pkey": pages: 2745 in total, 0 newly deleted, 2465 currently deleted, 0 reusable
    snapshot closed, after the third VACUUM      rows   100000   table   12.8 MiB   s_pkey  21.4 MiB
      VACUUM VERBOSE: index "s_pkey": pages: 2745 in total, 0 newly deleted, 2465 currently deleted, 2465 reusable
    after INSERT of as many new rows             rows  1000000   table  128.1 MiB   s_pkey  21.5 MiB

With no other snapshots the second VACUUM made all 2465 pages available for new entries, and the index did not grow after the insert. With the snapshot the second pass released none: the snapshot existed when the pages were deleted. Only after the snapshot was closed did the third pass free them. A long report or a forgotten transaction nearby holds deleted index pages just as it holds dead row versions.

In a working database autovacuum passes over the table again and again, so deleted index pages do eventually take new entries, as long as snapshots are not held for long. But they stay in the index file, just as free pages stay in the table file: only rebuilding the index gives them back to the system. For a table with a growing key and old rows deleted in a scattered way, the index bloats even while the table reuses its own space.

fillfactor and the price of an update

Update every row once, with no vacuum in between. How much space a page keeps free on insert is set by fillfactor:

measured observationbench/repack/versions.py, block 3, PostgreSQL 19.0.
3. UPDATING EVERY ROW ONCE: TABLE SIZE AND HOT SHARE
----------------------------------------------------
100000 rows (id int primary key, v int, note text of 60 chars); one UPDATE of v per row,
in batches of 1000 rows; no VACUUM in between; sizes are the main fork only, MiB = 1024 * 1024 bytes
  fillfactor table before MiB  after MiB  pkey before MiB  after MiB  HOT updates
         100              9.6       19.1              2.2        4.3 1987/100000 (2%)
          90             10.7       20.0              2.2        4.3 12750/100000 (13%)
          50             19.5       19.5              2.2        2.2 100000/100000 (100%)

At fillfactor 100 there is no room on the page, the new version moves to another page, and HOT happens 2% of the time: the table doubled, and so did the index, even though the indexed column never changed. fillfactor 90 changed little: the 10% left free was enough for 13% of the rows. Only fillfactor 50 gave HOT to every update — at the price of a table twice as large from the start.

The lesson is not to set fillfactor to 50. Free space on a page pays off when only a small share of a page's rows is updated between vacuums and VACUUM keeps freeing space behind them.

Bloat is not always a disease

The documentation states the goal of routine vacuuming differently from how it is usually understood: the idea is not to keep tables at their minimum size, but to maintain steady-state usage of disk space.

A check: 200,000 rows; each round updates a random fifth of them, then runs VACUUM. First from a freshly loaded table, then the same after REPACK:

measured observationbench/repack/space.py, block 2, PostgreSQL 19.0. The same random seed in both series.
2. STEADY UPDATES: THE TABLE GROWS BACK TO THE SAME SIZE
--------------------------------------------------------
200000 rows; each round updates a random 20% of rows (column v, no index on it),
then runs VACUUM; the same seed in both series
  from a freshly loaded table
    round  table MiB  s_pkey MiB
        0       25.6         4.3
        1       27.1         4.3
        2       27.1         4.3
        3       27.1         4.3
        4       27.1         4.3
        5       27.4         4.3
        6       27.4         4.3
        7       27.4         4.3
        8       27.4         4.3
  after REPACK s, same workload again
    round  table MiB  s_pkey MiB
        0       25.6         4.3
        1       28.0         4.3
        2       28.0         4.3
        3       28.0         4.3
        4       28.0         4.3
        5       28.0         4.3
        6       28.0         4.3
        7       28.0         4.3
        8       28.0         4.3

Under this load the table reaches 27–28 MiB in the very first round and grows no further: VACUUM frees space and updates take it. REPACK brought the table back to 25.6 MiB, and one round later it was 28.0 again. Rewriting such a table is work that is undone in minutes, and the documentation reaches the same conclusion: there is not much point in this if the table will just grow again in the future.

A rewrite pays off when the bloat is the trace of a one-off event, after which the table will not get back to its old size on its own:

  • a mass delete or archiving of old rows, after which the table will live smaller;
  • a long transaction during which vacuum could remove nothing and the table grew several times over — such a case is taken apart in the article on a job queue on PostgreSQL;
  • a mass update, such as filling in a new column, after which half the file is holes left by old versions.

A steady size is an argument against rewriting the table on a schedule, but not proof that the extra space costs nothing. Here the table holds 28.0 MiB against 25.6 after a rewrite: about a tenth to spare. Under another load the slack can be several times larger, and then you pay for it in extra pages to read, cache space and backup volume. The decision depends on what exactly has bloated and why:

what you seewhat to do
the table holds the same size under steady loaddo not rewrite; if the slack is large, tune autovacuum and fillfactor
only an index is bloated: scattered deletes under a growing key, as aboveREINDEX INDEX CONCURRENTLY — one index is rebuilt, the table is not touched
a one-off event: a mass delete, a long transaction, a new column filled inREPACK (CONCURRENTLY), with the preparation from the end of the article
the whole contents of a table or a whole partition are being removedTRUNCATE or dropping the partition, if their behaviour fits: there is nothing to rewrite

VACUUM FULL, CLUSTER and REPACK are one operation

language contractPostgreSQL 19 Release Notes; VACUUM — FULL

The PostgreSQL 19 release notes explain the new command like this:

Add REPACK command which replaces VACUUM FULL and CLUSTER (Antonin Houska). The two former commands did similar things, but with confusing names, so unify them as REPACK. The old commands have been retained for compatibility.

— PostgreSQL 19 Release Notes

The VACUUM page calls FULL deprecated and says it makes VACUUM behave like REPACK without a USING INDEX clause. REPACK … USING INDEX is the former CLUSTER: the same rewrite, with rows laid out in index order.

All three commands do one thing: read the live row versions, write them to a new file, build the indexes anew, swap the old files for the new ones and delete the old ones. Hence two costs common to all of them: for the duration of the run you need room for another copy of the table and its indexes, and the whole new table goes into the write-ahead log.

Before PostgreSQL 19 there was no built-in command that compacts a table without a long lock. Outside the core, the pg_repack extension has done this for a long time: a similar idea, but a separate project with its own limits. Everything below about REPACK (CONCURRENTLY) applies to the built-in command and does not carry over to the extension.

A bloated table of a million rows — each row updated twice without vacuum, then VACUUM: 128 MiB of live data in a 384 MiB file. Alongside, a reader and a writer, each sending one statement every 5 ms:

measured observationbench/repack/repack.py, block 1, PostgreSQL 19.0. Peak space from pg_database_size every 200 ms; latency is the time of one statement as the client saw it, which includes both waiting for a lock and the execution itself.
commandran, stable, MiBpeak space, MiBWAL, MiBslowest reader statement, mswriter, ms
VACUUM FULL1.17384.2 → 128.2+148.9146.411661164
REPACK1.16384.2 → 128.2+149.4146.4887890
REPACK (CONCURRENTLY)1.20384.2 → 128.5+137.4166.9569

The space result is the same: 384.2 MiB became about 128, and the index went from 42.9 MiB to 21.4. Peak space for the run is one more copy of the table with its index.

The difference is in the last two columns. Under VACUUM FULL the reader and the writer each sent a statement and got no answer for 1.17 s — the command's whole run. Under REPACK without CONCURRENTLY, about 0.89 s out of 1.16. Under REPACK (CONCURRENTLY) the slowest read took 5 ms and the slowest write 69 ms. In all three cases the writer checked that nothing was lost: the sum of the balance column grew by exactly the number of its commits.

One run is one observation. The same experiment, repeated five times for each command, with the table built anew before every run:

measured observationbench/repack/repack.py, block 7, PostgreSQL 19.0. Median and the spread from minimum to maximum.
7. REPEATS: HOW MUCH THE NUMBERS OF BLOCK 1 MOVE
------------------------------------------------
the block 1 run repeated 5 times for each command, the table rebuilt before every run;
median [min - max]
  command                            took s      ACCESS EXCL s        reader max ms        writer max ms
  VACUUM FULL            1.20 [1.15 - 1.32] 1.20 [1.15 - 1.31]   1199 [1151 - 1313]   1200 [1150 - 1315]
  REPACK                 1.09 [1.03 - 1.26] 0.85 [0.75 - 0.98]      842 [753 - 982]      841 [750 - 979]
  REPACK (CONCURRENTLY)  1.16 [1.02 - 1.28] 0.00 [0.00 - 0.01]            3 [2 - 3]         27 [25 - 99]

The times move by tenths of a second, and a write next to CONCURRENTLY takes anywhere from 25 to 99 ms. The order of magnitude does not change from run to run: under VACUUM FULL the neighbours stand still for the whole run, under plain REPACK for most of it, under CONCURRENTLY for milliseconds.

What CONCURRENTLY does

language contractPostgreSQL 19, REPACK — Notes on Concurrent Operation

When the CONCURRENTLY option is specified, the bulk of the operation is run with SHARE UPDATE EXCLUSIVE lock, and the ACCESS EXCLUSIVE lock is only acquired during the final phase to swap the table and index files. The data changes that took place during the creation of the new table and index files are captured using logical decoding and applied before the ACCESS EXCLUSIVE lock is requested. Once that lock is obtained, a final pass over any remaining captured concurrent data changes is done and the files are swapped. Thus the lock is typically held for a short time, depending on the amount of changes accumulated while the lock was being waited for.

— PostgreSQL 19, REPACK

Phase by phase: a copy of the table → indexes on the copy → applying the changes captured meanwhile (catch-up) → requesting ACCESS EXCLUSIVE → a last pass over the remaining changes → the file swap. What keeps the lock short is not the swap itself but the fact that almost everything has been applied by the time it is requested. How long it is held depends on how many changes are left — the documentation promises no fixed time.

SHARE UPDATE EXCLUSIVE is the same mode plain VACUUM takes. It protects a table against concurrent schema changes and VACUUM runs and does not conflict with reads and writes. ACCESS EXCLUSIVE conflicts with locks of all modes, including the simplest read.

Here is how it looks phase by phase. The phase is what the command reports about itself in pg_stat_progress_repack; the lock column is how many seconds the observer, looking at pg_locks every 10 ms, saw the command holding each lock within that row; on the right, how many reader and writer statements started within the row and how long the slowest of them took:

measured observationbench/repack/repack.py, block 2, PostgreSQL 19.0. Locks are sampled every 10 ms: the short file swap under CONCURRENTLY did not land in the sample. A row lasts until the next phase seen or until the command returned.
2. PHASE BY PHASE: WHICH LOCK, AND WHAT THE READER AND THE WRITER GOT
---------------------------------------------------------------------
phase = pg_stat_progress_repack.phase as the observer saw it, time from the start of the command;
a row lasts until the observer saw the next phase, or until the command returned;
lock = how long this session was seen holding each lock on acc within that row (sampled);
reader / writer = statements that started within that row: how many, and the slowest of them
  VACUUM FULL
     from s    to s  phase                      lock on acc, s                                            reader n/max ms  writer n/max ms
       0.00    0.01  (before the first sample)  -                                                                  1/1166           1/1164
       0.01    0.54  seq scanning heap          AccessExclusiveLock 0.53                                              0/-              0/-
       0.54    1.17  rebuilding index           AccessExclusiveLock 0.63, ShareLock 0.35                              1/0              0/-
  REPACK
     from s    to s  phase                      lock on acc, s                                            reader n/max ms  writer n/max ms
       0.00    0.00  (before the first sample)  -                                                                     0/-            1/890
       0.00    0.54  seq scanning heap          AccessExclusiveLock 0.54                                            1/887              0/-
       0.54    1.16  rebuilding index           AccessExclusiveLock 0.36, ShareLock 0.36                             54/1            26/34
  REPACK (CONCURRENTLY)
     from s    to s  phase                      lock on acc, s                                            reader n/max ms  writer n/max ms
       0.00    0.01  (before the first sample)  -                                                                     1/0              1/1
       0.01    0.02  initializing               ShareUpdateExclusiveLock 0.01                                         2/0              3/2
       0.02    0.63  seq scanning heap          ShareUpdateExclusiveLock 0.61                                       122/4           116/12
       0.63    1.20  rebuilding index           ShareUpdateExclusiveLock 0.31                                       115/5            83/69

Under VACUUM FULL and plain REPACK, while the lock was held, the reader and the writer stood still on their very first statement. Under CONCURRENTLY about two hundred statements of each went through in the same phases, the slowest being the writer's 69 ms.

Plain REPACK lets the neighbours go before it returns

The rebuilding index row of plain REPACK shows something odd: the observer saw ACCESS EXCLUSIVE for 0.36 s out of 0.62, and 54 reader and 26 writer statements went through in that row without waiting. The lock is gone while the command is still running. VACUUM FULL does not do this: its lock is held until the very return. The same measurement at three table sizes:

measured observationbench/repack/repack.py, block 8, PostgreSQL 19.0. «Neighbours resumed» is when the first statement the command had held up for more than 50 ms completed.
8. VACUUM FULL AND PLAIN REPACK: WHEN THE NEIGHBOURS MOVE AGAIN
---------------------------------------------------------------
the same reader and writer; 'neighbours resumed' = the moment the first statement that had been
blocked by the command (took over 50 ms) completed, from the start of the command; 'returned' =
when the command returned to its client; ACCESS EXCLUSIVE = sampled time this session held it;
old files = heap, TOAST, FSM, VM and index of acc before the command; MiB = 1024 * 1024 bytes
      rows  old files MiB command       ACCESS EXCL s  neighbours resumed s  returned s  gap s
   1000000          427.2 VACUUM FULL            1.19                  1.20        1.20   0.00
   1000000          427.2 REPACK                 0.87                  0.88        1.12   0.24
   2000000          854.3 VACUUM FULL            2.66                  2.66        2.66  -0.00
   2000000          854.3 REPACK                 2.31                  2.31        2.85   0.54
   4000000         1708.5 VACUUM FULL            6.11                  6.11        6.11  -0.00
   4000000         1708.5 REPACK                 4.53                  4.54        5.57   1.03

Under VACUUM FULL the neighbours move on at the same moment the command returns. Under plain REPACK there is a gap between the two, and it grows with the size of the old files: 0.24, 0.54 and 1.03 s for 427, 854 and 1709 MiB. So under plain REPACK the neighbours' stall is shorter than the command itself.

The explanation is in the source. Plain REPACK takes its lock for the transaction, and the lock is released at commit. And at commit the old files are deleted only after the locks are released:

implementation detail · PostgreSQL 19.0src/backend/access/transam/xact.c, CommitTransaction, lines 2496–2511, tag REL_19_0

Since this may take many seconds, also delay until after releasing locks.

— xact.c, REL_19_0

VACUUM FULL additionally takes a session-level lock on top of the transaction one (LockRelationIdForSession, vacuum.c, line 2203) and releases it only after the commit (line 2374) — that is, after the files are deleted. That is why the neighbours of VACUUM FULL wait out that time too, and the neighbours of REPACK do not. The measurement itself shows only the gap and how it grows with the size of the old files; it does not time the file deletion separately.

Logical decoding switches itself on

CONCURRENTLY gets the changes made during the copy from the log through logical decoding, which needs the log written at the logical level. The default is wal_level = replica, and PostgreSQL 19 raises the level on its own: The system automatically increases the effective WAL level to logical when creating the first logical replication slot, and decreases it back to replica when dropping or invalidating the last logical replication slot. The run shows it: effective_wal_level was replica, became logical 0.01 s after the command started and went back to replica at 0.94 s. If the server already has logical replication slots, the level is logical anyway and there is no switch.

How much WAL the command itself costs is visible with no load alongside, when nothing but the command writes to the log:

measured observationbench/repack/repack.py, block 10, PostgreSQL 19.0.
10. WAL WRITTEN WITH NOTHING ELSE RUNNING
-----------------------------------------
the same bloated table, no reader, no writer, no other session; WAL = pg_current_wal_lsn() before
and after the command; 5 runs each, median [min - max]; MiB = 1024 * 1024 bytes
  VACUUM FULL            146.3 [146.3 - 146.3] MiB
  REPACK                 146.3 [146.3 - 146.3] MiB
  REPACK (CONCURRENTLY)  165.0 [165.0 - 165.2] MiB

On this table CONCURRENTLY writes about 19 MiB more than VACUUM FULL and plain REPACK. The measurement covers only the WAL generated on the primary; it does not measure shipping to replicas or how long they take to replay it. Replicas receive the same WAL, so their link pays the price too.

How long the table is closed, and its size

The main difference shows not on one table but on several. The same bloated table at 1, 2 and 4 million rows, the same load alongside:

measured observationbench/repack/repack.py, block 6, PostgreSQL 19.0. ACCESS EXCL is the time the observer saw this lock (sampled every 10 ms); on the right, the slowest statement alongside.
6. TABLE SIZE: WHAT GROWS WITH IT AND WHAT DOES NOT
---------------------------------------------------
the same bloated table at three sizes, the same reader and writer; reader / writer max = the
slowest statement of each while the command ran, as the client saw it; ACCESS EXCLUSIVE = sampled
time this session held it; MiB = 1024 * 1024 bytes
      rows  table MiB command                 took s  ACCESS EXCL s  reader max ms  writer max ms
   1000000      384.2 VACUUM FULL               1.30           1.29           1299           1297
   1000000      384.2 REPACK (CONCURRENTLY)     2.02           0.01              5             56
   2000000      768.3 VACUUM FULL               3.07           3.07           3067           3067
   2000000      768.3 REPACK (CONCURRENTLY)     2.85           0.01              4             49
   4000000     1536.7 VACUUM FULL               5.66           5.66           5661           5662
   4000000     1536.7 REPACK (CONCURRENTLY)     6.71           0.01             12            106

Under VACUUM FULL the stall equals the run time and grows with the table: 1.3, 3.1, 5.7 s. On this machine that is 3.5 to 4.1 s per gibibyte of bloated table, and the repeats in block 7 show the figure moves from run to run. If the stall keeps growing in proportion — measured up to 1.5 GiB — then for a table of a hundred gigabytes that is minutes. Under CONCURRENTLY the slowest statement alongside took 4–12 ms on reads and 49–106 ms on writes at all three sizes. The exclusive lock barely shows up in a 10 ms sample.

This is an observation, not a guarantee. The time under the exclusive lock depends on how many changes are left to apply when the lock is obtained. The same REPACK (CONCURRENTLY), but now three more writers send UPDATEs back to back:

measured observationbench/repack/repack.py, block 9, PostgreSQL 19.0.
9. HEAVY WRITES DURING THE COPY
-------------------------------
REPACK (CONCURRENTLY) acc with the usual reader and writer, then again with 3 more writers that
send UPDATEs back to back with no pause; changes = writer commits while the command ran;
phases as the observer saw them; ACCESS EXCLUSIVE = sampled time this session held it

  usual load
    command ran 1.18 s; changes while it ran 194
    phases: initializing 0.01 s, seq scanning heap 0.62 s, rebuilding index 0.28 s, catch-up 0.27 s
    held: ShareUpdateExclusiveLock 0.92 s
    reader: max 6 ms, p99 3.4 ms; usual writer: max 44 ms, p99 39.4 ms
    sum(balance): 0 -> 2084, commits of all writers 2084: every change kept

  +3 writers at full speed
    command ran 1.69 s; changes while it ran 2605
    phases: initializing 0.03 s, seq scanning heap 1.02 s, rebuilding index 0.31 s, catch-up 0.05 s, performing final cleanup 0.28 s
    held: ShareUpdateExclusiveLock 1.42 s, AccessExclusiveLock 0.01 s
    reader: max 10 ms, p99 3.0 ms; usual writer: max 73 ms, p99 25.5 ms
    sum(balance): 0 -> 52511, commits of all writers 52511: every change kept

There were 2605 changes during the run instead of 194, and the command ran 1.69 s instead of 1.18 — the copy and the catch-up share the CPU with the writers. The usual writer's slowest statement took 73 ms, the reader's 10 ms. No change was lost. Two cores leave no room to push writes harder on this machine; on a server where orders of magnitude more changes pile up during the copy, the last pass under the lock will be longer.

As long as nothing gets in its way, this is what CONCURRENTLY promises: how long the table is closed barely depends on its size. What follows is about what can get in its way.

Where CONCURRENTLY still stops the service

A long transaction that has read the table

The file swap needs ACCESS EXCLUSIVE, and that conflicts even with the ACCESS SHARE held by any transaction that has read the table even once — until that transaction ends. The documentation says where the command will wait for it: the catch-up phase also covers waiting for the ACCESS EXCLUSIVE lock needed to swap the files.

The experiment: next to the same load, a transaction opens, reads one row of the table and stays open for 6 s. For VACUUM FULL it opens a second before the command; for CONCURRENTLY, as soon as the command starts copying:

measured observationbench/repack/repack.py, block 3, PostgreSQL 19.0. The reader and the writer each have one connection: each waits for its statement and does not send the next.
3. A LONG TRANSACTION NEXT TO THE REWRITE
-----------------------------------------
same reader and writer as in block 1; 'a reader' = a transaction that read one row of acc
and stays open, holding ACCESS SHARE on acc; 'a writer elsewhere' = a transaction that inserted
one row into another table (so it has a transaction id) and stays open; 'a SHARE UPDATE EXCLUSIVE
holder' = a transaction that took that lock on acc, as a running VACUUM or CREATE INDEX
CONCURRENTLY would; it opens 1 s before the command, or as soon as the command enters the phase
'seq scanning heap'; MiB = 1024 * 1024 bytes

  VACUUM FULL; a reader, shift -1 s, open 6 s
    command ran 6.07 s; table after it 128.2 MiB
    phases: initializing 0.01 s, seq scanning heap 0.48 s, rebuilding index 0.58 s
    held: AccessExclusiveLock 1.06 s, ShareLock 0.34 s
    waited for: AccessExclusiveLock 5.01 s
    reader: max 6072 ms, p99 6071.6 ms, statements 1, errors 0
    writer: max 6071 ms, p99 6070.7 ms, statements 1, errors 0

  REPACK (CONCURRENTLY); a reader, opens when the copy starts, open 6 s
    command ran 6.33 s; table after it 128.2 MiB
    phases: initializing 0.01 s, seq scanning heap 0.60 s, rebuilding index 0.31 s, catch-up 5.10 s, performing final cleanup 0.30 s
    held: ShareUpdateExclusiveLock 6.04 s, AccessExclusiveLock 0.01 s
    waited for: AccessExclusiveLock 5.10 s
    reader: max 5104 ms, p99 2.3 ms, statements 246, errors 0
    writer: max 5106 ms, p99 35.2 ms, statements 207, errors 0

VACUUM FULL waited 5.01 s for its lock — and all that time the reader and the writer stood behind it, though they do not conflict with the long transaction themselves: a read is compatible with a read. That is how the lock queue works: a statement waiting for ACCESS EXCLUSIVE is first in line, and everyone who arrives after it waits along with it. A stall of 6.1 s instead of 1.2.

CONCURRENTLY behaved the same, only at the end. The copy and the index rebuild went through under load without delays, and then the command spent 5.10 s in catch-up waiting for the lock to swap the files, and the slowest reader statement took 5104 ms, the slowest writer statement 5106 ms. The promise of "no blocking of reads and writes" is not kept here, and that is not a bug but a direct consequence of the file swap needing an exclusive lock.

The p99 in the record is small because each client has one connection: it waited for one statement, not a hundred. A service with a connection pool piles every statement on the table into that same queue during those 5 s and uses up the whole pool with them — what happens next is taken apart in the article on connection pools.

Who holds a table for a long time in everyday life: a report or an analytic query, a manual session with an open BEGIN, a dump. pg_dump takes shared table locks at the beginning of the dump and holds them until the dump ends — so it will play the long reader for every table it dumps. pg_dump itself was not run here; this follows from its documentation and from the experiment above.

A long writing transaction delays the start, not the load

The second point of waiting is at the start. For CONCURRENTLY the initializing phase waits for the transactions that have been assigned a transaction ID to end, including ones that started while this wait was in progress. Any transaction that has written something gets an ID — in any table, not necessarily this one. The experiment: a transaction inserts a row into another table and stays open for 6 s:

measured observationbench/repack/repack.py, block 3, fourth case, PostgreSQL 19.0.
  REPACK (CONCURRENTLY); a writer elsewhere, shift -1 s, open 6 s
    command ran 6.17 s; table after it 128.5 MiB
    phases: initializing 5.01 s, seq scanning heap 0.61 s, rebuilding index 0.55 s
    held: ShareUpdateExclusiveLock 5.90 s, AccessExclusiveLock 0.01 s
    reader: max 5 ms, p99 1.3 ms, statements 1233, errors 0
    writer: max 63 ms, p99 9.2 ms, statements 1192, errors 0

The command spent 5.01 s in initializing — exactly until that transaction ended. But all that time it held only SHARE UPDATE EXCLUSIVE, and the slowest statement alongside took 5 ms on reads and 63 ms on writes. It is a delay for the command, not for the service. One caveat: the same lock conflicts with VACUUM, so autovacuum of this table waits all that time.

lock_timeout limits waiting, not work

The natural defence is not to wait for the lock longer than a second: lock_timeout will Abort any statement that waits longer than the specified amount of time while attempting to acquire a lock. The limit applies to each wait for a lock separately. It does not limit how long the command holds a lock it has already obtained, nor how long it runs as a whole. The overall limit is statement_timeout, which will Abort any statement that takes more than the specified amount of time, but it cancels the command together with all the work done and does not suit a long copy.

With SET lock_timeout = '1s' before the command — three cases from the same block: a long reader, a writing transaction in another table, and a transaction holding SHARE UPDATE EXCLUSIVE on the table, as a running VACUUM or CREATE INDEX CONCURRENTLY would:

measured observationbench/repack/repack.py, block 3, third, fifth and sixth cases, PostgreSQL 19.0.
  same, with lock_timeout = 1s   -> LockNotAvailable: canceling statement due to lock timeout
    command ran 1.90 s; table after it 384.2 MiB
    phases: initializing 0.01 s, seq scanning heap 0.55 s, rebuilding index 0.31 s, catch-up 1.02 s
    held: ShareUpdateExclusiveLock 1.88 s
    waited for: AccessExclusiveLock 1.00 s
    reader: max 999 ms, p99 2.2 ms, statements 181, errors 0
    writer: max 1003 ms, p99 7.8 ms, statements 177, errors 0
  same, with lock_timeout = 1s   -> LockNotAvailable: canceling statement due to lock timeout
    command ran 1.02 s; table after it 384.2 MiB
    phases: initializing 1.02 s
    held: ShareUpdateExclusiveLock 1.01 s
    reader: max 1 ms, p99 0.7 ms, statements 203, errors 0
    writer: max 2 ms, p99 1.8 ms, statements 203, errors 0
  REPACK (CONCURRENTLY); a SHARE UPDATE EXCLUSIVE holder, shift -1 s, open 6 s, lock_timeout = 1s   -> LockNotAvailable: canceling statement due to lock timeout
    command ran 1.00 s; table after it 384.2 MiB
    phases: none seen
    waited for: ShareUpdateExclusiveLock 1.00 s
    reader: max 1 ms, p99 0.4 ms, statements 200, errors 0
    writer: max 3 ms, p99 1.8 ms, statements 201, errors 0

The stall is capped at a second in all three cases. But when the refusal comes depends on what the command was waiting for:

  • next to a long reader — after the copy and the index rebuild, while waiting for the lock to swap the files. The table stayed at 384.2 MiB and the work was lost: 0.86 s on this table, an hour on a table that takes an hour to copy, and the retry starts from scratch;
  • next to a writing transaction — right at the start, in initializing: the wait for other transactions to end obeys lock_timeout too. The table was not touched and the neighbours noticed nothing;
  • next to someone else's SHARE UPDATE EXCLUSIVE — earlier still: the command did not get even its first lock, and no phase was seen at all.

Hence the order of things. First make sure there are no long transactions nearby that have touched the table, and no writing transactions at all — by xact_start and backend_xid in pg_stat_activity and by pg_locks. Then run with lock_timeout, so that somebody's report arriving during the copy does not turn into a stall. And be ready to retry. Do not promise a deadline for the whole operation on the strength of lock_timeout — it limits only the waits.

A snapshot taken before the rewrite sees an empty table

language contractPostgreSQL 19, MVCC — Caveats; REPACK — Notes on Concurrent Operation

The REPACK documentation puts this in a warning:

REPACK with the CONCURRENTLY option is not MVCC-safe. After the repacking transaction commits, the table will appear empty to concurrent transactions, if they are using a snapshot taken before repacking started.

— PostgreSQL 19, REPACK

And it narrows down who is affected: a transaction that did not access the table in question before the command started. One that did holds ACCESS SHARE, and the command waits for it, as in the experiment above.

The check, step by step. Session B opens a REPEATABLE READ transaction, and its first statement reads another table — so the snapshot is taken while acc is left untouched. A third session counts the rows of acc ("before"), session A compacts acc, and session B counts the rows of acc in the same transaction ("B after"). At the end a new session counts the rows once more. The second part is the control: B's very first statement reads acc itself:

measured observationbench/repack/repack.py, block 4, PostgreSQL 19.0.
4. A SNAPSHOT TAKEN BEFORE THE REWRITE
--------------------------------------
step 1: session B runs BEGIN ISOLATION LEVEL REPEATABLE READ and SELECT count(*) FROM other;
        that first statement takes B's snapshot without touching acc
step 2: a third session counts acc ('before'); session A shrinks acc
step 3: B counts acc inside the same transaction ('B after'); B ends; a new session counts acc
  command in A                before   B after  new session
  VACUUM FULL                1000000   1000000      1000000
  REPACK                     1000000   1000000      1000000
  REPACK (CONCURRENTLY)      1000000         0      1000000
control: B's first statement is SELECT count(*) FROM acc itself, so B holds ACCESS SHARE on acc;
A starts REPACK (CONCURRENTLY) acc; 3 s later B counts acc again and commits
  B first: 1000000; B again after 3 s: 1000000; command finished before B committed: no; B committed at 3.07 s, command took 3.37 s; a new session then: 1000000

After CONCURRENTLY, transaction B sees zero rows in the table. There is no error: from the server's point of view it is a correct answer for its snapshot. The data is not lost: a new session sees a million. After VACUUM FULL and plain REPACK the same transaction B sees a million.

The control shows the other side of the same caveat. When B read acc with its very first statement, it holds ACCESS SHARE, and the command cannot finish while B is open: B committed at 3.07 s, the command returned at 3.37 s, and both counts inside B gave a million. Only a transaction that took its snapshot before the command without touching the table, and read it after the command finished, sees an empty table.

Where this is dangerous: a long REPEATABLE READ report that reconciles several tables and reaches this one later; a dump or a data migration that reads tables one after another in one snapshot. Such a process will not fail — it will silently get an empty table and, say, write a total without it. That is why CONCURRENTLY is not run while such processes are working — all the more so because if they have already read the table, the command will wait for them at the file swap anyway.

When CONCURRENTLY is not allowed

measured observationbench/repack/repack.py, block 5, PostgreSQL 19.0. Error code, message and, where present, DETAIL and HINT — as the server returned them.
5. WHERE CONCURRENTLY IS REFUSED
--------------------------------
  no primary key                       55000 cannot execute REPACK (CONCURRENTLY) on relation "x" | DETAIL: Relation "x" has no identity index.
  unique index, no replica identity    55000 cannot execute REPACK (CONCURRENTLY) on relation "x" | DETAIL: Relation "x" has no identity index.
  REPLICA IDENTITY USING INDEX         ok
  REPLICA IDENTITY FULL, no key        55000 cannot execute REPACK (CONCURRENTLY) on relation "x" | DETAIL: This operation does not support tables with REPLICA IDENTITY FULL.
  UNLOGGED table                       55000 cannot execute REPACK (CONCURRENTLY) on relation "x" | DETAIL: This operation is only supported for permanent relations.
  partitioned table                    0A000 REPACK (CONCURRENTLY) is not supported for partitioned tables | HINT: Consider running the command on individual partitions.
  one partition of it                  ok
  inside BEGIN ... COMMIT              25001 REPACK (CONCURRENTLY) cannot run inside a transaction block
  no table name                        0A000 REPACK (CONCURRENTLY) requires an explicit table name
  plain REPACK, no primary key         ok
  plain REPACK, partitioned table      ok
  plain REPACK, an invalid index       55000 cannot execute REPACK on relation "x" | DETAIL: An invalid index cannot be processed correctly: "x_b". | HINT: Use DROP INDEX or REINDEX.
  plain REPACK, no MAINTAIN privilege  42501 permission denied for table x

The documentation states the condition like this: the command refuses if the table lacks a primary key and index-based replica identity. A unique index on its own does not help — it has to be made the replica identity (ALTER TABLE … REPLICA IDENTITY USING INDEX, an index on NOT NULL columns), and then the command goes through. REPLICA IDENTITY FULL will not do: it is not an index, and the server refuses with a reason of its own.

A table with no primary key is common among logs and staging tables, and those are exactly the tables that bloat most often. Plain REPACK works on such a table, but with an exclusive lock for the whole run. CONCURRENTLY will not take a partitioned table as a whole, but it takes one partition at a time, and a partition is usually smaller than the whole table. Plain REPACK accepts a partitioned table and goes through all its partitions.

Refusals are not limited to CONCURRENTLY. An invalid index — say, one left over from a failed CREATE UNIQUE INDEX CONCURRENTLY — stops plain REPACK too, and the server suggests dropping or rebuilding the index. Only someone with the MAINTAIN privilege on the table can compact it: without it you get permission denied.

The remaining limits from the documentation were not tested here:

  • CONCURRENTLY does not work for system catalogs and TOAST tables, for tables whose access method is not heap, and for tables with the user_catalog_table parameter;
  • no more than max_repack_replication_slots commands with CONCURRENTLY can run at once — 5 by default, and the parameter changes only with a server restart;
  • if more than about 104 million rows are updated or deleted during the run, the command fails; the memory for each changed row is not limited by maintenance_work_mem;
  • the changes themselves, except unmodified TOAST columns, are stored on disk separately — space on top of the table copy;
  • CONCURRENTLY might fail to complete if DDL commands are executed on the table by other transactions.

One more consequence concerns not this table but all the others. For the transaction ID horizon, REPACK is considered a single long-running transaction, which prevents VACUUM from cleaning up dead rows from other tables. In the block 1 run the command's session had backend_xmin set for almost the whole run — 0.86–0.93 s out of 1.16–1.20. On a million rows that is a second; on a table that takes an hour to copy it is an hour, during which dead rows pile up in other tables. The documentation advises watching the backend_xid of the REPACK session. REPACK does not replace wraparound maintenance — that is what VACUUM is for.

What to configure and what to watch

  1. First find out whether a rewrite is needed. If a table under steady load holds its size, compaction will be undone in minutes: treat the cause — long transactions, infrequent autovacuum — not the size. If only an index has bloated, REINDEX INDEX CONCURRENTLY is enough. Rewrite the table after a one-off event.
  2. Check that CONCURRENTLY applies: a primary key or an index made the replica identity; a regular (not UNLOGGED) table with the heap access method; for a partitioned table, partition by partition; no invalid indexes; the MAINTAIN privilege; a free slot within max_repack_replication_slots.
  3. Check the space. For the run you need room for another copy of the table with all its indexes, plus the changes accumulated during the run, plus the WAL of the whole new table — on the replicas too. With USING INDEX a temporary sort file of up to the table's size may be needed as well.
  4. Get rid of long transactions before starting. Check pg_stat_activity: transactions with an old xact_start, especially those holding locks on this table (pg_locks), writing transactions (backend_xid) and dumps. A writing transaction will delay the start; a long reader will stop the service at the end.
  5. Do not run it next to reports in one snapshot. A transaction that took its snapshot before the command and had not touched the table will see it empty afterwards.
  6. Run with lock_timeout. It limits each wait for a lock, not the duration of the operation: the refusal can come at the start or after the whole copy, and then the retry starts from scratch. That is why step 4 matters more.
  7. Watch during the run: the phase in pg_stat_progress_repack (catch-up lasting longer than seconds means the command is waiting for the lock), the queue behind it in pg_locks, the backend_xid of the command's session and dead rows in other tables. The command can be cancelled at any moment — the table stays as it was.
  8. Check the result: table and index size before and after, the whole footprint by pg_total_relation_size, query latency on the table.

What to measure in production

whatwhere fromwhat it shows
table and index sizepg_relation_size, pg_table_size, pg_indexes_size, pg_total_relation_sizegrowth after a one-off event versus a steady size; main fork versus the whole footprint
dead rows and vacuumingn_dead_tup, last_autovacuum in pg_stat_user_tablesvacuum cannot keep up or cannot act
long transactionsxact_start, backend_xid, backend_xmin in pg_stat_activitywho will delay the start or the file swap; the REPACK session holds the horizon itself
compaction progressphase in pg_stat_progress_repackcatch-up lasting longer than seconds — the command is waiting for the lock
the queue behind the commandpg_locks where granted = falsestatements waiting behind ACCESS EXCLUSIVE
WAL leveleffective_wal_levellogical — logical decoding is running
WAL volumepg_current_wal_lsn() before and afterthe cost of compaction for replicas and the archive

How to reproduce the numbers

Every script brings up its own PostgreSQL cluster in a temporary directory, listens only on a unix socket on port 55439 and removes the cluster after the run. Every experiment builds its table anew; the cache is warm — the data has just been written and sits in the operating system's cache.

cd bench/repack
./run.sh                 # all three scripts
./run.sh repack          # only the named ones

You need PostgreSQL 19 binaries together with the contrib modules (PGBIN, default /usr/lib/postgresql/19/bin) and Python 3 with venv; the script installs psycopg 3 into .venv next to it. Run records are in bench/repack/runs/: the header of each carries the machine, the server and client versions and the settings the numbers depend on.

The published run: PostgreSQL 19.0 built from the 19.0 source tarball (configure --without-icu --with-openssl), default settings (wal_level = replica, max_repack_replication_slots = 5, maintenance_work_mem = 64MB, shared_buffers = 128MB, autovacuum off for the experiment tables), psycopg 3.3.9 with libpq 18, Python 3.13.18; two Intel Xeon 2.10GHz cores, 7.8 GiB of memory, ext4 on a virtual disk; November 2026. Each block 1 experiment was repeated five times (block 7), the rest once. Absolute times are a property of this machine; what carries over is the shape: under VACUUM FULL the stall grows with the table, under CONCURRENTLY it does not, and a long transaction alongside delays both commands by its own length.

Measured by

The numbers in this article come from these scripts. Each opens straight from here, together with its run record: what it ran on, what came out, and with what spread.

Take to work

  • Do not rewrite a table that holds its size under steady load: in our run a table compacted to 25.6 MiB was back at 28.0 after one round of updates. A rewrite pays off after a one-off event — a mass delete, a long transaction, filling in a new column.
  • Before REPACK (CONCURRENTLY), check pg_stat_activity and pg_locks: a transaction that has read the table makes the command wait for it at the file swap, and every new statement on the table queues behind the command — 5.1 s in our run. Dumps and reports are the first suspects. During the run, watch the REPACK session itself too: for the transaction horizon it is one long transaction, and while it runs VACUUM does not remove dead rows in other tables.
  • Set lock_timeout before REPACK (CONCURRENTLY), but remember that it limits only waits for locks, not the duration of the operation. Next to a long reader the cancellation comes after the copy and the index rebuild: the table stays bloated and the retry starts from scratch. So clear out long transactions first, then run it.
  • Do not run REPACK (CONCURRENTLY) while reports or data migrations are working in one snapshot: a transaction that took its snapshot before the command and had not touched the table sees it empty afterwards, with no error. VACUUM FULL and plain REPACK do not do this.
  • Look at indexes separately from the table: with a growing key and scattered deletes of old rows, the index in our run grew from 21.4 to 40.7 MiB while the table reused its own space. Only a rebuild gets its size back, and for one index the table does not need rewriting: REINDEX INDEX CONCURRENTLY brought it back to 21.4 MiB.

Common misconceptions

Claim

“VACUUM frees disk space”

Actually

It frees space inside the file: dead versions are removed and new rows will take their place. Only empty pages at the end of the table go back to the system. In our run, after deleting 90% of the rows scattered across the table the file stayed at 128.1 MiB; after deleting them from the end, 12.8 MiB. The documentation: it will not return the space to the operating system, except in the special case where one or more pages at the end of a table become entirely free.

Claim

“A bloated table should be compacted regularly”

Actually

A table under steady updates reaches a steady size: the space VACUUM frees is taken by new versions. In our run such a table held 27–28 MiB; after REPACK it was 25.6 MiB and one round of load later 28.0 again. The documentation draws the same conclusion: there is not much point in this if the table will just grow again in the future.

Claim

“REPACK (CONCURRENTLY) never blocks reads and writes”

Actually

It does not block them while it copies. To swap the files it needs ACCESS EXCLUSIVE, and if a long transaction holds the table, the command waits for it in the catch-up phase — and every new statement on the table waits behind the command. In our run a transaction that had read one row delayed the command by 5.10 s, and the reader and the writer stood still for 5104 and 5106 ms. Without such a transaction the slowest statement alongside took no more than 106 ms — in this run, not always: under the exclusive lock the command applies whatever has piled up.

Claim

“With lock_timeout, CONCURRENTLY is safe: if it cannot get the lock it will do it later”

Actually

If it cannot get the lock, it is cancelled entirely. lock_timeout limits each wait for a lock, not the duration of the operation, and cancels the command where it waits. Next to a long reader that is the file swap at the very end: in our run with lock_timeout = 1s the command worked for 1.90 s and returned an error, and the table stayed at 384.2 MiB — all the work was lost. Next to a writing transaction the refusal came at the start, after 1.02 s, touching nothing. The stall is capped in both cases, but there is no "it will do it later".

Claim

“VACUUM FULL and REPACK are different operations”

Actually

They are one. The PostgreSQL 19 release notes: REPACK replaces VACUUM FULL and CLUSTER, and the VACUUM page calls FULL deprecated and says it behaves like REPACK without a USING INDEX clause. In our run both commands compacted the table from 384.2 to 128.2 MiB and wrote the same 146.4 MiB of WAL, keeping the table closed for the whole copy.

Claim

“REPACK (CONCURRENTLY) is MVCC-safe, since no changes are lost”

Actually

Changes are indeed not lost: the sum the writer was changing during the compaction added up in every experiment. But the documentation explicitly calls the command not MVCC-safe: a transaction with a snapshot taken before the command sees the table empty afterwards. In our run a REPEATABLE READ transaction that had read another table before counted 0 rows instead of 1000000, while a new session right after saw all 1000000. After VACUUM FULL the same transaction sees a million.

Knowledge check

Question 1 of 5

90% of the rows of a 128 MiB table were deleted in a scattered way, by id % 10 <> 0, and VACUUM ran. What will the table file be?

Sources & further reading

18 SOURCES

  1. PostgreSQL 19 — REPACKOfficial documentation. What the command does: «REPACK reclaims storage occupied by dead tuples. Unlike VACUUM, it does so by rewriting the entire contents of the table specified by table_name into a new disk file with no extra space (except for the space guaranteed by the fillfactor storage parameter), allowing unused space to be returned to the operating system». Locks: without CONCURRENTLY «an ACCESS EXCLUSIVE lock is acquired at the beginning and remains held throughout the operation»; with it «the bulk of the operation is run with SHARE UPDATE EXCLUSIVE lock, and the ACCESS EXCLUSIVE lock is only acquired during the final phase to swap the table and index files». The warning: «REPACK with the CONCURRENTLY option is not MVCC-safe». The limit: «if more than about 104 million rows are concurrently updated or deleted during the execution of REPACK, the command fails». Space: «you need free disk space at least equal to the sum of the table size and the index sizes». The same page lists the cases where CONCURRENTLY cannot be used.https://www.postgresql.org/docs/19/sql-repack.html
  2. PostgreSQL 19 — VACUUMOfficial documentation. On FULL: «This option, which is deprecated, makes VACUUM behave like REPACK without a USING INDEX clause». On plain vacuum: «Plain VACUUM (without FULL) simply reclaims space and makes it available for re-use. This form of the command can operate in parallel with normal reading and writing of the table, as an exclusive lock is not obtained. However, extra space is not returned to the operating system (in most cases); it's just kept available for re-use within the same table».https://www.postgresql.org/docs/19/sql-vacuum.html
  3. PostgreSQL 19 — Routine Vacuuming, Recovering Disk SpaceOfficial documentation. Why space is not freed at once: «In PostgreSQL, an UPDATE or DELETE of a row does not immediately remove the old version of the row». What plain VACUUM gives back: «it will not return the space to the operating system, except in the special case where one or more pages at the end of a table become entirely free and an exclusive table lock can be easily obtained». Why not keep a table minimal at all: «the idea is not to keep tables at their minimum size, but to maintain steady-state usage of disk space» and «there is not much point in this if the table will just grow again in the future». On the locks of rewriting commands: «All these options require an ACCESS EXCLUSIVE lock, except that REPACK can be run with CONCURRENTLY, in which case the ACCESS EXCLUSIVE lock is held only while swapping the table and index files».https://www.postgresql.org/docs/19/routine-vacuuming.html
  4. PostgreSQL 19 Release Notes — REPACKOfficial documentation. «Add REPACK command which replaces VACUUM FULL and CLUSTER (Antonin Houska). The two former commands did similar things, but with confusing names, so unify them as REPACK. The old commands have been retained for compatibility» and «Allow REPACK to rebuild tables without access-exclusive locking … This is enabled via the CONCURRENTLY option. Server variable max_repack_replication_slots was also added».https://www.postgresql.org/docs/19/release-19.html
  5. PostgreSQL 19 — Explicit Locking, Table-Level LocksOfficial documentation. SHARE UPDATE EXCLUSIVE «Conflicts with the SHARE UPDATE EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, and ACCESS EXCLUSIVE lock modes. This mode protects a table against concurrent schema changes and VACUUM runs». ACCESS EXCLUSIVE «Conflicts with locks of all modes», and «REPACK also acquires this lock mode. When run with CONCURRENTLY, REPACK acquires it only while swapping the table and index files».https://www.postgresql.org/docs/19/explicit-locking.html
  6. PostgreSQL 19 — MVCC, CaveatsOfficial documentation. «Some commands, currently only TRUNCATE, the table-rewriting forms of ALTER TABLE and REPACK with the CONCURRENTLY option, are not MVCC-safe. This means that after the truncation or rewrite commits, the table will appear empty to concurrent transactions, if they are using a snapshot taken before the command committed». And who is affected: «This will only be an issue for a transaction that did not access the table in question before the command started».https://www.postgresql.org/docs/19/mvcc-caveats.html
  7. PostgreSQL 19 — Progress Reporting, REPACK PhasesOfficial documentation. For CONCURRENTLY the initializing phase «waits for the transactions that have been assigned a transaction ID to end, including ones that started while this wait was in progress, so this phase can last longer than the longest transaction running when the command started». The catch-up phase «also covers waiting for the ACCESS EXCLUSIVE lock needed to swap the files, so a command blocked by a conflicting lock stays in this phase».https://www.postgresql.org/docs/19/progress-reporting.html
  8. PostgreSQL 19 — Database Page Layout, Table Row LayoutOfficial documentation. The row-version header fields that bench/repack/versions.py prints: t_xmin — «insert XID stamp», t_xmax — «delete XID stamp», t_ctid — «current TID of this or newer row version». Block 4 of the same script shows that a row lock and a rolled-back delete set t_xmax too.https://www.postgresql.org/docs/19/storage-page-layout.html
  9. PostgreSQL 19 — Heap-Only Tuples (HOT)Official documentation. The conditions for a HOT update: «The update does not modify any columns referenced by the table's indexes, not including summarizing indexes. The only summarizing index method in the core PostgreSQL distribution is BRIN» and «There is sufficient free space on the page containing the old row for the updated row». What it buys: «New index entries are not needed to represent updated rows». And how to improve the odds: «You can increase the likelihood of sufficient page space for HOT updates by decreasing a table's fillfactor». On pruning without vacuum: «When a row is updated multiple times, row versions other than the oldest and the newest can be completely removed during normal operation, including SELECTs, instead of requiring periodic vacuum operations».https://www.postgresql.org/docs/19/storage-hot.html
  10. PostgreSQL 19 — pageinspect, heap_page_itemsOfficial documentation. How bench/repack/versions.py reads the page: «heap_page_items shows all line pointers on a heap page. For those line pointers that are in use, tuple headers as well as tuple raw data are also shown. All tuples are shown, whether or not the tuples were visible to an MVCC snapshot at the time the raw page was copied».https://www.postgresql.org/docs/19/pageinspect.html
  11. PostgreSQL 19 — WAL Settings (wal_level, effective_wal_level), max_repack_replication_slots, lock_timeoutOfficial documentation. On wal_level: «when wal_level is set to replica, the effective WAL level can automatically change based on the presence of logical replication slots. The system automatically increases the effective WAL level to logical when creating the first logical replication slot, and decreases it back to replica when dropping or invalidating the last logical replication slot». On max_repack_replication_slots: «Specifies the maximum number of replication slots for use of the REPACK command. The default is 5. This parameter can only be set at server start». On lock_timeout: «Abort any statement that waits longer than the specified amount of time while attempting to acquire a lock» and «A value of zero (the default) disables the timeout».https://www.postgresql.org/docs/19/runtime-config-wal.html
  12. PostgreSQL 19 — Client Connection Defaults, statement_timeoutOfficial documentation. The overall limit on a statement: «Abort any statement that takes more than the specified amount of time». Unlike lock_timeout, it counts the whole run, not only waits for locks.https://www.postgresql.org/docs/19/runtime-config-client.html
  13. PostgreSQL 19 — REINDEXOfficial documentation. When an index rebuild is needed: «An index has become “bloated”, that is it contains many empty or nearly-empty pages». What CONCURRENTLY gives: «PostgreSQL will rebuild the index without taking any locks that prevent concurrent inserts, updates, or deletes on the table».https://www.postgresql.org/docs/19/sql-reindex.html
  14. pg_repack — an extension for repacking tablesSource. An outside project that has long compacted tables without a long exclusive lock. Mentioned only as an existing tool outside the core; its guarantees are not tested in the article and do not carry over to the built-in REPACK.https://reorg.github.io/pg_repack/
  15. PostgreSQL 19 — pg_dump, --lock-wait-timeoutOfficial documentation. What pg_dump does when it starts: «Do not wait forever to acquire shared table locks at the beginning of the dump». So a dump holds a lock on every table it dumps from start to finish — like the long reader in block 3.https://www.postgresql.org/docs/19/app-pgdump.html
  16. postgres/src/backend/commands/repack.c, tag REL_19_0 — how both modes workSource code. The comment at the top of the file: «In non-concurrent mode, it's easy: take AccessExclusiveLock, create a new transient relation, copy the tuples over to the relfilenode of the new relation, swap the relfilenodes, then drop the old relation» and «In concurrent mode, we lock the table with only ShareUpdateExclusiveLock, then do an initial copy as above. However, while the tuples are being copied, concurrent transactions could modify the table. To cope with those changes, we rely on logical decoding to obtain them from WAL». This is how version 19.0 is built, not a promise of the documentation.https://github.com/postgres/postgres/blob/REL_19_0/src/backend/commands/repack.c
  17. postgres/src/backend/access/transam/xact.c and commands/vacuum.c, tag REL_19_0 — when the lock is releasedSource code. CommitTransaction releases locks (line 2496) before it deletes the files the transaction dropped (line 2511): «Since this may take many seconds, also delay until after releasing locks». VACUUM additionally takes a session-level lock on the table (vacuum.c, line 2203, LockRelationIdForSession) and releases it after the commit (line 2374). This is how version 19.0 is built, not a promise of the documentation.https://github.com/postgres/postgres/blob/REL_19_0/src/backend/access/transam/xact.c#L2503-L2511
  18. postgres/src/backend/access/nbtree/README, tag REL_19_0 — Placing deleted pages in the FSMSource code. Why a deleted index page does not take new entries at once: «A deleted page can only be put in the FSM to be recycled once there is no possible scan or search that has a reference to it» and «We implement the technique by waiting until all active snapshots and registered snapshots as of the page deletion are gone». This is how the B-tree of version 19.0 is built, not a promise of the documentation.https://github.com/postgres/postgres/blob/REL_19_0/src/backend/access/nbtree/README