Relational databases: collection tree

Relational databases

PostgreSQL vacuum and transaction age

Deep diveAbout 13 minutes AI-generated

PostgreSQL’s VACUUM makes obsolete row-version space reusable, maintains visibility information and keeps old transaction identifiers safe to interpret. A completed run does not mean every old tuple was removable, every page was frozen or the table file became smaller. Those are different maintenance outcomes.

Return to the blue mug, P7. A report establishes a snapshot at price 20.00, then another transaction raises the catalogue price to 22.00 and commits. Inside PostgreSQL followed the two versions through the heap and indexes. Here we follow what prevents their cleanup, what vacuum can change, and why even a table that never changes still needs maintenance.

This is the collection’s independent price replay. Order 103 remains pending, with no payment and agreed line prices totalling 29.00. The figures are labelled models; their page layouts, schedules and age values are illustrative.

Why the old price must stay

The report runs its first ordinary query inside a read-only Repeatable Read transaction before the price changes. That establishes its snapshot; merely sending BEGIN would not. After the writer commits, a new reader sees 22.00, while the report still sees 20.00.

Neither commit nor vacuum may remove the tuple that supplies the report’s answer. Finishing that report can release its requirement, but another participant with an earlier retained snapshot can still prevent cleanup.

Keep the version a reader still needs
Figure 1. A price index makes this a non-HOT update. Cleanup also removes the obsolete index entry; the heap file does not shrink.
Figure as text

A report retains its £20 snapshot while a new reader sees committed £22. Vacuum keeps the old tuple. After the report ends, a later vacuum reclaims it only if no other retention requirement remains.

In a separate disposable PostgreSQL 18.6 server, a three-product copy with a price index showed the same distinction. With the report’s snapshot retained, VACUUM (VERBOSE, INDEX_CLEANUP ON) reported one dead tuple not yet removable; the report still read 20.00 and a new reader read 22.00. After the report committed, the next vacuum removed one tuple and reported zero dead tuples not yet removable. The heap still occupied one page. This checks the two-session behaviour, not a production maintenance rate.

The earlier tuple passes through three states: still required, eligible for removal, then reclaimed. Ending the last relevant snapshot moves it into the second state. Cleanup must still happen to reach the third. Page pruning can reclaim obsolete tuple bytes during ordinary page access; vacuum also carries out work across the table and its indexes.

A retention horizon limits how far cleanup can advance: PostgreSQL must preserve history that a participant may still need. The engine uses conservative boundaries, rather than asking whether a particular report will actually select P7. A report can therefore hold cleanup back even if its next query never reads that product. Several participants can retain history; releasing one is insufficient while another still needs it.

What vacuum changes

Once the old version is removable, vacuum can clear its obsolete index entries and reclaim its heap space. Changing a price covered by an ordinary price index prevents a HOT update, so the new tuple also needs new index entries. In a HOT chain, page pruning can instead remove old tuple bytes while preserving the original index route through a redirect. The parent article explains that route; neither case makes vacuum optional.

Two small maps describe different properties of the resulting page:

One page, two different questions
MapWhat it recordsWhat uses it
Free space mapAvailable space within heap pages.Later inserts and updates can find a page with room.
Visibility mapAn all-visible bit and an all-frozen bit for each heap page.Index-only scans can avoid heap visibility checks on all-visible pages; vacuum can skip work already proved unnecessary.

Vacuum sets the all-visible bit only when the page qualifies. A clear bit means there is no such proof, rather than proving that a row is invisible. A change to another row on the same page can clear it. Thus a covering index can still need heap fetches after an update, even when the query never asks for the changed row. PostgreSQL’s visibility-map documentation defines those guarantees.

ANALYZE does another job: it samples data to refresh the planner’s statistics. Ordinary vacuum updates some table-level estimates, but does not replace that distribution information. VACUUM (ANALYZE) requests both kinds of maintenance. Refreshing estimates does not erase retained versions, and reclaiming a tuple does not by itself repair a poor query plan.

Find what holds cleanup back

