Skip to main content
← CONCEPTS / SQL
An end-to-end domain learning journey

PostgreSQL MVCC, 32-Bit XID
Wraparound & Autovacuum Freezing.

PostgreSQL's 32-bit transaction IDs (XIDs) wrap modulo 2^32 (~4.29B), splitting the ring into 2B past and 2B future; unless autovacuum freezes old tuples via HEAP_XMIN_FROZEN before age(relfrozenxid) nears 2B, the database halts all writes to prevent silent data loss.
Start the journey7 sections· Last modified Nov 25, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

PostgreSQL's 32-bit transaction IDs (XIDs) wrap modulo 2^32 (~4.29B), splitting the ring into 2B past and 2B future; unless autovacuum freezes old tuples via HEAP_XMIN_FROZEN before age(relfrozenxid) nears 2B, the database halts all writes to prevent silent data loss.

TL;DR30-second simplified summary
▾

PostgreSQL implements Multi-Version Concurrency Control (MVCC) by stamping every heap tuple header with 32-bit xmin and xmax transaction IDs instead of overwriting rows in place. Because 32-bit XIDs wrap around after 4.29 billion transactions, PostgreSQL compares them using modulo-2^32 circular arithmetic: ~2 billion XIDs behind the current XID are visible past, while ~2 billion ahead are invisible future.

To prevent old committed rows from suddenly appearing to be in the future after wraparound, autovacuum freeze workers scan pg_class.relfrozenxid and mark aged tuples with the HEAP_XMIN_FROZEN bit in t_infomask. Once a page's tuples are all frozen, the Visibility Map (VM) marks the page all-frozen so future anti-wraparound scans can skip it entirely.

Under high write rates (e.g., 30,000 updates/sec), an idle reporting transaction (BEGIN; SELECT ...), orphaned replication slot, or low default autovacuum_vacuum_cost_limit=200 pins the backend xmin horizon and blocks dead-tuple cleanup. Table bloat explodes 5x and XID age climbs toward the 2B emergency shutdown wall (~1M-3M XIDs remaining), forcing PostgreSQL into read-only mode until manual single-user VACUUM FREEZE completes.

From patterns to decisions.

PostgreSQL's 32-bit transaction IDs (XIDs) wrap modulo 2^32 (~4.29B), splitting the ring into 2B past and 2B future; unless autovacuum freezes old tuples via HEAP_XMIN_FROZEN before age(relfrozenxid) nears 2B, the database halts all writes to prevent silent data loss.

Full walkthrough · 7 stages
01
foundation

Stage 1: MVCC Tuple Versioning (xmin, xmax & t_infomask).

Every INSERT writes a new tuple with xmin set to the creating XID, and every UPDATE writes a brand-new tuple version while stamping the old version's xmax with the updating XID. Readers check tuple visibility against their snapshot's xmin/xmax bounds and t_infomask hint bits rather than acquiring read locks.

FOUNDATION · HEAP TUPLE HEADERS

MVCC Row Versioning via xmin, xmax & t_infomask Hint Bits

INSERT / UPDATETupleWrite PathHeap Tuple HeaderVersion MetadataTransactionSnapshotVisibility CheckSnapshot ReadResultMVCC IsolationCompare XIDs

1.Append-Only Updates: UPDATEs leave dead tuple versions behind in heap pages until VACUUM reclaims them.

2.Hint-Bit Caching: t_infomask caches commit status so subsequent readers skip CLOG lookups.

PostgreSQL MVCC stamps every row version with 32-bit xmin and xmax headers so readers never block writers.

02
foundation

Stage 2: The 32-Bit Circular XID Ring & 2B Horizon.

PostgreSQL uses unsigned 32-bit integers (0 to 4,294,967,295) for normal XIDs. Circular comparison treats any XID within 2^31 (~2.14B) behind current_xid as past and any XID within 2^31 ahead as future. If a table's oldest unfrozen XID crosses 2B transactions behind current_xid, it wraps into the 'future' half of the ring and becomes invisible—causing silent data loss unless prevented.

FOUNDATION · CIRCULAR XID RING

Modulo-2^32 XID Arithmetic: 2B Past vs. 2B Future

Current XID CounterClock HeadVisible Past (~2BXIDs)Committed HistoryInvisible Future(~2B XIDs)Uncommitted / Future2B Wraparound WallData-Loss GuardLeading 2B window

1.High-Write Burn Rate: At 30,000 write XIDs/sec, a database consumes 2 billion XIDs in under 19 hours.

2.Hard Safety Stop: PostgreSQL refuses new XIDs ~1M-3M before wraparound to guarantee zero silent data disappearance.

Modulo-2^32 XID comparison divides 4.29B IDs into 2B past and 2B future, triggering a write halt before unfrozen rows wrap.

03
intermediate

Stage 3: HEAP_XMIN_FROZEN, relfrozenxid & the Visibility Map.

When a tuple's age exceeds vacuum_freeze_min_age (default 50M), VACUUM sets bit 0x0200 (HEAP_XMIN_FROZEN) in t_infomask so all snapshots treat it as unconditionally older than any current XID. Once every tuple on an 8 KB heap page is frozen, the Visibility Map (VM) sets the page's all-frozen bit, allowing future anti-wraparound scans to skip the page and advance pg_class.relfrozenxid.

INTERMEDIATE · FREEZING & VISIBILITY MAP

Advancing pg_class.relfrozenxid Without Full-Table Re-Scans

