Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Preventing PostgreSQL XID Wraparound
Outages & Autovacuum Starvation.

Harden a 400 GB PostgreSQL ledger handling 30,000 updates/sec against 5x MVCC table bloat and emergency 2B XID wraparound write freezes.
Start the journey7 stages· Last modified Nov 25, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Harden a 400 GB PostgreSQL ledger handling 30,000 updates/sec against 5x MVCC table bloat and emergency 2B XID wraparound write freezes.

From patterns to decisions.

Harden a 400 GB PostgreSQL ledger handling 30,000 updates/sec against 5x MVCC table bloat and emergency 2B XID wraparound write freezes.

Full walkthrough · 7 stages
01
foundation

Stage 1: Incident Anatomy — 30K/s Ledger & Emergency Write Freeze.

At 30,000 write XIDs/sec, PostgreSQL consumes ~108M XIDs per hour and hits the 2B wraparound limit in ~18.5 hours if relfrozenxid cannot advance. Meanwhile, unreclaimed dead tuples inflate a 400 GB table to 2 TB (5x bloat), degrading buffer-cache hit ratios and slowing every sequential/index scan until the emergency shutdown triggers.

FOUNDATION · INCIDENT TIMELINE

How 30,000 Updates/Sec Hits the 2B XID Wall in < 19 Hours

30,000 WriteXIDs/secXID Burn RatePinned Global xminBlocker5x Heap & IndexBloatI/O Collapse2B Emergency WriteFreezeOutageBlock vacuum reclamation

1.18.5-Hour Runway: At 30K XIDs/sec, even a half-day autovacuum stall pushes a table close to the 2B limit.

2.Compounding Slowdown: 5x bloat makes any eventual VACUUM scan 5x slower to complete.

At 30,000 updates/sec, pinned xmin and throttled vacuum bloat tables 5x and exhaust the 2B XID runway in under 19 hours.

02
foundation

Stage 2: Live Triage Queries (pg_stat_activity & pg_class).

During an active XID-age spike, operators must immediately rank tables by age(relfrozenxid) in pg_class and cross-reference pg_stat_activity for backend_xmin holders and pg_replication_slots for inactive xmin/catalog_xmin pins. Terminating a single zombie PID via pg_terminate_backend(pid) unblocks autovacuum within seconds.

FOUNDATION · LIVE TRIAGE

Three-Query Incident Triage to Unpin Global xmin

pg_class.relfrozen…Target Finderpg_stat_activitySession Auditpg_replication_slo…Slot Auditpg_terminate_backe…MitigationKill idle-in-tx PID

1.Check Subtransactions: Monitor pg_stat_activity wait events for SubtransSLRU contention alongside backend_xmin.

2.Safe Slot Drop: Verify consumer replica is decommissioned before calling pg_drop_replication_slot().

Inspecting pg_class, pg_stat_activity, and pg_replication_slots pinpoints the exact blocker holding back relfrozenxid.

03
intermediate

Stage 3: Enforcing Session Timeouts & Replication WAL Caps.

Manual triage is too slow at 30K XIDs/sec. Setting idle_in_transaction_session_timeout = '30s' and statement_timeout = '15s' on OLTP/reporting roles automatically aborts forgotten BEGIN; SELECT sessions. Setting max_slot_keep_wal_size = '20GB' invalidates disconnected replication slots before they pin xmin or fill pg_wal.

INTERMEDIATE · BLOCKER PREVENTION

Automated Guardrails Against Zombie Sessions & Dead Slots

OLTP / BIConnectionsClient Trafficidle_in_tx_timeout =30sSession Guardmax_slot_keep_wal =20GBSlot GuardUnpinned GlobalxminHealthy HorizonFree backend_xmin

1.Replica Read Isolation: Route long-running BI analytics to a dedicated read replica without hot_standby_feedback.

2.PgBouncer Transaction Pooling: Transaction-mode pooling returns connections immediately after COMMIT, reducing idle-in-tx risk.

30-second idle-in-transaction timeouts and max_slot_keep_wal_size prevent zombie sessions and dead slots from pinning xmin.

04
intermediate

Stage 4: HOT Updates with fillfactor=70 on Update-Heavy Tables.

On the 400 GB ledger, setting ALTER TABLE ledger SET (fillfactor = 70); reserves 30% free space on every 8 KB heap page. Non-indexed column updates stay on the same heap page as Heap-Only Tuples (HOT), eliminating secondary B-tree index writes and allowing inline page pruning to keep steady-state bloat under 5%.

