Skip to content
dbexplore

PostgreSQL 19

REPACK (CONCURRENTLY) in PostgreSQL 19

For anyone who rewrites bloated tables with VACUUM FULL, CLUSTER or pg_repack and wants to know what the in-core replacement still locks.

Reference page, revised in place. Last updated .

What to use it for, and the one thing to set first

PostgreSQL 19 folds VACUUM FULL and CLUSTER into a single command, REPACK, and gives it a CONCURRENTLY option that copies the table while reads and writes carry on. Our advice is short. Use the concurrent form on any table that is in use, and always run it with a lock_timeout. Its last step still needs the same ACCESS EXCLUSIVE lock that VACUUM FULL holds from start to finish, and while it waits for that lock, every new query on the table queues behind it.

The reference page is precise about the split. Without the option, the exclusive lock is taken at the start and held throughout. With it, the bulk of the work runs under SHARE UPDATE EXCLUSIVE, changes made in the meantime are captured through logical decoding, and the exclusive lock is taken only to swap the files. The overview at the top of the release notes describes the concurrent form as repacking without blocking reads and writes, which is true of the copy and not of the swap, and the measurement further down is the reason we side with the reference page. The change is recorded under Utility Commands in the PostgreSQL 19 release notes, where the old commands are described as retained for compatibility.

On 18 the word means nothing

REPACK (CONCURRENTLY) warehouse_events;
ERROR:  syntax error at or near "REPACK"
LINE 1: REPACK (CONCURRENTLY) warehouse_events;
        ^

The statement fails at the parser on 18, before it ever looks for the table. The version branch belongs in the job that issues the command rather than in SQL, because REPACK (CONCURRENTLY) refuses to run inside a transaction block and has to be sent as a statement of its own. A maintenance job that has to run on both majors branches on server_version_num and uses pg_repack, or a VACUUM FULL maintenance window, on 18 and earlier.

A table that lost three quarters of its rows

The fixture is a log table that had most of its rows deleted. Plain vacuum makes the space reusable inside the file, which is what it is for, and gives almost none of it back to the filesystem.

CREATE TABLE warehouse_events (event_id bigint PRIMARY KEY, payload text);
CREATE TABLE dock_doors (door_id int PRIMARY KEY, label text);
INSERT INTO warehouse_events SELECT g, repeat('w', 200) FROM generate_series(1, 200000) AS g;
INSERT INTO dock_doors SELECT g, 'door ' || g FROM generate_series(1, 12) AS g;
DELETE FROM warehouse_events WHERE event_id % 4 <> 0;
VACUUM warehouse_events;
SELECT pg_size_pretty(pg_table_size('warehouse_events'))   AS heap,
       pg_size_pretty(pg_indexes_size('warehouse_events')) AS indexes;
CREATE TABLE
CREATE TABLE
INSERT 0 200000
INSERT 0 12
DELETE 150000
VACUUM
 heap  | indexes 
-------+---------
 47 MB | 4408 kB
(1 row)
REPACK (CONCURRENTLY) warehouse_events;
SELECT pg_size_pretty(pg_table_size('warehouse_events'))   AS heap,
       pg_size_pretty(pg_indexes_size('warehouse_events')) AS indexes;
REPACK
 heap  | indexes 
-------+---------
 12 MB | 1112 kB
(1 row)

The rewrite returned roughly three quarters of the heap and of the primary key index, which is what deleting three rows in four should produce. While it ran, the server needed room for a complete second copy of the table and its indexes, and the concurrent form also writes the full row data of every change made during the copy to disk on the side. On a table that is bloated because the disk is nearly full, that arithmetic decides whether you can run it at all.

Tables it refuses

CREATE TABLE scan_audit (scanned_at timestamptz, door_id int);
REPACK (CONCURRENTLY) scan_audit;
ERROR:  cannot execute REPACK (CONCURRENTLY) on relation "scan_audit"
DETAIL:  Relation "scan_audit" has no identity index.