age(relfrozenxid)>= 200MTrigger ThresholdVisibility Map (VM)I/O AcceleratorSetHEAP_XMIN_FROZENTuple FreezeAdvancerelfrozenxidWraparound ClearScan non-frozen pages

1.Anti-Wraparound Priority: Anti-wraparound autovacuum runs even if autovacuum=off and cannot be permanently blocked by user locks.

2.Visibility Map Payoff: Append-only/cold pages marked all-frozen are skipped on subsequent freeze sweeps, cutting I/O by 90%+.

Autovacuum freeze workers set HEAP_XMIN_FROZEN on aged tuples and use the Visibility Map to skip already-frozen pages.

04
intermediate

Stage 4: How Idle Transactions & Replication Slots Pin xmin.

PostgreSQL computes a global oldest_xmin horizon across pg_stat_activity (active/idle-in-transaction sessions), prepared transactions (2PC), and pg_replication_slots (hot_standby_feedback). A single forgotten BEGIN; SELECT ... reporting session pins oldest_xmin at its start XID, preventing autovacuum from removing dead tuples or advancing xmin-dependent cleanup.

INTERMEDIATE · XMIN PINNING

Three Silent Horizon Pinners That Starve Autovacuum

Idle-in-Tx ZombieSession PinnerOrphaned ReplicationSlotReplica PinnerOrphaned 2PCTransactionPrepared PinnerPinned Global xminVacuum StarvedHold catalog_xmin

1.5x Table Bloat: While xmin is pinned, 30,000 updates/sec accumulate millions of unreclaimable dead tuples in heap pages.

2.Diagnostic Query: Always inspect pg_stat_activity (state='idle in transaction') and pg_replication_slots (active=false).

Idle-in-transaction sessions, inactive replication slots, and orphaned 2PC transactions pin global xmin and cause severe table bloat.

05
intermediate

Stage 5: Heap-Only Tuples (HOT) & fillfactor=70 Tuning.

Normally, every UPDATE must insert new index entries into every B-tree index on the table. If the updated columns are not indexed AND the same 8 KB heap page has free space, PostgreSQL performs a Heap-Only Tuple (HOT) update—chaining the new version on the same page with zero index writes. Setting fillfactor=70 reserves 30% free space per page so 30K/s updates stay HOT.

INTERMEDIATE · HOT UPDATES

Keeping 30,000 Updates/Sec Page-Local with fillfactor=70

UPDATE (Non-IndexedCol)Write WorkloadHeap Page(fillfactor=70)Page HeadroomHOT Chain + PruneFast UpdateBloat < 5% SteadyStateBounded SizeLink t_ctid on page

1.Zero Index Bloat: HOT updates avoid appending dead pointers to secondary B-tree indexes, slashing I/O and WAL volume.

2.Page-Level Pruning: Subsequent readers opportunistically prune dead HOT chains inline without waiting for autovacuum.

Reserving 30% page headroom via fillfactor=70 enables Heap-Only Tuple updates that avoid index writes and keep bloat under 5%.

06
advanced

Stage 6: Autovacuum Cost-Limit Throttling & Multi-Worker Tuning.

PostgreSQL's default autovacuum_vacuum_cost_limit=200 and cost_delay=2ms (or 20ms on older releases) throttle vacuum I/O to a crawl—allowing a 400 GB ledger at 30K updates/sec to generate dead tuples and XIDs faster than autovacuum can clean them. Raising autovacuum_vacuum_cost_limit=2000, lowering cost_delay=2ms, and scaling autovacuum_max_workers lets freeze workers finish before XID age spikes.

ADVANCED · I/O BUDGET TUNING

Unthrottling Autovacuum from Default 200 to 2000 Cost Limit

Default Cost Limit(200)BottleneckTuned Cost Limit(2000)Throughput FixMulti-Worker PoolParallel Freezerelfrozenxid < 200MHealthy ClusterDistribute across tables

1.Per-Table Overrides: High-churn ledger tables can set aggressive storage parameters (cost_limit=2000) without starving batch analytics.

2.NVMe Headroom: Modern NVMe SSDs sustain 100K+ IOPS, making default HDD-era vacuum throttling obsolete.

Raising autovacuum_vacuum_cost_limit to 2000 with 2ms delay and sufficient workers prevents vacuum starvation on high-churn tables.

07
advanced

Stage 7: Emergency Recovery & Automated Prevention Guardrails.

Preventing wraparound requires defense in depth: idle_in_transaction_session_timeout=30s and statement_timeout kill zombie readers, max_slot_keep_wal_size bounds dead replication slots, and Prometheus alerts fire when max(age(relfrozenxid)) > 150M. If a cluster ever hits the 2B read-only wall, operators must terminate blockers, start PostgreSQL in --single mode, and run VACUUM FREEZE.

ADVANCED · SRE GUARDRAILS

Defense-in-Depth Against XID Wraparound Outages

Session TimeoutsBlocker Killermax_slot_keep_wal_s…Slot GuardXID Age TelemetryEarly WarningSingle-User VACUUMFREEZERunbookDrop orphaned replicas

1.30-Second Zombie Kill: idle_in_transaction_session_timeout=30s guarantees forgotten reporting transactions cannot pin xmin for hours.

2.Early-Warning SLO: Alerting at 150M XIDs gives SREs hours of runway before the 200M anti-wraparound trigger or 2B shutdown.

Enforcing 30s idle-in-transaction timeouts, bounded replication slots, and tiered XID-age alerts prevents wraparound write freezes.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does PostgreSQL shut down all writes ~1M-3M XIDs before reaching the 2B transaction ID wraparound boundary?

Recommended Learning Flow