Sub topic 15
Transaction ID wraparound and freezing
This chapter assumes you know what xmin and xmax are, how a snapshot decides visibility, and what VACUUM does with dead tuples. It explains why PostgreSQL must also rewrite old, still-live rows, which is called freezing, and how to watch for the problem it prevents.
The problem: a 32-bit counter
Every row version records the transaction ID (XID) that created it in xmin. An XID is a 32-bit number. A busy database can use billions of them, so the counter eventually passes 2^32 and starts over. That restart is called wraparound.
PostgreSQL does not compare XIDs as plain integers. It compares them modulo 2^32, as if they sat on a circle. For any XID, the 2^31 (about 2.1 billion) values behind it count as "in the past" and the 2^31 values ahead count as "in the future". Visibility rules rely on this: a row whose xmin is in the past and committed can be seen, and one whose xmin is in the future cannot.
This works only while every live row is younger than about 2 billion transactions. Suppose a row is inserted by XID 1000 and never touched again. After about 2.1 billion more transactions, XID 1000 flips from "past" to "future" in the comparison. The row would suddenly look as if it was created by a transaction that has not happened yet, and every query would skip it. Nothing was deleted, but the data would vanish from view.
The fix: freezing
Freezing marks a row version as older than every possible snapshot. Once a tuple is frozen, PostgreSQL stops comparing its xmin against the XID circle and treats the row as visible to everyone, provided the inserting transaction committed.
In current versions, freezing sets flag bits in the tuple header (HEAP_XMIN_FROZEN is the combination of the "committed" and "invalid" hint bits for xmin). The original xmin value stays in place. Before PostgreSQL 9.4, vacuum overwrote xmin with the special XID 2 (FrozenTransactionId). The newer approach keeps the original value, which helps when you investigate a damaged table.
Freezing is done by VACUUM. It is the third job VACUUM does, besides removing dead tuples and updating the visibility map.
Seeing how close you are
Two catalog columns track the danger. pg_class.relfrozenxid is a table-level promise: every unfrozen XID in that table is at least this new. pg_database.datfrozenxid is the oldest relfrozenxid of any table in the database. The age() function converts an XID into "how many transactions ago".
SELECT datname, age(datfrozenxid) AS xid_age
FROM pg_database
ORDER BY xid_age DESC;To find which tables are responsible, look at the table level:
SELECT c.oid::regclass AS table_name,
age(c.relfrozenxid) AS xid_age,
pg_size_pretty(pg_total_relation_size(c.oid)) AS size
FROM pg_class c
WHERE c.relkind IN ('r', 'm', 't')
ORDER BY age(c.relfrozenxid) DESC
LIMIT 10;The relkind values cover ordinary tables, materialized views and TOAST tables. TOAST tables appear separately because they have their own relfrozenxid.
To see the freezing rows on a page, use pageinspect again. After VACUUM (FREEZE), the flags show the frozen state while t_xmin still shows the original ID:
VACUUM (FREEZE) accounts;
SELECT lp, t_xmin, t_xmax, combined_flags
FROM heap_page_items(get_raw_page('accounts', 0)),
LATERAL heap_tuple_infomask_flags(t_infomask, t_infomask2)
WHERE t_infomask IS NOT NULL;heap_tuple_infomask_flags needs PostgreSQL 13 or later. In combined_flags you should see HEAP_XMIN_FROZEN.
The settings that control freezing
| Setting | Default | Meaning |
|---|---|---|
| `vacuum_freeze_min_age` | 50 million | A normal VACUUM freezes tuples whose `xmin` is at least this many transactions old. |
| `vacuum_freeze_table_age` | 150 million | When `age(relfrozenxid)` reaches this value, VACUUM becomes aggressive and scans every page not marked all-frozen. |
| `autovacuum_freeze_max_age` | 200 million | When `age(relfrozenxid)` reaches this value, autovacuum starts an anti-wraparound vacuum, even if autovacuum is turned off. Changing it requires a server restart. |
| `vacuum_failsafe_age` | 1.6 billion | PostgreSQL 14 and later. VACUUM drops index cleanup and cost-based delays to finish freezing as fast as possible. |
You can read the current values with pg_settings:
SELECT name, setting
FROM pg_settings
WHERE name IN ('vacuum_freeze_min_age', 'vacuum_freeze_table_age',
'autovacuum_freeze_max_age', 'vacuum_failsafe_age');A normal VACUUM can skip pages that the visibility map marks all-visible. That is fast, but it cannot advance relfrozenxid, because skipped pages may still hold old XIDs. An aggressive VACUUM skips only pages marked all-frozen, so it can set a new relfrozenxid when it finishes. Since PostgreSQL 9.6 the visibility map has this all-frozen bit, so once a page is frozen and unchanged, later aggressive vacuums do not need to read it.
What happens if you ignore it
Postgres escalates in stages:
- At
autovacuum_freeze_max_age, autovacuum launches an anti-wraparound vacuum on the table. Unlike an ordinary autovacuum, it is not cancelled when another session requests a conflicting lock, so it can run long and compete for I/O. - When fewer than tens of millions of XIDs remain before the hard limit, the server logs warnings such as
database "app" must be vacuumed within N transactions. - A few million XIDs before the limit, the server refuses any command that needs a new XID. Reads still work. You must run VACUUM, and you should expect a long outage if the tables are large.
Why freezing sometimes cannot make progress
Freezing a tuple is only safe when no snapshot could still need its old state. So VACUUM cannot advance past the oldest XID that something still holds. That is the same horizon problem that causes bloat, and it has the same culprits. Check each one:
SELECT pid, state, xact_start, backend_xmin
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC;
SELECT gid, prepared, transaction
FROM pg_prepared_xacts
ORDER BY age(transaction) DESC;
SELECT slot_name, active, xmin, catalog_xmin,
age(xmin) AS xmin_age, age(catalog_xmin) AS catalog_xmin_age
FROM pg_replication_slots;- A long-running or idle-in-transaction session holds
backend_xminback. - A forgotten prepared transaction (
PREPARE TRANSACTIONthat was never committed or rolled back) holds its XID indefinitely, even across restarts. - An abandoned replication slot keeps
xminorcatalog_xminpinned. - A standby with
hot_standby_feedback = oncan hold back the primary's horizon through its own queries.
Practical points and mistakes
- Only transactions that write get a real XID. A read-only transaction uses a virtual ID that does not count toward wraparound. A transaction that uses savepoints and writes inside them can consume several XIDs, because each subtransaction that writes gets its own.
- Insert-only tables used to be a trap. They produce no dead tuples, so autovacuum had no reason to visit them until the anti-wraparound vacuum arrived, which then had to freeze everything at once. PostgreSQL 13 added insert-triggered autovacuum (
autovacuum_vacuum_insert_threshold), which spreads this work out. - Lowering
vacuum_freeze_min_agefreezes sooner, but freezing a row that is about to be updated again wastes work, because the new version needs freezing later. The default suits most workloads. For a table that is loaded once and then read, runVACUUM (FREEZE)right after the load. Then the work happens when you choose, not during a forced vacuum later. - Multixact IDs, which record multiple row lockers, have their own 32-bit counter and the same wraparound problem. Vacuum freezes them too, governed by parallel settings such as
vacuum_multixact_freeze_min_age. pg_current_xact_id()returns a 64-bitxid8that includes an epoch counting past wraparounds. This is the value to use if you need a never-repeating transaction identifier, such as for ordering application events. The 32-bit value inxminrepeats.- For a table that needs help now, run
VACUUM (FREEZE, VERBOSE) tablename;. Then re-run the age query to confirmrelfrozenxidmoved.
Exercise
A table's rows were all inserted by XID 5000 and never modified. Explain what would eventually go wrong if VACUUM never froze them, and what freezing changes in the tuple.
Show answer
PostgreSQL compares XIDs modulo 2^32. About 2^31 transactions after XID 5000, that XID would stop counting as "in the past" and start counting as "in the future", so the rows would look as if they were created by a transaction that has not started, and queries would no longer see them. Freezing sets the frozen flag bits (HEAP_XMIN_FROZEN) in the tuple header. Visibility checks then treat the row as visible to every snapshot without comparing its xmin to the current XID. The original xmin value is kept.
Exercise
age(datfrozenxid) for your database is 1.2 billion and rising, and autovacuum is running. Name the three queries you would run first and what each one is looking for.
Show answer
Query pg_stat_activity for old backend_xmin or xact_start values, which finds long-running or idle-in-transaction sessions. Query pg_prepared_xacts for old prepared transactions. Query pg_replication_slots for old xmin or catalog_xmin, which finds abandoned slots. Also check whether a standby with hot_standby_feedback is holding the horizon. After removing the blocker, run VACUUM (FREEZE) on the tables with the highest age(relfrozenxid).