A growing dead-tuple estimate suggests work to investigate. It does not tell you whether vacuum has not reached the table, cannot acquire a needed lock, lacks capacity, or has finished while retaining versions. Start with the table, then inspect what can retain history.

SELECT relname, n_live_tup, n_dead_tup,
       last_vacuum, last_autovacuum,
       last_analyze, last_autoanalyze
FROM pg_stat_user_tables
WHERE relid = 'public.products'::regclass;

SELECT pg_relation_size('public.products') AS heap_bytes,
       pg_indexes_size('public.products') AS index_bytes,
       pg_total_relation_size('public.products') AS total_bytes;

n_live_tup and n_dead_tup are estimates; a last-run timestamp establishes neither useful reclamation nor a healthy age. The total size includes indexes, TOAST and auxiliary storage, whereas the first size is just the heap’s main fork. Read cumulative statistics in fresh short transactions: they lag activity, and values can be cached during a transaction. Clear the statistics snapshot with pg_stat_clear_snapshot() when deliberately sampling again inside one.

For sessions, inspect both transaction IDs (XIDs) and snapshot horizons. Order by their age, rather than treating the oldest connection or longest elapsed query as the answer.

SELECT pid, datname, application_name, state,
       xact_start, query_start,
       age(backend_xid) AS xid_age,
       age(backend_xmin) AS xmin_age,
       wait_event_type, wait_event
FROM pg_stat_activity
WHERE backend_xid IS NOT NULL OR backend_xmin IS NOT NULL
ORDER BY GREATEST(age(backend_xid), age(backend_xmin))
         DESC NULLS LAST;

backend_xid is the session’s assigned transaction ID; backend_xmin is its current xmin horizon. A read-only report can retain a snapshot without having an assigned XID. An idle session outside a transaction is different from idle in transaction. Conversely, a transaction’s elapsed time alone does not establish the history it retains: interpret the IDs, state and commands together. Visibility into other sessions requires suitable monitoring privileges.

Then check participants that are easy to miss:

Retention need not belong to an ordinary active query
EvidenceWhat it can mean
pg_prepared_xactsA prepared two-phase transaction remains unfinished after its session has detached. Its transaction manager must resolve the outcome; cancelling a query cannot finish it.
pg_replication_slots.xminA slot retains row history even when its consumer is inactive.
catalog_xmin on a slotA separate boundary retains system-catalogue tuples needed by logical decoding.
pg_stat_replication.backend_xminStandby feedback can hold the primary’s cleanup horizon back to protect standby reads.
Queries for prepared transactions, slots and standby feedback
SELECT gid, database, owner, prepared,
       age(transaction) AS xid_age
FROM pg_prepared_xacts
ORDER BY age(transaction) DESC;

SELECT slot_name, slot_type, active,
       age(xmin) AS xmin_age,
       age(catalog_xmin) AS catalog_xmin_age,
       restart_lsn
FROM pg_replication_slots;

SELECT pid, application_name, state,
       age(backend_xmin) AS feedback_xmin_age
FROM pg_stat_replication;

A slot’s retained WAL position, restart_lsn, is a different obligation from its row and catalogue horizons. A large WAL backlog does not prove retained heap tuples, and a null slot xmin does not prove the slot costs no WAL space. Choose a slot or standby policy with the replication owner; dropping a slot or removing feedback can sacrifice the consumer’s ability to continue or finish its read. PostgreSQL physical replicas and promotion and PostgreSQL logical replication and change feeds own those choices.

For an ordinary abandoned transaction, first establish who owns it and what ending it would undo. Cancelling its current statement may leave its transaction open. Have the client commit or roll back as appropriate, or deliberately end the session under the incident’s recovery plan. Then sample the horizons again and check the next vacuum’s result. More worker time cannot make an unsafe removal safe.

Reusable space, bloat and file size

Suppose retention has ended and vacuum reclaims the old tuples, but the file stays large. That can be the expected result. If live tuples remain on every page, freeing most of the tuple bytes still leaves each page occupied.

Figure 2 Free bytes do not remove the pages around them
Before cleanup

6 live units + 18 obsolete units · 6 pages