INTERMEDIATE · BLOAT CONTROL

fillfactor=70 + Inline Page Pruning for < 5% Bloat

ALTER TABLEfillfactor=70Page ConfigSame-Page HOT UpdateWrite OptimizationInline Page PruningFast ReuseBloat < 5% SteadyStateStorage TargetPrune dead chains inline

1.REPACK / pg_repack: Existing 5x-bloated tables require online pg_repack (or VACUUM FULL) after setting fillfactor=70 to rewrite dense pages.

2.Index Column Hygiene: Avoid indexing monotonically updated timestamp/counter columns that would disqualify HOT updates.

Reserving 30% free space per page with fillfactor=70 enables HOT updates and inline pruning, holding bloat under 5%.

05
intermediate

Stage 5: Autovacuum Cost-Limit & Worker Scaling.

Default autovacuum_vacuum_cost_limit=200 caps vacuum at ~8 MB/s per worker—far too slow for a 400 GB table at 30K updates/sec. Increasing autovacuum_vacuum_cost_limit=2000 (with cost_delay=2ms), lowering autovacuum_vacuum_scale_factor=0.01, and setting autovacuum_max_workers=6 gives freeze workers 10x I/O throughput without starving OLTP queries.

INTERMEDIATE · VACUUM THROUGHPUT

10x Autovacuum I/O Budget & Scale-Factor Tuning

scale_factor = 0.01Trigger Policycost_limit = 2000 /2msRate Limitermax_workers = 6Worker Poolrelfrozenxid < 200MSLO MetAllocate 2000 cost credits

1.Shared Cost Balance: Remember autovacuum_vacuum_cost_limit is shared across active workers unless overridden per table.

2.maintenance_work_mem: Set maintenance_work_mem=1GB..2GB so VACUUM stores dead-tuple TIDs in 1 pass instead of multiple index scans.

Tuning cost_limit=2000, scale_factor=0.01, and maintenance_work_mem=1GB lets autovacuum keep pace with 30K updates/sec.

06
advanced

Stage 6: Partitioning & Subtransaction Avoidance at 30K/s.

Vacuuming a monolithic 400 GB table takes hours even with tuned I/O; range-partitioning by day or week limits active vacuuming to ~20 GB hot partitions while cold partitions stay 100% all-frozen in the Visibility Map. Additionally, eliminating nested SAVEPOINT / PL/pgSQL EXCEPTION blocks avoids subtransaction XID burn and SubtransSLRU lock contention.

ADVANCED · PARTITIONING & SUBTX

Bounding Freeze Blast Radius with Partitioned Hot Tables

Weekly LedgerPartitionsTable LayoutCold Partitions (VMFrozen)Skipped DataZero-SAVEPOINTPolicyXID Hygiene4-Minute Hot FreezeBounded RecoveryVacuum only hot partition

1.95% I/O Reduction: Partitioning shrinks active freeze scans from 400 GB to a 20 GB hot partition (~4.3 minutes).

2.Subtransaction Trap: A single transaction with 1,000 SAVEPOINTs burns 1,000 XIDs and can trigger SubtransSLRU stalls.

Range partitioning shrinks freeze scans from 400 GB to 20 GB hot partitions while avoiding SAVEPOINT XID amplification.

07
advanced

Stage 7: Tiered XID-Age Alerting & Single-User Emergency Runbook.

Export max(age(relfrozenxid)) and max(age(datfrozenxid)) every 60 seconds with alerts at 150M (info), 500M (page on-call), and 1.5B (critical). If a cluster ever reaches the 2B read-only wall, stop application pools, start postgres --single -D $PGDATA <db>, execute VACUUM FREEZE;, and restart normal multi-user service.

ADVANCED · TELEMETRY & RECOVERY

Tiered XID-Age Alerting & Single-User Emergency Thaw

pg_exporter (60sScrape)Telemetry500M XID Page AlertOn-Call Gate1.997B Read-OnlyWallSafety Haltpostgres --singleModeEmergency ThawIf unmitigated

1.Database-Wide datfrozenxid: Remember pg_database.datfrozenxid tracks the oldest relfrozenxid across all tables—even unused template0/postgres DBs.

2.Pre-Freeze Verification: Confirm disk space headroom before running VACUUM FREEZE so WAL generation does not fill $PGDATA.

60-second XID-age telemetry catches wraparound hours early, while single-user VACUUM FREEZE provides deterministic recovery.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

In Production Scenario #28, which two factors combined to push the 400 GB ledger into an XID wraparound write freeze?

Recommended Learning Flow