0%
PostgreSQL Deep Dive: MVCC, Vacuum, Plans, and Replication
Architecture and Storage
Indexes and Query Planning
Concurrency and Schema
Transaction ID Wraparound
Every tuple in PostgreSQL stores the transaction identifiers of the transactions that created and deleted it, and those identifiers are 32 bit numbers. At thousands of transactions per second, a 32 bit counter runs out within weeks or months, so Postgres reuses identifiers in a circle. Making that safe requires that old tuples be frozen before their identifiers come around again. When freezing falls behind, Postgres first warns, then refuses to assign new transaction identifiers, which stops all writes. Wraparound outages are rare but severe, often taking hours or days to recover from on large databases, and they are entirely preventable. This lesson explains the arithmetic, the freezing machinery, the warning stages and how to keep a database far away from the limit.
Why the identifiers are 32 bits
Each tuple header carries xmin and xmax, so the size of a transaction identifier is multiplied by the number of tuples on disk. Widening them to 64 bits would add 8 bytes to every row in every table, a significant cost for narrow rows and large tables. Postgres instead keeps 32 bit identifiers in tuples and tracks a 64 bit counter internally, with an epoch that counts how many times the 32 bit space has wrapped. Functions such as pg_current_xact_id return the full 64 bit value, but tuples store only the low 32 bits, which is what makes wraparound a concern.
Circular comparison
With only 32 bits, Postgres cannot compare identifiers as plain integers once the counter wraps, since a new identifier like 5 would appear older than an old one like 4 billion. Instead, comparison is circular: for any identifier, the roughly two billion identifiers before it on the circle are considered in the past, and the two billion after it are in the future. Technically, a precedes b when the 32 bit difference a minus b, interpreted as a signed number, is negative. This works as long as no two identifiers that must be compared are more than about two billion apart.
What would go wrong
Imagine a row inserted by transaction 100 that is never touched again. When the counter reaches about 2.1 billion, 100 is just under two billion in the past, still fine. A little later, the circular comparison flips: from the point of view of new transactions, 100 is now in the future, and a tuple created in the future is invisible. The row would silently disappear from every query. This is data loss without any error, which is why Postgres treats the approach to wraparound as a critical condition and will stop accepting writes rather than let it happen.
Ages, not values
Because comparison is circular, the useful measure is not an identifier value but its age, the number of transactions between it and the current one, which the age function computes. The age of the oldest unfrozen identifier in a table is what matters, and Postgres tracks it as relfrozenxid in pg_class, a lower bound on every unfrozen xmin in the table. The oldest relfrozenxid across a database is datfrozenxid in pg_database. Monitoring the age of datfrozenxid for every database is the single most important wraparound check.
How fast ages grow
An age grows by one for every transaction identifier assigned anywhere in the cluster, since the counter is shared by all databases. A server assigning 1000 identifiers per second ages every unfrozen tuple by 86 million per day and covers two billion in about 23 days. At 10000 per second, that becomes about two and a half days. Read only transactions do not count, since they never get an identifier, but every writing transaction does, including those that roll back. The consumption rate turns the abstract limit into a concrete deadline for freezing.
Rolled back transactions count
A transaction that writes and then rolls back still consumed an identifier, and its tuples remain in the table as dead rows until vacuum removes them. Workloads with high rollback rates, such as optimistic retries, consume identifiers just as fast as successful ones. The same is true of subtransactions created by savepoints that write, each of which takes an identifier of its own. A batch that wraps every row in a savepoint can consume identifiers hundreds of times faster than its commit count suggests.
The 64 bit future
There has been long running work to move Postgres to 64 bit transaction identifiers in tuples, or to store a per page base so tuples keep 32 bit offsets. Some forks and managed services have adopted variants. In mainstream Postgres, as of recent versions, tuples still hold 32 bit identifiers and the freezing machinery described here remains essential. Even if 64 bit identifiers arrive, freezing will remain useful for setting the all frozen bits that let vacuum skip pages, so the concepts carry forward.
Where the limits come from
The comparison window is two to the 31st, about 2.147 billion. Postgres sets its hard stop a few million transactions before that, warns earlier, and triggers aggressive vacuuming much earlier, at 200 million by default. These margins exist because freezing a large database can take hours or days, and the system needs enough room to finish it after detecting the problem. The distance between the routine trigger and the stop limit is the safety margin an operator has to work with.
Wraparound is cluster wide
The transaction counter is shared by every database in the cluster, so a busy database ages the tuples in an idle one at the same rate. An idle database still needs freezing, but template0 does not allow connections and cannot be vacuumed normally, so it is kept fully frozen and never needs work. Other idle databases, including template1 and postgres, are vacuumed by autovacuum for wraparound like any other, which is one reason autovacuum must never be disabled cluster wide.
Why freezing is the answer
The fix for circular comparison is to make old identifiers irrelevant. Once every transaction that could ever need to see a tuple as not yet committed has ended, the tuple can be marked as created infinitely long ago, frozen, and its xmin is no longer compared at all. Freezing is the process of doing this to every old tuple before its age reaches the danger zone. The next section explains exactly how and when vacuum freezes.
Virtual transaction ids
Read only transactions never consume a real identifier. Every transaction gets a virtual transaction id, made of the backend id and a local counter, which is enough to identify it for locking and for snapshots. A real xid is assigned lazily, the first time the transaction writes. This is why a workload dominated by reads barely moves the counter, and why one stray write inside an otherwise read only path, such as touching a session row, can multiply xid consumption.
Checking the rate
The xid rate is easy to measure: sample pg_current_xact_id or txid_current_snapshot at two points in time and divide the difference by the interval, or graph the xact_commit and xact_rollback counters in pg_stat_database as an approximation. Knowing the rate converts every age into a time, so an alert at one billion can say how many days remain. The rate also reveals regressions, such as a deploy that started wrapping every row in a savepoint.
Subtransactions and their cost
Each savepoint that writes allocates its own subtransaction xid and records its parent in pg_subtrans. Beyond xid consumption, a backend with more than 64 subtransactions overflows its cached subxid list, which forces other sessions computing snapshots to consult pg_subtrans, a known source of severe slowdowns on busy systems. Frameworks that create a savepoint per statement can trigger both problems, so it pays to know whether the ORM in use does this.
Tuples store 32 bit xids compared on a circle with a two billion window. The age of the oldest unfrozen xid grows with every xid assigned anywhere in the cluster, including rollbacks and subtransactions. Measure your xid rate and keep every database far below the limit.