Page 1
LiveOldOldOld
Page 2
LiveOldOldOld
Page 3
LiveOldOldOld
Page 4
LiveOldOldOld
Page 5
LiveOldOldOld
Page 6
LiveOldOldOld
After ordinary vacuum

6 live units + 18 reusable units · 6 pages

Page 1
LiveFreeFreeFree
Page 2
LiveFreeFreeFree
Page 3
LiveFreeFreeFree
Page 4
LiveFreeFreeFree
Page 5
LiveFreeFreeFree
Page 6
LiveFreeFreeFree
After a justified rewrite

The same 6 live units · 2 pages

Page 1
LiveLiveLiveLive
Page 2
LiveLiveFreeFree

A separate schematic heap: six pages, each with four equal-sized units. The first row’s old versions are all removable. Ordinary vacuum frees their bytes within each page; every page still holds live data. A rewrite packs that same data into fewer pages. Units, packing and counts are invented, not PostgreSQL tuple sizes or measured bloat.

The freed bytes may be useful capacity for tomorrow’s writes. Keeping them avoids allocating more storage. They can also leave a lasting cost: a sequential scan still visits the occupied pages, and those pages occupy cache and storage. Bloat is excess physical space relative to the useful data and layout the workload needs, rather than a synonym for either dead tuples or any free byte. Deliberately reserved fillfactor space is part of that layout.

Measure the object that costs you. Track heap and index sizes separately, alongside live data and the workload’s buffer or scan cost. Where available, the pgstattuple extension distinguishes tuple bytes and free space, while pgstatindex reports B-tree page density. These scans cost work and need privileges; concurrent changes mean their results are not one instantaneous database snapshot. A dead-tuple estimate divided by live rows is not a reliable bloat percentage.

Ordinary vacuum can truncate completely empty pages at the heap file’s end, under suitable conditions. It cannot compact internal gaps out of still-occupied pages. Tail truncation needs a brief ACCESS EXCLUSIVE lock; TRUNCATE false disables that part when its locking cost is unsuitable. Most of ordinary vacuum permits normal reads and writes, though its I/O and conflicting maintenance locks still matter.

VACUUM FULL rewrites the table into a new compact file, rebuilds its indexes, needs spare space for the replacement and holds an ACCESS EXCLUSIVE lock that blocks reads and writes. It is a costly compaction choice, not the routine response to high dead-tuple counts or transaction-age alarms. A sparse index may need its own rebuild even when the heap is healthy. PostgreSQL schema changes under load develops the lock, capacity and rollout decisions for rewrites and index maintenance.

Transaction ID age and freezing

A table can have no dead tuples and still need vacuum. PostgreSQL uses finite 32-bit transaction IDs, or XIDs, in tuple visibility metadata. Their ordering is circular: roughly half the space is interpreted as the past, and half as the future. An ordinary committed insertion ID cannot safely age through that boundary indefinitely. The wider xid8 type used by some SQL functions does not remove this obligation in stored tuples.

Freezing marks an eligible old insertion as permanently in the past for visibility purposes. In current PostgreSQL it preserves the tuple’s original xmin value and sets metadata flags, so looking for xmin = 2 is not a valid freezing check. No business value needs to change. An unchanged price row can therefore need freezing as other cluster work consumes XIDs.

The price stays still. Its boundary ages.
Figure 3. Invented transaction counts. The 200-million marker is a maintenance trigger, not the wraparound limit.
Figure as text

Other transactions age the table’s frozen boundary from 20 to 180 million transactions. Vacuum freezes eligible live tuples and advances the boundary. It later ages by another 20 million, while the frozen tuple remains safe.

pg_class.relfrozenxid records a lower bound: this table contains no unfrozen insertion XID older than that boundary. It is not the insertion ID of its oldest business row. age(relfrozenxid) measures how far the boundary trails current XID allocation. The database’s datfrozenxid reflects the oldest per-table boundary, so one neglected table can keep database age high. Include TOAST tables and system catalogues when finding it.

SELECT c.oid::regclass AS relation,
       age(c.relfrozenxid) AS xid_age,
       mxid_age(c.relminmxid) AS multixact_age