A table with no primary key and no index-based replica identity is refused because the change capture needs a way to find each row again. A primary key alone is not enough: we tested a table with one whose replica identity was set to FULL, then NOTHING, and both were refused. The reference page lists the others, among them materialized views, unlogged tables, partitioned tables, catalog and TOAST tables, tables using an access method other than heap, any call inside a transaction block, and any call that would need a replication slot beyond max_repack_replication_slots. Both forms refuse a table that has an invalid index until that index is dropped or rebuilt, and the concurrent form can fail to complete if other sessions run DDL on the table while it works. The plain form has fewer limits and repacks a partitioned table by repacking each of its partitions.

The lock it still needs, and who queues behind it

Three sessions take part, played here through dblink so the whole exchange fits in one block: a report that read the table inside a transaction it has not finished, the repack, and a latecomer that runs one plain SELECT after the copy is done.

CREATE EXTENSION dblink;
SELECT dblink_connect('report',    'dbname=' || current_database() || ' application_name=report'),
       dblink_connect('repack',    'dbname=' || current_database() || ' application_name=repack'),
       dblink_connect('latecomer', 'dbname=' || current_database() || ' application_name=latecomer');
SELECT dblink_exec('report', 'BEGIN');
SELECT * FROM dblink('report', 'SELECT count(*) FROM warehouse_events') AS r(rows_seen bigint);
SELECT dblink_send_query('repack', 'REPACK (CONCURRENTLY) warehouse_events');
DO $$ BEGIN
  FOR i IN 1..120 LOOP
    EXIT WHEN EXISTS (SELECT 1 FROM pg_stat_progress_repack WHERE phase = 'catch-up');
    PERFORM pg_sleep(0.25);
  END LOOP;
END $$;
SELECT dblink_send_query('latecomer', 'SELECT count(*) FROM warehouse_events');
SELECT pg_sleep(1);
SELECT a.application_name AS session, a.backend_type, a.wait_event_type, a.wait_event,
       (SELECT string_agg(b.application_name, ', ') FROM pg_stat_activity b
         WHERE b.pid = ANY (pg_blocking_pids(a.pid))) AS blocked_by
FROM pg_stat_activity a
WHERE a.datname = current_database() AND a.pid <> pg_backend_pid()
ORDER BY a.backend_start;
SELECT phase, heap_blks_scanned = heap_blks_total AS copy_finished, heap_tuples_inserted
FROM pg_stat_progress_repack;
SELECT slot_type, plugin, temporary,
       slot_name LIKE 'pg_repack_%' AS named_pg_repack,
       slot_name = 'pg_repack_' || (SELECT pid FROM pg_stat_activity
                                    WHERE backend_type = 'REPACK decoding worker') AS named_after_worker_pid,
       current_setting('wal_level') AS wal_level,
       current_setting('effective_wal_level') AS effective_wal_level
FROM pg_replication_slots;
SELECT dblink_exec('report', 'COMMIT');
SELECT * FROM dblink_get_result('repack') AS r(status text);
SELECT * FROM dblink_get_result('latecomer') AS r(rows_seen bigint);
CREATE EXTENSION
 dblink_connect | dblink_connect | dblink_connect 
----------------+----------------+----------------
 OK             | OK             | OK
(1 row)

 dblink_exec 
-------------
 BEGIN
(1 row)

 rows_seen 
-----------
     50000
(1 row)

 dblink_send_query 
-------------------
                 1
(1 row)

DO
 dblink_send_query 
-------------------
                 1
(1 row)

 pg_sleep 
----------
 
(1 row)

  session  |      backend_type      | wait_event_type |   wait_event    | blocked_by 
-----------+------------------------+-----------------+-----------------+------------
 report    | client backend         | Client          | ClientRead      | 
 repack    | client backend         | Lock            | relation        | report
 latecomer | client backend         | Lock            | relation        | repack
           | REPACK decoding worker | IPC             | WaitForWalFlush | report
(4 rows)

  phase   | copy_finished | heap_tuples_inserted 
----------+---------------+----------------------
 catch-up | t             |                50000
(1 row)

 slot_type |  plugin  | temporary | named_pg_repack | named_after_worker_pid | wal_level | effective_wal_level 
-----------+----------+-----------+-----------------+------------------------+-----------+---------------------
 logical   | pgrepack | t         | t               | t                      | replica   | logical
(1 row)

 dblink_exec 
-------------
 COMMIT
(1 row)

 status 
--------
 REPACK
(1 row)

 rows_seen 
