dataiotech Labs
Back to Performance Guide
[PostgreSQL]RUNBOOKPostgreSQL 16 / 1724 minSenior DBA / SRE

[PostgreSQL] RUNBOOK + DEEP DIVE: Vacuum, Analyze, and Autovacuum Tuning

PostgreSQL MVCC generates dead row versions on every UPDATE and DELETE. Stale vacuum cycles trigger table and index bloat, stale statistics, and catastrophic transaction ID wraparound outages.

Production Incident Scenario

A 2GB table expands to 18GB over 3 months despite flat row counts. Disk usage explodes, Index Only Scans trigger massive Heap Fetches due to dirty visibility maps, and weekly storage alarms sound. Bloated dead tuples indicate autovacuum saturation.

Overview and MVCC Foundations

Vacuum is the most frequently misunderstood operational mechanism in PostgreSQL. Many engineers treat it merely as a background garbage collector. In reality, vacuum sits at the exact center of query performance, disk storage allocation, lock queue dynamics, and database uptime.

When vacuum lags, table heaps bloat, B-Tree indexes swell, query execution plans degrade, disk partitions fill, and in the worst-case scenario, transaction ID exhaustion forces the cluster into emergency read-only shutdown.

In this runbook and deep dive, you will learn the mechanics of MVCC, how the autovacuum daemon schedules cleanup work, how to identify lagging tables, how to tune autovacuum thresholds per table safely, and how to recover bloated relations online without downtime.


Scenario

The 9x Bloat Incident. A mission-critical orders table initially measured 2 GB. Over three months of steady production traffic, its physical on-disk size expanded to 18 GB. The active row count remained virtually unchanged (even dropping slightly due to archival jobs), yet the table consumed nine times more storage.

Query performance degraded systematically. In EXPLAIN ANALYZE, fast Index Only Scan executions vanished, replaced by slow scans where Heap Fetches exploded into the hundreds of thousands. Storage alerts trigger weekly. The application team proposes dropping and recreating the table.

The defect is not the table schema; it is autovacuum saturation. Deleted and updated rows were never physically purged; they lingered as dead tuple corpses within the heap pages. Autovacuum was simply unable to keep pace with the write rate.


Why Vacuum Exists: Understanding PostgreSQL MVCC

PostgreSQL implements Multi-Version Concurrency Control (MVCC). When a transaction updates an existing row, the engine does not overwrite the physical bytes on disk in-place. Instead, it creates an entirely new version of the tuple with a new xmin transaction header and marks the old version as dead by setting its xmax header.

Consider an update:

sql
UPDATE customers SET email = 'new@example.com' WHERE id = 123;

PostgreSQL executes this under the hood as follows:

  1. 1It writes a brand new tuple containing new@example.com into the table page.
  2. 2It stamps the existing row version as expired (xmax = current_txid).
  3. 3It retains the expired row version because concurrent transactions that began earlier may still require it for snapshot isolation.

Once all concurrent transactions that could possibly see the old version have committed or terminated, that row becomes a dead tuple.

The core responsibility of VACUUM is to reclaim the space occupied by dead tuples, mark page free space in the Free Space Map (FSM), and update the Visibility Map (VM). Without vacuum, dead tuples accumulate, pages fragment, sequential scans must read gigabytes of dead data, and B-Tree indexes swell with dead leaf pointers.


VACUUM vs ANALYZE vs AUTOVACUUM

These three operations must be strictly differentiated:

▸VACUUM (Standard)

Purges dead tuples, updates the Free Space Map, and marks all-visible pages in the Visibility Map (enabling lightning-fast Index Only Scans).

sql
VACUUM orders;
  • •Concurrency: Non-blocking. Does not acquire an exclusive lock; applications can continue reading and writing concurrently.
  • •Limitation: It returns space to the internal table page pool for future inserts; it does not shrink the physical file on the operating system filesystem (unless dead tuples happen to reside at the very physical end of the file).

▸VACUUM FULL

Re-writes the entire physical relation into a brand-new, completely compact disk file, returning all unused disk space to the OS.

sql
VACUUM FULL orders;
  • •DANGER: Acquires an AccessExclusiveLock. It completely blocks all read and write operations until it finishes. Never run VACUUM FULL on large production tables during business hours. Use pg_repack instead.

▸ANALYZE

Inspects a statistical sample of rows in the relation and populates the pg_statistic system catalog.

