Skip to content

VACUUM strategies for very large PostgreSQL tables

Tune autovacuum for large PostgreSQL tables — per-table thresholds, parallel workers, freeze management, and the patterns that prevent transaction-ID wraparound.

Default autovacuum settings work for tables up to about 100 GB. Past that — events tables, audit logs, large fact tables — autovacuum starts to fall behind, bloat creeps in, and eventually the dreaded transaction-ID wraparound warning appears in the logs. This article covers per-table autovacuum tuning, parallel workers, freeze management, and the operational habits that keep large Postgres tables healthy long-term.

How to verify

Check autovacuum health and the freeze horizon:

psql -d app -c "SELECT relname,
                       n_live_tup, n_dead_tup,
                       round(n_dead_tup * 100.0 / NULLIF(n_live_tup,0), 1) AS dead_pct,
                       last_vacuum, last_autovacuum,
                       last_analyze, last_autoanalyze
                FROM pg_stat_user_tables
                WHERE n_dead_tup > 100000
                ORDER BY n_dead_tup DESC LIMIT 20;"
psql -d app -c "SELECT datname,
                       age(datfrozenxid) AS xid_age,
                       2^31 - age(datfrozenxid) AS xids_remaining
                FROM pg_database
                ORDER BY age(datfrozenxid) DESC;"
psql -d app -c "SELECT * FROM pg_stat_progress_vacuum;"

xids_remaining is the metric to alert on. Below 500 million is yellow; below 100 million is red — wraparound at 0 takes the database offline.

What’s happening

PostgreSQL uses MVCC: every row has an xmin (transaction that created it) and an xmax (transaction that deleted it, if any). When an UPDATE happens, the old version is marked deleted-by-this-xid and a new version is written. Eventually the old version is dead — no transaction can see it — and VACUUM reclaims the space.

There are two costs that scale with table size:

  1. Bloat. Dead tuples take up disk. Autovacuum kicks in when dead tuples exceed autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor * reltuples. The default scale factor is 0.2 — vacuum when 20% of rows are dead. On a 1 billion row table that’s 200 million dead rows before autovacuum starts; 200 million rows of bloat is a lot of disk.

  2. Freezing. Transaction IDs are 32-bit and wrap around at 4 billion. To prevent the wraparound from confusing visibility checks, VACUUM “freezes” old tuples — marks them as “always visible” so the xmin doesn’t matter. Autovacuum runs an aggressive freeze pass when age(relfrozenxid) exceeds autovacuum_freeze_max_age (200M by default). On a large append-only table, the freeze pass scans the entire heap — which can take hours.

The right approach for large tables: tune per-table autovacuum thresholds, run more aggressive freezing earlier, and use parallel vacuum on PG 13+.

The procedure

  1. Set per-table autovacuum thresholds:

    ALTER TABLE events SET (
      autovacuum_vacuum_scale_factor = 0.02,        -- vacuum at 2% dead
      autovacuum_analyze_scale_factor = 0.01,
      autovacuum_vacuum_cost_limit = 2000,          -- faster vacuum, more I/O
      autovacuum_vacuum_cost_delay = 2,
      autovacuum_freeze_max_age = 100000000,        -- freeze every 100M xids
      autovacuum_multixact_freeze_max_age = 100000000
    );

    Lower scale factor = vacuum sooner. The cost limits control how much I/O autovacuum uses per round — default is intentionally conservative. On modern SSD-backed hosts, raising the cost limit and lowering the delay lets autovacuum keep up.

  2. Use parallel vacuum (PG 13+):

    VACUUM (PARALLEL 4) events;

    Splits the index-cleanup phase across 4 workers. Useful for big tables with many indexes — cuts cleanup time substantially. Autovacuum also supports parallel vacuum since 13.

  3. Tune the server-wide autovacuum workers and cost:

    autovacuum_max_workers = 6                       # default 3
    autovacuum_naptime = 30s                         # default 60s
    maintenance_work_mem = 2GB                       # default 64MB
    autovacuum_work_mem = 1GB                        # PG 16+
    vacuum_cost_limit = 2000                         # raise from 200

    maintenance_work_mem is the index-cleanup memory; raising it dramatically speeds up index vacuum on large tables.

  4. Run manual freeze in maintenance windows for very large tables:

    VACUUM (FREEZE, VERBOSE, PARALLEL 4) events;

    On a 1 TB events table this can take 8-24 hours. Schedule it before autovacuum’s emergency wraparound vacuum would trigger. The VERBOSE output tells you how many pages were frozen.

  5. Monitor age across databases:

    SELECT n.nspname || '.' || c.relname AS table_name,
           age(c.relfrozenxid) AS xid_age,
           pg_size_pretty(pg_total_relation_size(c.oid)) AS size
    FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
    WHERE c.relkind IN ('r', 'm', 'p')
    ORDER BY age(c.relfrozenxid) DESC LIMIT 20;

    The oldest-xid table is your wraparound risk; prioritise its freeze.

  6. Watch progress on running vacuums:

    SELECT pid, datname, relid::regclass, phase,
           heap_blks_total, heap_blks_scanned, heap_blks_vacuumed,
           index_vacuum_count
    FROM pg_stat_progress_vacuum;

    phase = 'vacuuming indexes' on a 12-index table is where most vacuum time is spent — maintenance_work_mem matters here.

Common pitfalls

  • A long-running transaction (a forgotten session, a slow analytical query) holds back the global xmin horizon — autovacuum can’t reclaim any row newer than the start of that transaction. Set idle_in_transaction_session_timeout and statement_timeout.
  • Replication slots also pin the horizon — an abandoned logical replication slot is silent xmin drag. Monitor pg_replication_slots.xmin.
  • VACUUM FULL is the only way to return disk to the OS, but it takes ACCESS EXCLUSIVE. Use pg_repack for online rebuilds.
  • Autovacuum doesn’t compete with itself well — if a slow autovacuum is running and the system needs to run a wraparound vacuum, you may need to cancel and restart manually with higher cost_limit.
  • The autovacuum logs at autovacuum_naptime intervals into the regular Postgres log; log_autovacuum_min_duration = 0 logs every run — useful for the first weeks of tuning, then ratchet up.

In the engagements we run, every large Postgres table gets per-table autovacuum settings during onboarding — defaults aren’t sufficient past 100 GB. We schedule manual freezes for tables with append-only patterns, monitor xid_age and xmin across the fleet, and treat any growth in dead tuples or long-running transactions as a first-class signal. The combination keeps the database healthy for years without a wraparound emergency. For the operating model behind a Postgres footprint at this scale, see managed operations.