-----------
     50000
(1 row)

Read the activity rows from the top. The report is idle inside its transaction, holding the ACCESS SHARE lock it took when it read the table. The repack finished copying every block and is now waiting on a relation lock, blocked by the report. The latecomer is waiting too, and its blocker is the repack. Its plain read conflicts with nothing the report holds; it is queued behind the repack’s pending exclusive request, because PostgreSQL grants locks in order and a newer request does not jump an older one. The pg_dump documentation describes the same queue in its section on parallel dumps.

So the reference page’s “typically held for a short time” is true once the lock is granted, and the time before that is set by the longest-running transaction holding a lock on the table. Once granted, the hold itself depends on how many changes piled up during the wait, because a final pass applies them under the lock. One reporting query left open over lunch turns the swap into a table-wide stall for every application session that arrives meanwhile. log_lock_waits is on by default in 19, so the server log records the repack’s wait once it passes deadlock_timeout; that is a log line, and it does not end the wait. Lock contention and blocking trees covers how to find the session at the head of a queue like this one.

Two more things showed up that a dashboard will notice. A temporary logical replication slot exists for the duration, with output plugin pgrepack and a name made of pg_repack_ and the process id of the decoding worker described below. The name shares its prefix with the third-party pg_repack extension, which helps to know before someone goes looking for an extension that was never installed. And effective_wal_level reported logical while the slot existed, on a server configured for replica. The WAL settings page says the effective level rises to logical with the first logical slot and falls back when the last one goes, so for as long as the repack runs the server adds the information logical decoding needs to the WAL it writes, and physical standbys receive that larger stream. Like any replication slot, this one can also hold WAL back from removal until it is dropped, up to whatever max_slot_wal_keep_size allows. A background process listed as REPACK decoding worker does the decoding. It sits in an IPC wait rather than a lock wait, although pg_blocking_pids reports the report against it as well.

Bounding the wait

The fix for an unbounded wait is the ordinary one. The block below repeats the setup with the report holding its lock, and gives the repack two seconds.

CREATE EXTENSION IF NOT EXISTS dblink;
SELECT dblink_connect('report', 'dbname=' || current_database()),
       dblink_connect('repack', 'dbname=' || current_database());
SELECT dblink_exec('report', 'BEGIN');
SELECT * FROM dblink('report', 'SELECT count(*) FROM warehouse_events') AS r(rows_seen bigint);
SELECT dblink_exec('repack', 'SET lock_timeout = ''2s''');
SELECT dblink_send_query('repack', 'REPACK (CONCURRENTLY) warehouse_events');
SELECT pg_sleep(6);
SELECT * FROM dblink_get_result('repack', false) AS r(status text);
SELECT dblink_error_message('repack');
SELECT dblink_exec('report', 'COMMIT');
SELECT count(*) AS leftover_slots FROM pg_replication_slots;
CREATE EXTENSION
 dblink_connect | dblink_connect 
----------------+----------------
 OK             | OK
(1 row)

 dblink_exec 
-------------
 BEGIN
(1 row)

 rows_seen 
-----------
     50000
(1 row)

 dblink_exec 
-------------
 SET
(1 row)

 dblink_send_query 
-------------------
                 1
(1 row)

 pg_sleep 
----------
 
(1 row)

 status 
--------
(0 rows)

                             dblink_error_message                              
-------------------------------------------------------------------------------
 ERROR:  canceling statement due to lock timeout                              +
 CONTEXT:  waiting for AccessExclusiveLock on relation 16385 of database 16384
(1 row)

 dblink_exec 
-------------
 COMMIT
(1 row)

 leftover_slots 
----------------
              0
(1 row)

The repack gave up waiting, and its slot went with it. That safety has a price we should state plainly: a timeout at this stage throws away the whole copy. On a table whose copy takes hours, lock_timeout turns a stall into hours of wasted I/O and a retry. We still set it every time, because wasted I/O is recoverable and a queue of blocked application sessions is an incident. The better habit is to check for long transactions on the table before starting, and to retry in a quieter window rather than raising the timeout until it stops failing. What we measured is lock_timeout bounding the wait for the swap lock; whether it also cuts short the wait in the initializing phase described below, we have not tested.

A snapshot that sees an empty table