FROM pg_class AS c
WHERE c.relkind IN ('r', 'm', 't')
ORDER BY age(c.relfrozenxid) DESC;

SELECT datname, age(datfrozenxid) AS xid_age,
       mxid_age(datminmxid) AS multixact_age
FROM pg_database
ORDER BY age(datfrozenxid) DESC;

The first query examines stored tables, materialised views and TOAST relations in the current database, including catalogues. Reorder it by mxid_age(c.relminmxid) when investigating MultiXact age. Connect to the database identified by the second query to locate its responsible relations; vacuuming one table elsewhere cannot repair its boundary.

MultiXact age

Several transactions can lock the same row compatibly. PostgreSQL can represent those lockers with a MultiXact identifier and associated membership information. That finite identifier space needs separate maintenance. mxid_age(relminmxid) and mxid_age(datminmxid) measure that obligation; healthy XID age does not establish healthy MultiXact age. Compare it with the MultiXact freeze settings and investigate old lockers. Replication slots do not directly hold back MultiXact cleanup, so dropping a stale slot is not the corresponding remedy.

When transaction age becomes urgent

Routine vacuum freezes eligible tuples opportunistically. An aggressive vacuum must visit all-visible pages that are not yet all-frozen to advance age, while all-frozen pages can be skipped. PostgreSQL 18 can also scan some all-visible pages eagerly before that aggressive pass. Consequently a recent space-cleanup run need not have advanced the table’s frozen boundary.

Age settings reserve successive margins for this work. vacuum_freeze_min_age controls ordinary freeze eligibility; vacuum_freeze_table_age makes a run use the aggressive strategy; autovacuum_freeze_max_age forces age-driven vacuum even when routine autovacuum is disabled. MultiXacts have corresponding settings. Nearer danger, the failsafe prioritises age progress over optional work and cost delay. Protective restrictions eventually prevent new XID-consuming work rather than allowing identifiers to become ambiguous. A forced autovacuum is a maintenance trigger, not evidence that the wraparound boundary has already been reached.

Allow enough headroom for the oldest work to finish. Take an illustrative age margin of 50 million XIDs, with the cluster consuming 10,000 XIDs a second. The margin lasts about 5,000 seconds, or 83 minutes, before allowing for bursts. Count allocation across the cluster, including relevant subtransaction use; one SQL statement is not one XID, and read-only work need not allocate one.

When age is urgent, identify the oldest relevant relations and retained transactions, resolve the retaining cause, and run targeted ordinary vacuum with an authorised maintenance connection. Keep checking age progress and server warnings. VACUUM (FREEZE) aggressively requests freezing but cannot override a retained horizon; applying it indiscriminately can add avoidable work. Compaction is a different task.

If protective restrictions have already begun, follow the server’s specific warning and documented recovery procedure. That repair uses plain VACUUM in the identified database, with authority to process the responsible catalogues as well as user tables. Avoid FULL and FREEZE in that emergency repair; they add work or consume identifiers. Raising limits postpones the same unresolved cause.

Keeping autovacuum ahead of the workload

Autovacuum first decides that a table needs work, then needs an available worker and enough time to do it. PostgreSQL 18’s update/delete trigger combines a base threshold and a fraction of estimated table rows, capped by autovacuum_vacuum_max_threshold unless that cap is disabled. The default base is 50, scale factor 0.2 and cap 100 million.

A separate million-row workload, changing 1,000 tuples each second
Assumed settingsUpdate/delete thresholdTime to reach it from zero
Base 50; scale 0.250 + 0.2 × 1,000,000 = 200,050About 200 seconds
Base 50; scale 0.0150 + 0.01 × 1,000,000 = 10,050About 10 seconds

These are eligibility calculations, not predicted start times or measured vacuum intervals. A lower per-table scale factor can ask for work sooner. It cannot release a retained report snapshot, overcome a lock, guarantee a free worker or supply storage bandwidth. If removable work arrives faster than maintenance can process it, an earlier trigger alone cannot keep the backlog bounded.

