Sub topic 11
Visibility map, freezing, and transaction ID wraparound
This chapter assumes you know how MVCC creates dead tuples, what VACUUM removes, and how autovacuum decides to run. You should be comfortable reading pg_stat_user_tables and running queries in psql. Here you will learn about two side jobs VACUUM does along the way: tracking which pages need no attention, and freezing old rows so the 32-bit transaction counter can wrap around safely.
The visibility map
Every table has a small companion file called the visibility map (VM). It stores two bits for each 8 kB heap page:
- all-visible: every row version on the page is visible to every current and future transaction. The page has no dead tuples and no recent changes that some snapshot might not see.
- all-frozen: every row on the page is already frozen (explained below). Frozen pages are also all-visible.
VACUUM sets these bits after it has cleaned a page. Any INSERT, UPDATE, or DELETE that touches the page clears them again.
The map has two practical uses.
- VACUUM skips pages. A normal VACUUM does not read pages marked all-visible, because there is nothing to remove there. On a large table where most data is cold, this is why a vacuum can finish in minutes instead of hours.
- Index-only scans work. An index-only scan reads only the index and skips the heap. It can do this only if the VM says the page is all-visible. Otherwise PostgreSQL must visit the heap page to check row visibility.
You can see the second effect in EXPLAIN. The Heap Fetches line counts the visits to the heap that the scan could not avoid:
EXPLAIN (ANALYZE, COSTS OFF)
SELECT customer_id FROM public.orders WHERE customer_id BETWEEN 100 AND 200;On a table that has not been vacuumed recently, you may see an Index Only Scan with a large Heap Fetches number. Running VACUUM public.orders sets the VM bits and the number drops. This is a common reason an index-only scan is slower than expected.
Inspecting the map
The planner's own estimate is in pg_class.relallvisible. For exact per-table counts, use the pg_visibility extension that ships with PostgreSQL:
CREATE EXTENSION IF NOT EXISTS pg_visibility;
SELECT c.relpages,
c.relallvisible,
s.all_visible,
s.all_frozen
FROM pg_class c,
pg_visibility_map_summary('public.orders') s
WHERE c.oid = 'public.orders'::regclass;all_visible and all_frozen are page counts. If all_visible is far below the total number of pages in a table that is mostly read, VACUUM is not keeping up, or something is blocking it (see the chapter on cleanup blockers).
placeholderThe page life cycle looks like this:
Why transaction IDs wrap around
Every transaction that changes data gets a transaction ID (XID), a 32-bit number. Each row version records the XID that created it (xmin) and, if applicable, the XID that deleted it (xmax). To decide whether a row is visible, PostgreSQL compares those XIDs with the XID of the current snapshot.
A 32-bit counter holds about 4.3 billion values, and a busy system can use them up. PostgreSQL does not stop at the end. It treats the XID space as a circle. For any given XID, about 2 billion XIDs are "in the past" and about 2 billion are "in the future".
This causes a problem. A row written at XID 100 looks like it is in the past today. After 2 billion more transactions, XID 100 would suddenly look like it is in the future, and the row would vanish from every query. This is transaction ID wraparound. It would be silent data loss, so PostgreSQL goes to great lengths to prevent it.
Freezing
The prevention is freezing. When VACUUM finds a row version that is old enough, and visible to everyone, it marks the row as frozen. A frozen row is treated as being in the past for all transactions, whatever the current XID is. The original xmin no longer matters, so the row cannot be affected by wraparound.
Freezing is a normal part of VACUUM, not a separate command. Several settings control it:
| Setting | Default | Meaning |
|---|---|---|
| `vacuum_freeze_min_age` | 50 million | A VACUUM freezes rows whose XID is older than this many transactions. |
| `vacuum_freeze_table_age` | 150 million | If the table's oldest unfrozen XID is older than this, VACUUM scans all pages that are not all-frozen, instead of skipping all-visible pages. |
| `autovacuum_freeze_max_age` | 200 million | If the table's oldest unfrozen XID passes this, autovacuum starts a vacuum even when autovacuum is otherwise off. |
| `vacuum_failsafe_age` | 1.6 billion | Past this age, VACUUM drops optional work such as index cleanup and cost delays to finish quickly (PostgreSQL 14 and later). |
The defaults above are for recent versions. Check yours with SHOW.
Each table records the oldest XID it may still contain in pg_class.relfrozenxid. Each database has a matching pg_database.datfrozenxid. The function age() converts these to "how many transactions ago":
SELECT c.oid::regclass AS table_name,
age(c.relfrozenxid) AS xid_age,
pg_size_pretty(pg_table_size(c.oid)) AS size
FROM pg_class c
WHERE c.relkind IN ('r', 'm')
ORDER BY age(c.relfrozenxid) DESC
LIMIT 10;SELECT datname, age(datfrozenxid) AS xid_age
FROM pg_database
ORDER BY xid_age DESC;A healthy system shows ages that stay below autovacuum_freeze_max_age, with sawtooth behavior: age grows, a vacuum runs, age drops.
The all-frozen bit
Before PostgreSQL 9.6, a freeze-driven vacuum had to read every page of the table, even cold ones. The all-frozen bit fixed that. Pages marked all-frozen are skipped even by the aggressive scans described by vacuum_freeze_table_age. This means that once a large, append-only table has been frozen, later freeze vacuums touch only the new pages.
Anti-wraparound autovacuum
When a table's age passes autovacuum_freeze_max_age, autovacuum launches a worker on it. In pg_stat_activity the query text ends with (to prevent wraparound). These vacuums differ from ordinary ones in three ways:
- They run even if autovacuum is disabled for the table or for the server.
- They are aggressive: they cannot skip pages that are merely all-visible, only those that are all-frozen.
- They do not give up when they conflict with a lock request. A normal autovacuum cancels itself if another session needs a conflicting lock, but an anti-wraparound one keeps going. A
LOCK TABLEorALTER TABLEthat arrives during one will wait.
The last point surprises people. If a schema change hangs for no obvious reason, look for a wraparound vacuum on the same table:
SELECT pid, relid::regclass AS table_name, phase, query
FROM pg_stat_progress_vacuum v
JOIN pg_stat_activity a USING (pid)
WHERE a.query LIKE '%to prevent wraparound%';Do not cancel such a vacuum unless you must. The table will need it again right away.
What happens if freezing fails
If vacuum cannot advance relfrozenxid, the age keeps climbing. The server escalates:
- At
autovacuum_freeze_max_age, anti-wraparound vacuums start. - At
vacuum_failsafe_age, VACUUM skips index cleanup and cost-based throttling to freeze as fast as possible. - When roughly 3 million XIDs remain before wraparound, the server logs warnings.
- When about 3 million remain (the exact margin varies by version), it refuses new write transactions that need an XID, until a manual VACUUM has run.
The causes are the same as for ordinary bloat, only worse: a long transaction, an abandoned replication slot, or a forgotten prepared transaction holds back the oldest XID that VACUUM may freeze. Find them with the backend_xmin query from the cleanup-blockers chapter, plus:
SELECT gid, prepared, age(transaction) AS xid_age
FROM pg_prepared_xacts
ORDER BY prepared;SELECT slot_name, active, age(xmin) AS xmin_age, age(catalog_xmin) AS catalog_xmin_age
FROM pg_replication_slots;Practical guidance
- Alert on age, not only on bloat. Alert when
age(datfrozenxid)passes about 50 to 60 percent ofautovacuum_freeze_max_age... more usefully, when it passes the freeze max age itself, since at that point it should already be dropping. - Freeze after bulk loads. After loading a large table that will rarely change, run
VACUUM (FREEZE, VERBOSE) public.orders;. This sets the all-visible and all-frozen bits at once, so later autovacuums have little to do and index-only scans work. - Do not raise
autovacuum_freeze_max_agecasually. A higher value delays the large freeze scans, but they come later and in a worse place. You can lower it per table withALTER TABLE ... SET (autovacuum_freeze_max_age = ...), which is the safer direction. - Multixact IDs have the same problem. Row locks shared by several transactions use multixact IDs, with matching settings such as
autovacuum_multixact_freeze_max_ageandage-style functions (mxid_age()). The same fixes apply.
Exercise
A 2 TB table is almost never updated. Its age(relfrozenxid) has just passed autovacuum_freeze_max_age, and a vacuum "to prevent wraparound" has started. It is slow and reads a lot of data. What did the table lack, and what would have avoided the expensive scan?
Show answer
The table's pages were not marked all-frozen, because rows were never frozen after they were written. The anti-wraparound vacuum therefore had to read and freeze nearly all pages in one pass. Running VACUUM (FREEZE) after the initial load, or letting regular autovacuums run so pages get frozen while the data is still young, would have set the all-frozen bits. Later aggressive vacuums skip those pages and finish quickly.
Exercise
An index-only scan on a table shows a high Heap Fetches count even though the query only reads indexed columns. What is the likely cause and the fix?
Show answer
Many heap pages are not marked all-visible in the visibility map, usually because the table was recently written and not yet vacuumed, or because something blocks VACUUM. The scan must check the heap for those pages. Run VACUUM on the table (and look for long transactions or other blockers if the count stays high) so the pages are marked all-visible.