sql
ANALYZE orders;
  • •Updates row count estimates, distinct values, null fractions, and most common value (MCV) histograms.
  • •Non-blocking and very fast. Essential for query planner accuracy.

▸AUTOVACUUM

The autonomous background daemon that orchestrates VACUUM and ANALYZE automatically whenever a table crosses calculated dead-tuple thresholds.


How Autovacuum Decides: Threshold Formulas

Autovacuum evaluates every relation against mathematical formulas:

▸The Vacuum Trigger Threshold

📐 Formül:\text{Threshold} = \text{autovacuum\_vacuum\_threshold} + (\text{autovacuum\_vacuum\_scale\_factor} \times \text{reltuples})

Default Settings:

  • •autovacuum_vacuum_threshold = 50
  • •autovacuum_vacuum_scale_factor = 0.2 (20%)

For a table with 1,000,000 rows, autovacuum will not wake up until:

📐 Formül:50 + (0.20 \times 1,000,000) = 200,050 \text{ dead tuples}

On a 20-million-row table, the default formula requires 4 million dead tuples before autovacuum triggers. By that time, the table has bloated by gigabytes and performance has already degraded.


▸The Analyze Trigger Threshold

📐 Formül:\text{Threshold} = \text{autovacuum\_analyze\_threshold} + (\text{autovacuum\_analyze\_scale\_factor} \times \text{reltuples})

Default Settings:

  • •autovacuum_analyze_threshold = 50
  • •autovacuum_analyze_scale_factor = 0.1 (10%)

On a 10-million-row table, 1,000,000 rows must mutate before statistics are updated, causing the query planner to run blind on stale cardinality models.


Step 1: Detect Bloated Tables and Dead Tuples

Run this diagnostic query to isolate the top 20 tables with the highest dead tuple volume:

sql
SELECT schemaname, relname AS table_name, n_live_tup AS live_tuples, n_dead_tup AS dead_tuples, round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) AS dead_tuple_ratio_pct, last_vacuum, last_autovacuum, last_analyze, last_autoanalyze FROM pg_stat_user_tables WHERE (n_live_tup + n_dead_tup) > 10000 ORDER BY n_dead_tup DESC LIMIT 20;

Assessment Criteria:

  • •Dead Ratio > 20%: Autovacuum is lagging behind the write rate.
  • •Dead Ratio > 50%: Severe bloat emergency. More than half the disk space read by queries contains obsolete garbage.
  • •`last_autovacuum` is NULL: The table has never been processed by autovacuum since instance startup or creation.

Step 2: Inspect Active Autovacuum Progress

PostgreSQL provides real-time worker telemetry in pg_stat_progress_vacuum:

sql
SELECT p.pid, c.relname AS table_name, p.phase, p.heap_blks_total, p.heap_blks_scanned, round(100.0 * p.heap_blks_scanned / NULLIF(p.heap_blks_total, 0), 2) AS scan_progress_pct, p.heap_blks_vacuumed, p.num_dead_tuples FROM pg_stat_progress_vacuum p JOIN pg_class c ON c.oid = p.relid;

Phases of Vacuum:

  1. 1scanning heap: Reading table pages into buffer memory to discover dead tuples.
  2. 2vacuuming indexes: Scanning every B-Tree/GIN index on the table to prune pointers matching dead tuples.
  3. 3vacuuming heap: Returning to table pages to mark dead tuple slots as free space.
  4. 4truncating heap: Attempting to shrink the file tail if empty pages exist at the end.

Step 3: Why Does Autovacuum Fall Behind? (The 4 Blockers)

If autovacuum is not running or takes days to complete, investigate these four blockers:

▸1. Long-Running Transactions and Idle In Transaction

Vacuum cannot remove any dead tuple that is newer than the oldest open transaction (Oldest XMIN). If an analytical report or an forgotten terminal session opened a transaction 4 hours ago, vacuum is blocked from cleaning any dead tuple created during those 4 hours across the entire database.

sql
SELECT pid, usename, state, now() - xact_start AS duration, query FROM pg_stat_activity WHERE xact_start IS NOT NULL ORDER BY xact_start ASC LIMIT 5;

▸2. Throttled Cost Limits (autovacuum_vacuum_cost_limit)

PostgreSQL intentionally throttles autovacuum I/O so background workers do not overwhelm client queries.

  • •Default: autovacuum_vacuum_cost_limit = 200 (historically 200, often bumped to 1000–2000 on modern NVMe drives).
  • •Default: autovacuum_vacuum_cost_delay = 2ms.