Insert-driven vacuum matters too: a table receiving only new rows can need visibility-map and freezing work. Its insert threshold uses inserted tuples since the last vacuum and the table’s unfrozen fraction, rather than the update/delete count. Age-driven work is another independent reason to run. Analyse has its own change thresholds. Check the effective table overrides as well as global settings before attributing a run to one trigger.

Inspect table overrides and global vacuum settings
SELECT oid::regclass AS relation, reloptions
FROM pg_class
WHERE oid = 'public.products'::regclass;

SELECT name, setting, unit, source
FROM pg_settings
WHERE name LIKE 'autovacuum%'
   OR name LIKE 'vacuum%'
ORDER BY name;

Use the table’s change rate, time between useful cleanups and maintenance duration to choose a table-specific trigger. If eligible work waits, investigate worker availability and locks. If a running worker cannot keep up, inspect waits, I/O, cost delay and index work before adjusting resources. More workers can process different tables, but also compete with application work and one another. Keep the repair proportionate to the table causing the debt.

Read the work that is happening

SELECT p.pid, p.relid::regclass AS relation, p.phase,
       p.heap_blks_total, p.heap_blks_scanned,
       p.heap_blks_vacuumed, p.index_vacuum_count,
       a.wait_event_type, a.wait_event
FROM pg_stat_progress_vacuum AS p
LEFT JOIN pg_stat_activity AS a USING (pid)
WHERE p.datid = (SELECT oid FROM pg_database
                 WHERE datname = current_database());

A finished heap scan is not a finished vacuum. Index cleanup, further heap work and finalisation may remain, and a run can cycle between phases. heap_blks_scanned / heap_blks_total describes heap-scan progress, not a percentage of the whole job. VACUUM FULL reports through pg_stat_progress_cluster instead.

Combine the phase and wait evidence with vacuum reports. VACUUM (VERBOSE) public.products;, run outside a transaction block with suitable authority, reports removed and remaining tuples and age information. Autovacuum logging, controlled by log_autovacuum_min_duration, supplies reports for automatic runs. Read what was retained and what boundaries advanced, rather than accepting a recent timestamp as success.

There are two routine exceptions to automatic coverage. Autovacuum cannot maintain another session’s temporary table, so its owning session must vacuum and analyse it. A partitioned parent has no heap to vacuum, and changes to partitions do not automatically refresh the parent’s aggregate planner statistics: arrange manual ANALYZE of the parent. The stored partitions receive their own ordinary vacuum work.

Choosing and checking a maintenance action

Choose the acceptance condition before changing anything. For P7, the first question was whether the earlier snapshot still required 20.00. After that requirement ended, the next question was whether cleanup reclaimed its bytes. Neither answer established the separate transaction-age condition.

Match the action to the unfinished obligation
EvidenceTargeted actionCheck afterwards
Old versions still retainedResolve the responsible transaction, prepared outcome or replication retention with its owner.The relevant horizon advances; subsequent cleanup can remove eligible versions.
Removable work accumulatingLet ordinary vacuum catch up; repair its trigger, lock or capacity problem.Useful reclamation keeps pace with changes over repeated samples.
XID or MultiXact age rising dangerouslyResolve the matching old work; prioritise vacuum that advances the responsible boundaries.Both relation and database ages improve, with renewed completion margin.
Planner distribution estimates staleRun appropriate ANALYZE.Relevant estimates and measured plan work improve.
Persistent costly heap or index sparsityPlan justified compaction or index rebuilding with lock and spare-space budgets.The intended object shrinks or its workload cost improves, without immediate regrowth from an unresolved cause.

Keep the scope of that check tied to the repair. A smaller file cannot prove safe transaction age, and lower age cannot prove a faster report. If the request is still slow after maintenance meets its own condition, Operating and diagnosing PostgreSQL follows the wider request through pool, waits and execution evidence.

Sources and further reading

Checked against PostgreSQL 18 documentation. The figures and threshold arithmetic are illustrative models. The diagnostic SQL blocks were checked on PGlite 0.5.8, PostgreSQL 18.3 compiled to WebAssembly. The separate two-session check used native PostgreSQL 18.6 on Linux in a disposable container. No production throughput, scheduler timing or wraparound emergency was measured.