The reference page warns that the concurrent form is not MVCC-safe. In practice that means a transaction whose snapshot predates the repack, and which had not yet read the table, sees it empty afterwards.

CREATE EXTENSION IF NOT EXISTS dblink;
SELECT dblink_connect('report', 'dbname=' || current_database());
SELECT dblink_exec('report', 'BEGIN ISOLATION LEVEL REPEATABLE READ');
SELECT * FROM dblink('report', 'SELECT count(*) FROM dock_doors') AS r(doors bigint);
REPACK (CONCURRENTLY) warehouse_events;
SELECT * FROM dblink('report', 'SELECT count(*) FROM warehouse_events') AS r(events_seen bigint);
SELECT dblink_exec('report', 'COMMIT');
SELECT dblink_exec('report', 'BEGIN ISOLATION LEVEL REPEATABLE READ');
SELECT * FROM dblink('report', 'SELECT count(*) FROM dock_doors') AS r(doors bigint);
REPACK warehouse_events;
SELECT * FROM dblink('report', 'SELECT count(*) FROM warehouse_events') AS r(events_seen bigint);
SELECT dblink_exec('report', 'COMMIT');
CREATE EXTENSION
 dblink_connect 
----------------
 OK
(1 row)

 dblink_exec 
-------------
 BEGIN
(1 row)

 doors 
-------
    12
(1 row)

REPACK
 events_seen 
-------------
           0
(1 row)

 dblink_exec 
-------------
 COMMIT
(1 row)

 dblink_exec 
-------------
 BEGIN
(1 row)

 doors 
-------
    12
(1 row)

REPACK
 events_seen 
-------------
       50000
(1 row)

 dblink_exec 
-------------
 COMMIT
(1 row)

Zero rows after the concurrent form, every row after the plain one. The concurrency caveats page lists the concurrent form beside TRUNCATE and the rewriting forms of ALTER TABLE, and does not list the plain form, which matches what we measured. The exposure is a long repeatable-read job that reads several tables in turn, such as an export or a reconciliation, and reaches the repacked one only after the swap. It does not get an error. It gets a consistent-looking result with one table missing.

Watching one in progress

pg_stat_progress_repack is new in 19 and reports REPACK, CLUSTER and VACUUM FULL alike. The older pg_stat_progress_cluster is kept for existing queries and translates a repack into CLUSTER when it orders by an index and VACUUM FULL otherwise, so a dashboard written for 18 keeps working and quietly mislabels the command.

Two phases are where a concurrent repack spends time that looks like nothing is happening. In initializing, it enables logical decoding if the server is not already at that level, then waits for every transaction that has been assigned a transaction id to end, including ones that start while it is waiting, so the phase can outlast the longest transaction that was running when the command began. That includes any concurrent repack already running, so a second one waits for the first to finish. In catch-up, it applies the changes made during the copy and also waits for the swap lock, which is why the measurement above joined the progress row to pg_stat_activity: the phase name alone does not say whether it is working or blocked. For alerting, a repack in catch-up with a Lock wait for longer than a few seconds is the condition to page on, unless a lock_timeout already bounds the swap.

For the purposes of wraparound, the reference page treats a repack as one long-running transaction, which keeps vacuum from cleaning dead rows in every other table until it finishes. On a large table that is its own source of bloat, and the repacking backend’s backend_xid in pg_stat_activity is where it shows. The page is also clear that REPACK is the wrong tool for wraparound itself: it advances the freeze horizon only as a side effect, takes much longer than vacuum, and can fail late.

What it costs to run

The space is a copy of the table and every index, plus, with USING INDEX, a sort file up to the size of the table if the planner chooses to sort. The concurrent form adds a small fixed amount of memory for each row updated or deleted during the run, outside maintenance_work_mem, and the reference page says it fails if more than about 104 million rows are changed concurrently. It also needs a free slot under max_repack_replication_slots, which defaults to 5 and can only be changed at server start. No statistics are gathered unless you pass ANALYZE, so a table repacked by index order still has the planner’s old idea of its correlation until the next analyze.

Before reaching for any of it, ask why the table bloated. Autovacuum and bloat covers the causes, and what each table costs to keep vacuumed gives the before-and-after number a rewrite should move.

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.