If cost limits are too low, vacuum sleeps constantly and cannot keep up with high-write ingestion.


▸3. Worker Concurrency Saturation

PostgreSQL defaults to autovacuum_max_workers = 3. If 3 large multi-gigabyte tables occupy the 3 available worker slots, all other tables in the database are starved of vacuuming and analyzing.


▸4. Explicit Lock Conflicts

Autovacuum requires a lightweight ShareUpdateExclusiveLock. If an application migration runs ALTER TABLE or a long-running batch job locks the table, autovacuum yields and backs off.


Step 4: Per-Table Tuning (The Gold Standard)

Never adjust global autovacuum settings aggressively across an entire cluster to accommodate one heavy table. Tune the specific hot tables directly using table-level storage parameters:

sql
-- Set aggressive autovacuum thresholds on high-write table ALTER TABLE orders SET ( autovacuum_vacuum_scale_factor = 0.05, -- Trigger at 5% dead tuples instead of 20% autovacuum_vacuum_threshold = 1000, autovacuum_analyze_scale_factor = 0.02, -- Refresh stats at 2% changes instead of 10% autovacuum_vacuum_cost_limit = 2000, -- Allocate dedicated I/O budget autovacuum_vacuum_cost_delay = 0 -- Eliminate sleep throttling on NVMe storage );

Verify current table configuration:

sql
SELECT relname, reloptions FROM pg_class WHERE relname = 'orders';

Step 5: Online Defragmentation Without Downtime (pg_repack)

Once a table is physically bloated (e.g., 2 GB of data occupying 18 GB of disk), standard VACUUM cannot shrink the file. You have two options:

▸Option A: pg_repack (Zero-Downtime Standard)

pg_repack is an open-source extension that builds a new copy of the table in the background, streams incremental changes via triggers, and swaps the tables in an instantaneous metadata lock (< 1 second):

bash
# Run online table defragmentation pg_repack -h localhost -U postgres -d production_db -t orders
  • •Reads and writes remain fully functional throughout the repack.
  • •Requires free disk space equal to the size of the table and its indexes.

▸Option B: Scheduled VACUUM FULL (Maintenance Window Only)

If pg_repack is unavailable, schedule a maintenance window and run:

sql
-- WARNING: Blocks all concurrent traffic VACUUM FULL orders;

The Ultimate Disaster: Transaction ID Wraparound

PostgreSQL uses 32-bit transaction IDs ($\approx 4.2 \text{ billion}$ distinct transaction numbers). To prevent arithmetic wraparound where old committed data appears in the future, autovacuum must freeze old transaction IDs (FREEZE).

If autovacuum is disabled or permanently blocked by long open transactions:

sql
SELECT datname, age(datfrozenxid) AS xid_age FROM pg_database ORDER BY xid_age DESC;
  • •When `age(datfrozenxid) > 200,000,000`: Autovacuum enters aggressive emergency freeze mode (autovacuum_freeze_max_age). Workers ignore cost limits and consume maximum I/O.
  • •When `age(datfrozenxid) > 2,140,000,000`: PostgreSQL enters read-only emergency protection and refuses to accept further write connections until vacuumed in single-user maintenance mode.

Operational Checklist

  • Top 20 tables with the highest dead tuple counts listed
  • Tables exceeding a 20% dead tuple ratio identified
  • Autovacuum daemon status confirmed running
  • Active autovacuum workers inspected in pg_stat_progress_vacuum
  • Long-running and idle-in-transaction sessions checked
  • Per-table autovacuum scale factors tuned for high-write tables
  • Global autovacuum parameters tuned conservatively
  • pg_repack maintenance plan scheduled for severely bloated relations
  • Maintenance window defined before running VACUUM FULL
  • Transaction ID age checked against autovacuum_freeze_max_age
  • 24-hour observation window conducted post-tuning
  • Relation physical disk size and n_dead_tup verified

Related Guides in Series

  • •Pillar: Performance & Query Optimization
  • •Cluster: Finding Top 20 Expensive Queries with pg_stat_statements
  • •Cluster: The N+1 Query Problem and Connection Pool Saturation
  • •Cluster: Reading and Deconstructing EXPLAIN ANALYZE
  • •Cluster: Index Architecture: B-Tree, Hash, GiST, GIN, BRIN Deep Dive
Operational Checklist

Verify each operational safety check before completing the task: