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

Preventing PostgreSQL VACUUM
Starvation & Bloat.

An idle-in-transaction session and a 4-hour analytics query pin PostgreSQL's oldest xmin horizon, preventing autovacuum from reclaiming 480 GB of dead tuples and degrading p99 latency 12x.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a single bottleneck threatens end-to-end availability, enforce idle_in_transaction_session_timeout and statement_timeout, isolate BI reads with hot_standby_feedback=off, and reclaim bloat online via pg_repack.

TL;DR30-second simplified summary
▾

Core Mechanics: A 180 GB PostgreSQL 15 ledger_entries table receiving 3,500 UPDATEs/s and 12,000 SELECTs/s bloated to 660 GB (82.5% of an 800 GB NVMe disk) in 10 days, pushing PK lookup p99 from 4 ms to 52 ms.

Visual & Structural Flow: Depicts Pinned xmin Blocks autovacuum Until Unblocked + pg_repack (3.5k/s UPDATEs -> Global xmin Horizon -> autovacuum -> pg_repack Online); Zero-Downtime Heap & Index Rebuild Without Long Locks (3.5k/s OLTP -> ledger_entries (660G) -> Shadow Table (180G) -> pg_repack).

Trade-Offs & Production: Running VACUUM FULL locks the 180 GB table with ACCESS EXCLUSIVE for hours, causing a total write/read outage. Restore MVCC reclamation and reclaim the 480 GB of bloat online: Unblock xmin Horizon: Query pg_stat_activity (backend_xmin) and pg_replication_slots (xmin.

Failure Modes & Application: MVCC bloat hygiene is essential for any write-heavy PostgreSQL deployment: High-Churn Ledger & Job Queue Tables: fillfactor=80 + aggressive per-table autovacuum keeps HOT updates in-page.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why PostgreSQL VACUUM Starvation & Bloat Matter.

Why this matters: The mechanism: understand how Why PostgreSQL VACUUM Starvation & Bloat Matter works from first principles.

Think of Why PostgreSQL VACUUM Starvation & Bloat Matter as the intuition layer for Preventing PostgreSQL VACUUM Starvation & Bloat: The mechanism: understand how Why PostgreSQL VACUUM Starvation & Bloat Matter works from first principles.

A 180 GB PostgreSQL 15 ledger_entries table receiving 3,500 UPDATEs/s and 12,000 SELECTs/s bloated to 660 GB (82.5% of an 800 GB NVMe disk) in 10 days, pushing PK lookup p99 from 4 ms to 52 ms. Even though autovacuum is running continuously, n_dead_tup exceeds 420M rows with zero dead tuples reclaimed—and VACUUM FULL is strictly forbidden because it takes an ACCESS EXCLUSIVE lock for hours.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of MVCC Dead-Tuple Accumulation.

Why this matters: The problem: see what breaks without Real-World Impact of MVCC Dead-Tuple Accumulation under real concurrency or scale.

In PostgreSQL MVCC, every UPDATE writes a new tuple version and marks the old one dead, relying on VACUUM to reclaim space:

  1. Horizon Pinning (xmin): A single long-running idle in transaction session, BI query on a hot_standby_feedback=on replica, or orphaned replication slot pins the global xmin horizon—forbidding autovacuum from removing any dead tuple newer than that snapshot.
  2. Index & Heap Bloat: 420M dead tuples force index/heap scans to read 3.6× more pages, evicting hot pages from shared_buffers and spiking p99 from 4 ms to 52 ms.
  3. Disk Exhaustion: At 82.5% NVMe usage, the primary risks read-only/crash shutdown before standard VACUUM can shrink files.
MVCC Horizon Pinning & Bloat

Pinned xmin Blocks autovacuum Until Unblocked + pg_repack

3.5k/s UPDATEs420M dead tuplesGlobal xmin HorizonPinned by idle-in-tx / slotautovacuum0 dead tuples removedpg_repack Online660 GB -> 180 GB (no…

1.Find Horizon Blocker: Check pg_stat_activity (backend_xmin) and pg_replication_slots.

2.Timeout Guardrails: Set idle_in_transaction_session_timeout = '60s' and statement_timeout.

3.Replica Isolation: Disable hot_standby_feedback on BI replicas so reports don't pin primary.

4.pg_repack: Rebuilds bloated 660 GB table online without ACCESS EXCLUSIVE lock.

Unpinning the xmin horizon lets autovacuum reclaim dead tuples, while pg_repack shrinks the 660 GB file online.

Engineering Decision Framework
Problem
How to implement Preventing PostgreSQL VACUUM Starvation & Bloat without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a single bottleneck threatens end-to-end availability, enforce idle_in_transaction_session_timeout and statement_timeout, isolate BI reads with hot_standby_feedback=off, and reclaim bloat online via pg_repack.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Preventing PostgreSQL VACUUM Starvation & Bloat experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive Solution (and Why It Breaks).

Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Think of Naive Solution (and Why It Breaks) as the intuition layer for Preventing PostgreSQL VACUUM Starvation & Bloat: The problem: see what breaks without Naive Solution under real concurrency or scale.

Running VACUUM FULL locks the 180 GB table with ACCESS EXCLUSIVE for hours, causing a total write/read outage. Cranking autovacuum_vacuum_cost_limit alone does nothing while an idle in transaction session or hot_standby_feedback=on replica pins xmin.

Request & State Flow

Naive Solution (and Why It Breaks)

Client TxPlanner / Lock MgrWAL / MemTableHeap / SSTable1. Acquire snapshot / index plan2. Append redo record + fsync WAL3. Flush dirty pages / compactSSTables4. Commit & release row locks
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: Unpin `xmin`, Tune `autovacuum` & Run `pg_repack`.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Restore MVCC reclamation and reclaim the 480 GB of bloat online:

  • Unblock xmin Horizon: Query pg_stat_activity (backend_xmin) and pg_replication_slots (xmin, catalog_xmin); terminate stale idle in transaction sessions and drop orphaned slots. Enforce idle_in_transaction_session_timeout = '60s'.
  • Isolate BI Replicas: Set hot_standby_feedback = off on analytics replicas (use max_standby_streaming_delay instead).
  • Online Compaction (pg_repack) + HOT Tuning: Run pg_repack -t ledger_entries to rebuild heap/indexes in a shadow table using triggers and swap metadata in milliseconds. Lower table fillfactor = 80 for HOT updates and increase autovacuum_vacuum_scale_factor = 0.01.
pg_repack Online Compaction

Zero-Downtime Heap & Index Rebuild Without Long Locks

3.5k/s OLTPledger_entries(660G)Shadow Table (180G)pg_repack1. Brief lock: attach log trigger2. Copy live rows + build indexesonline3. 3.5k/s UPDATEs continueuninterrupted4. Apply delta log + ms metadataswap

pg_repack shrinks 660 GB down to 180 GB while 3,500 UPDATEs/s and 12,000 SELECTs/s continue running.

SELECT pid, state, now() - xact_start AS age, backend_xmin FROM pg_stat_activity WHERE backend_xmin IS NOT NULL ORDER BY age(backend_xmin) DESC;

ALTER SYSTEM SET idle_in_transaction_session_timeout = '60s';
-- pg_repack --only-indexes --table ledger_entries -d prod_db

SELECT datname, age(datfrozenxid) FROM pg_database ORDER BY age(datfrozenxid) DESC;
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where PostgreSQL VACUUM & Bloat Control Apply in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

MVCC bloat hygiene is essential for any write-heavy PostgreSQL deployment:

  • High-Churn Ledger & Job Queue Tables: fillfactor=80 + aggressive per-table autovacuum keeps HOT updates in-page.
  • OLTP + BI Read-Replica Splits: hot_standby_feedback=off prevents analytics queries from bloating the primary.
  • Disk & Tail-Latency Management: pg_repack reclaims space safely without VACUUM FULL downtime.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why can `autovacuum` run continuously on a 660 GB table yet show zero dead tuples removed?

Recommended Learning Flow