Video in progress

What is transaction ID wraparound, and why might Postgres stop accepting writes in that situation?

Transaction IDs are 32-bit and wrap around; if old rows aren't "frozen", there's a risk they start to look like they belong to a future transaction. To prevent that, Postgres refuses new transactions when it gets close to the limit.

📖 Answer

XIDs form a circle of about 4 billion values. For each transaction, half of it is the "past" and half is the "future". If a row's xmin falls more than 2 billion behind, it suddenly crosses into the future and becomes invisible, meaning the data "disappears".

Postgres handles this with VACUUM FREEZE: it marks old rows as "visible to everyone". When autovacuum_freeze_max_age (default 200 million) is reached, autovacuum forces an aggressive scan of the table, even if autovacuum has been turned off.

When the problem shows up:

  • a very write-heavy system (thousands of transactions per second);
  • a transaction left open for days, or an abandoned prepared transaction;
  • a replication slot that stopped working;
  • autovacuum configured too weakly.

To monitor:

SELECT datname, age(datfrozenxid) FROM pg_database ORDER BY 2 DESC;
SELECT relname, age(relfrozenxid) FROM pg_class
WHERE relkind = 'r' ORDER BY 2 DESC LIMIT 10;

In practice I set an alert when age is around 500 million. When it gets very close to the limit (about 3 million XIDs left), Postgres starts refusing commands that need a new XID ("database is not accepting commands ... to avoid wraparound data loss"): reads work, writes don't. Up to PG16, single-user mode was often recommended to get out of this; now a plain VACUUM is enough, and on a big table that means hours of vacuum. The cause is almost always that something is holding vacuum back.