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
- PostgreSQL erases nothing straight away. Changing a row means writing a new version of it; deleting one means marking the old version.
- Cleanup (
VACUUM) frees space inside the file, but the file itself almost never gets smaller. In our run, after 90% of the rows were deleted it stayed at 128.1 MiB. - Shrinking a table means rewriting it clean. Before PostgreSQL 19 the built-in way to do it was
VACUUM FULL, and the table could not be used the whole time. PostgreSQL 19 hasREPACK (CONCURRENTLY): it rewrites the table while people keep working with it. - But at the very end it needs a moment when nobody touches the table, and how long that moment lasts depends on how much was changed meanwhile. If somebody holds the table for a long time,
REPACKwaits — and everyone else waits along with it. - And a transaction that took a "photo" of the database before
REPACK (CONCURRENTLY)sees the table empty afterwards.
A ledger where nothing is erased
Picture a ledger in which erasing is not allowed. To correct an entry, you cross it out and write a new line below. To delete one, you just cross it out. That is how a PostgreSQL table works: a page of the ledger is a page of the table, and a line is a row version.
Why? While some people read the ledger, others write in it. A reader who opened it five minutes ago must see it as it was five minutes ago. So the old entry stays as long as anyone might still see it.
On a page you can see it literally. Three entries, then a correction of one: the old one is crossed out and points to the new one. The page already has four entries, while a reader sees three.
If the corrected field is not part of the table of contents (the index) and the same page has room, the new line is written right there and the table of contents is left alone. If the field is in the table of contents, or the page has no room, the table of contents gets one more pointer.
The cleaner erases, but the ledger gets no thinner
Every now and then a cleaner comes by — VACUUM. It erases crossed-out
entries that nobody can see any more, and the freed lines can be written on
again. But it does not tear pages out of the ledger. The only exception is
empty pages at the very end: those can be torn off.
Some cleaning happens without the cleaner too: when a page is almost full,
whoever reads it erases what is crossed out on it. But the table of contents
still points at the erased lines, and only VACUUM can remove those
pointers.
In the run behind this article, 90% of a million rows were deleted:
- deleted in a scattered way — each page kept a tenth of its entries, and the file stayed at 128.1 MiB (mebibytes, 1024 × 1024 bytes) after cleaning;
- deleted from the end — the last pages emptied out entirely, and the file became 12.8 MiB.
In the first case the space was not lost: when as many rows were inserted into the table again, it did not grow by a single megabyte. Same ledger, it just has room to write in again.
The table of contents fared worse. The new entries got numbers larger than
all the old ones, and in the table of contents their place is at the end, not
on the half-empty pages at the start. The table of contents nearly doubled —
from 21.4 to 40.7 MiB. Shrinking it does not need the ledger rewritten:
rewriting just the table of contents (REINDEX INDEX CONCURRENTLY) is enough,
and in our run it went back to 21.4 MiB.
A thick ledger is not always a problem
If the ledger is written in all the time, it reaches its working size and stops thickening: the cleaner frees lines, new entries take them. In our run the table held at 27–28 MiB. It was rewritten clean — 25.6 MiB — and after the first round of updates it was 28.0 again. The slack in the working size is not free — the extra pages still have to be read and stored — but if it is small, there is nothing to rewrite for.
A rewrite is worth it after a one-off event after which the ledger will not slim down on its own: old entries were deleted and will not come back; the cleaner could not work for a long time because somebody held an old "photo" of the database; a new column was filled in for every row at once.
You can check for yourself in a minute that cleaning does not shrink the file — you need PostgreSQL 19:
CREATE TABLE t (id bigint PRIMARY KEY, note text);
INSERT INTO t SELECT g, repeat('n', 80) FROM generate_series(1, 1000000) g;
SELECT pg_size_pretty(pg_relation_size('t')); -- size before the delete
DELETE FROM t WHERE id % 10 <> 0; -- 90% of rows, scattered
VACUUM t;
SELECT pg_size_pretty(pg_relation_size('t')); -- the same size
REPACK (CONCURRENTLY) t;
SELECT pg_size_pretty(pg_relation_size('t')); -- only the live rowsRewriting the ledger clean
To rewrite is to take a new ledger, copy only the live entries into it and
replace the old one. In PostgreSQL 19 that is the REPACK command. The old
name VACUUM FULL still works and does the same. Outside PostgreSQL itself
the pg_repack extension has long done something similar, but it is a separate
tool, and everything below is about the built-in command.
VACUUM FULL and plain REPACK take the ledger away for the rewrite: nobody
can read or write. In our run VACUUM FULL closed a 384 MiB table for 1.3 s,
a 768 MiB one for 3.1 s, a 1.5 GiB one for 5.7 s. The bigger the ledger, the
longer everyone waits.
REPACK (CONCURRENTLY) rewrites without taking the ledger away. While it
copies entries into the new one, everyone keeps working with the old one, and
it remembers what they managed to add. At the end it takes the ledger briefly,
copies the last changes and swaps the ledgers. In our run the slowest
statement alongside took no more than 106 ms at all three sizes, and no change
was lost. That is not a promise: the more was changed during the rewrite, the
longer the last copy takes.
The moment that may not come
That moment is when nobody is holding the ledger. If somebody opened it and
is sitting over it for a long time — a long report, a dump, a forgotten open
transaction — REPACK waits until they finish. And everyone who comes to the
ledger after that queues up behind REPACK, even if they only want to
read.
In our run such a transaction stayed open for 6 s, and ordinary statements
alongside stood still for more than 5 s — just like with the old
VACUUM FULL, only at the end instead of the start.
You can tell REPACK "wait no longer than a second" (lock_timeout). That
limits only the waiting, not the whole job. In the run with a long reader
REPACK gave up only after it had rewritten the whole ledger: the work was
lost and the table stayed thick. When a writing transaction was open nearby,
it gave up right away, at the start, touching nothing. So first make sure
nobody is sitting over the table for a long time, and only then run it.
A photo taken before the rewrite
A transaction in REPEATABLE READ mode works like a photo: it sees the
database as it was at the moment of the snapshot. Usually that is reliable.
But if the photo was taken before REPACK (CONCURRENTLY), and the transaction
had not looked into the table itself before that, then when it looks after the
rewrite has finished, it sees an empty ledger. The data is still there:
any new transaction sees all of it.
In our run such a transaction counted 0 rows instead of a million, and there
was no error. After VACUUM FULL the same transaction saw every row. That is
why REPACK (CONCURRENTLY) is not run while long reports that read tables
one after another are working.
When CONCURRENTLY will not work
The server refuses if the table has neither a primary key nor a unique index
made its replication identity (REPLICA IDENTITY USING INDEX); if the table is
UNLOGGED; if it is asked to rewrite a partitioned table as a whole (one
partition at a time is fine); if the command is inside BEGIN … COMMIT; and if
no table name is given. Plain REPACK works on a table without a key and on a
partitioned table, but takes it away for the whole run.
What follows from this
- Do not rewrite a table that holds its size under steady load: it will be back to that size within minutes.
- Rewrite after a one-off event — a mass delete, a long transaction, filling in a new column.
- Before
REPACK (CONCURRENTLY), look for long transactions, especially ones that have touched this table, and dumps. - Set
lock_timeout, but remember it limits only the waiting, and the refusal may come after all the work. - Do not run it next to long reports in one snapshot.
TL;DR
- In PostgreSQL,
UPDATEwrites a new row version andDELETEmarks the old one.VACUUMfrees 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
REPACKto 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 CONCURRENTLYis enough: 40.7 → 21.4 MiB without rewriting the table. VACUUM FULLcloses 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. PlainREPACKcloses 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_timeoutlimits 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 FULLand plainREPACKdo 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
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:
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:
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:
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:
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:
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:
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.
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.
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:
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.
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:
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:
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:
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 see | what to do |
|---|---|
| the table holds the same size under steady load | do not rewrite; if the slack is large, tune autovacuum and fillfactor |
| only an index is bloated: scattered deletes under a growing key, as above | REINDEX 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 in | REPACK (CONCURRENTLY), with the preparation from the end of the article |
| the whole contents of a table or a whole partition are being removed | TRUNCATE or dropping the partition, if their behaviour fits: there is nothing to rewrite |
VACUUM FULL, CLUSTER and REPACK are one operation
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.
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:
| command | ran, s | table, MiB | peak space, MiB | WAL, MiB | slowest reader statement, ms | writer, ms |
|---|---|---|---|---|---|---|
VACUUM FULL | 1.17 | 384.2 → 128.2 | +148.9 | 146.4 | 1166 | 1164 |
REPACK | 1.16 | 384.2 → 128.2 | +149.4 | 146.4 | 887 | 890 |
REPACK (CONCURRENTLY) | 1.20 | 384.2 → 128.5 | +137.4 | 166.9 | 5 | 69 |
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:
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
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.
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:
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:
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:
Since this may take many seconds, also delay until after releasing locks.
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:
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:
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:
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:
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:
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:
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 obeyslock_timeouttoo. 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
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.
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:
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
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:
CONCURRENTLYdoes not work for system catalogs and TOAST tables, for tables whose access method is notheap, and for tables with theuser_catalog_tableparameter;- no more than
max_repack_replication_slotscommands withCONCURRENTLYcan 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 isnot limited by maintenance_work_mem
; - the changes themselves, except unmodified TOAST columns,
are stored on disk separately
— space on top of the table copy; CONCURRENTLYmight 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
- 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 CONCURRENTLYis enough. Rewrite the table after a one-off event. - Check that
CONCURRENTLYapplies: a primary key or an index made the replica identity; a regular (notUNLOGGED) table with theheapaccess method; for a partitioned table, partition by partition; no invalid indexes; theMAINTAINprivilege; a free slot withinmax_repack_replication_slots. - 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 INDEXa temporary sort file of up to the table's size may be needed as well. - Get rid of long transactions before starting. Check
pg_stat_activity: transactions with an oldxact_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. - 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.
- 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. - Watch during the run: the phase in
pg_stat_progress_repack(catch-uplasting longer than seconds means the command is waiting for the lock), the queue behind it inpg_locks, thebackend_xidof the command's session and dead rows in other tables. The command can be cancelled at any moment — the table stays as it was. - 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
| what | where from | what it shows |
|---|---|---|
| table and index size | pg_relation_size, pg_table_size, pg_indexes_size, pg_total_relation_size | growth after a one-off event versus a steady size; main fork versus the whole footprint |
| dead rows and vacuuming | n_dead_tup, last_autovacuum in pg_stat_user_tables | vacuum cannot keep up or cannot act |
| long transactions | xact_start, backend_xid, backend_xmin in pg_stat_activity | who will delay the start or the file swap; the REPACK session holds the horizon itself |
| compaction progress | phase in pg_stat_progress_repack | catch-up lasting longer than seconds — the command is waiting for the lock |
| the queue behind the command | pg_locks where granted = false | statements waiting behind ACCESS EXCLUSIVE |
| WAL level | effective_wal_level | logical — logical decoding is running |
| WAL volume | pg_current_wal_lsn() before and after | the 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.
This is neither a retelling nor a separate text: everything below is taken from the article itself — its own summary, the section headings, the “actually” column and the version table. Which is why these theses cannot drift from the article.
The gist
- In PostgreSQL,
UPDATEwrites a new row version andDELETEmarks the old one.VACUUMfrees 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
REPACKto 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 CONCURRENTLYis enough: 40.7 → 21.4 MiB without rewriting the table. VACUUM FULLcloses 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. PlainREPACKcloses 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_timeoutlimits 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 FULLand plainREPACKdo not do this.
In fact
- 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.
- A table under steady updates reaches a steady size: the space
VACUUMfrees is taken by new versions. In our run such a table held 27–28 MiB; afterREPACKit 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. - 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 thecatch-upphase — 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. - If it cannot get the lock, it is cancelled entirely.
lock_timeoutlimits 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 withlock_timeout = 1sthe 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". - They are one. The PostgreSQL 19 release notes:
REPACKreplaces VACUUM FULL and CLUSTER, and theVACUUMpage callsFULLdeprecated 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. - 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 READtransaction that had read another table before counted 0 rows instead of 1000000, while a new session right after saw all 1000000. AfterVACUUM FULLthe same transaction sees a million.
What is covered
- Why should I care?
- The model: UPDATE writes a new row version
- What VACUUM does
- Bloat is not always a disease
- VACUUM FULL, CLUSTER and REPACK are one operation
- What CONCURRENTLY does
- Where CONCURRENTLY still stops the service
- A snapshot taken before the rewrite sees an empty table
- When CONCURRENTLY is not allowed
- What to configure and what to watch
- How to reproduce the numbers
- Measured by
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), checkpg_stat_activityandpg_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 theREPACKsession itself too: for the transaction horizon it is one long transaction, and while it runsVACUUMdoes not remove dead rows in other tables. - Set
lock_timeoutbeforeREPACK (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 FULLand plainREPACKdo 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 CONCURRENTLYbrought it back to 21.4 MiB.
Common misconceptions
“VACUUM frees disk space”
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
.
“A bloated table should be compacted regularly”
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
.
“REPACK (CONCURRENTLY) never blocks reads and writes”
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.
“With lock_timeout, CONCURRENTLY is safe: if it cannot get the lock it will do it later”
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".
“VACUUM FULL and REPACK are different operations”
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.
“REPACK (CONCURRENTLY) is MVCC-safe, since no changes are lost”
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
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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- PostgreSQL 19 — Database Page Layout, Table Row LayoutOfficial documentation. The row-version header fields that
bench/repack/versions.pyprints: 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 - 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
- PostgreSQL 19 — pageinspect, heap_page_itemsOfficial documentation. How
bench/repack/versions.pyreads 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 - 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
- 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
- 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
- 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/
- 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
- 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
- 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
- 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