How to Tune PostgreSQL Autovacuum for Busy Tables
Stop bloat and transaction ID wraparound by setting per-table autovacuum thresholds, scale factors and cost limits that match your write rate.
On this page
Introduction
PostgreSQL does not update a row in place. An UPDATE writes a new version and marks the old one dead; a DELETE marks the row dead. Those dead tuples stay in the table and its indexes until vacuum reclaims them. Autovacuum does that reclamation in the background, and it also advances the frozen transaction horizon that protects the database from transaction ID wraparound, a failure mode that can take the whole cluster read-only. The default autovacuum settings are tuned for small databases and moderate write rates, which is why busy tables bloat, indexes grow without bound, and wraparound warnings appear. This article explains how autovacuum decides when to run, how to read the signals that say it is losing, and how to tune it per table.
Why the Defaults Fail at Scale
Autovacuum triggers a vacuum on a table when the number of dead tuples exceeds a threshold: autovacuum_vacuum_threshold plus autovacuum_vacuum_scale_factor times the number of live rows. The scale factor default is 0.2, so a table with ten million rows waits until two million rows are dead before autovacuum cleans it. By then the table has grown substantially and the vacuum has much more work to do, which makes it slower and more likely to fall behind. The same logic applies to the analyze scale factor, which controls when statistics are refreshed.
A second default that hurts busy systems is cost-based throttling. Autovacuum sleeps between pages according to autovacuum_vacuum_cost_delay, which is deliberately gentle. On a high-throughput database the vacuum sleeps more than it works and never catches up, so dead tuples accumulate faster than they are removed. The fix is not to disable throttling globally, which can hurt latency for everyone, but to tune it per table where the write rate is high.
Reading Bloat and Dead Tuples
Before changing settings, measure. Query the statistics views to see how many dead tuples each table holds and when it was last vacuumed and analyzed. The difference between n_live_tup and n_dead_tup tells you the backlog; last_autovacuum tells you whether autovacuum is keeping up. A table whose dead tuples only fall at manual vacuum time is one autovacuum is not reaching.
-- Dead-tuple backlog and last activity per table
SELECT relname,
n_live_tup,
n_dead_tup,
CASE WHEN n_live_tup > 0
THEN round(100.0 * n_dead_tup / (n_live_tup + n_dead_tup), 1)
ELSE 0 END AS dead_pct,
last_vacuum, last_autovacuum, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;
-- Table and index sizes, to separate heap bloat from index bloat
SELECT c.relname AS object,
pg_size_pretty(pg_relation_size(c.oid)) AS size
FROM pg_class c
WHERE c.relkind IN ('r', 'i')
ORDER BY pg_relation_size(c.oid) DESC
LIMIT 20;
Per-Table Thresholds and Scale Factors
The most effective change is to lower the scale factor and threshold for hot tables using storage parameters, so autovacuum runs more often on smaller batches of dead tuples. Running frequently on a small backlog is cheaper than running rarely on a huge one, because the vacuum reads fewer pages and holds fewer locks at once. Set these parameters per table rather than globally so cold tables keep the inexpensive defaults.
ALTER TABLE events SET (
autovacuum_vacuum_threshold = 5000,
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_analyze_threshold = 2500,
autovacuum_analyze_scale_factor = 0.01
);
ALTER TABLE events SET (
autovacuum_vacuum_cost_delay = 0, -- do not sleep on this hot table
autovacuum_vacuum_cost_limit = 10000
);
SELECT relname, reloptions FROM pg_class WHERE relname = 'events';
Cost-Based Throttling and Vacuum Cost Delay
Cost-based throttling limits how much I/O vacuum performs per interval. The cost limit counts pages touched, with different weights; when the accumulated cost exceeds the limit, vacuum sleeps for the cost delay before continuing. Raising the cost limit or lowering the delay lets vacuum do more work per unit time. On dedicated hardware it can be acceptable to set the delay to zero for the busiest tables, trading a small latency cost for keeping the table lean. On shared infrastructure, raise the limit moderately first and watch query latency.
Increase max_parallel_maintenance_workers where available: a parallel vacuum can use multiple workers on the index portion, finishing faster and reducing the window during which the table is unavailable for DDL. Balance worker count against the CPU the database needs for foreground traffic.
Monitoring Wraparound and Vacuum Progress
Every transaction consumes a transaction ID, and the space is finite and circular. If the oldest unfrozen transaction ID falls too far behind the current one, PostgreSQL will refuse new writes and shut down cleanly to avoid data loss. Autovacuum is what prevents this by freezing old rows. Monitor the age of the oldest transaction ID per database and alert well before the danger zone; do not wait for the warning in the log.
-- Highest transaction-ID age; the closer to 2 billion, the more urgent
SELECT datname,
age(datfrozenxid) AS xid_age,
round(100.0 * age(datfrozenxid) / 2000000000, 2) AS pct_to_wraparound
FROM pg_database
ORDER BY age(datfrozenxid) DESC;
-- In-progress autovacuum
SELECT pid, phase, heap_blks_scanned, heap_blks_vacuumed, index_vacuum_count
FROM pg_stat_progress_vacuum;
Common Pitfalls
Long-running transactions and abandoned replication slots block vacuum from removing dead tuples, because a vacuum cannot remove a row version that any open snapshot might still need. A single transaction left open for hours can freeze the cleanup horizon for the whole database. Find them with a query on pg_stat_activity filtered by state and age, and set idle_in_transaction_session_timeout so forgotten transactions are terminated automatically.
Another common mistake is running VACUUM FULL on a large production table. It rewrites the table and takes an exclusive lock, blocking reads and writes for the duration. Plain VACUUM or pg_repack reclaims space online; VACUUM FULL should be reserved for planned maintenance windows. Finally, do not assume more autovacuum workers is always better; each worker competes for I/O, so match their count and cost budget to the machine.
Conclusion
Autovacuum is not a background chore you can ignore on a busy cluster; it is the mechanism that keeps tables lean and prevents wraparound. Measure dead tuples and table size, lower the scale factor and threshold on hot tables so cleanup runs often and cheaply, raise the cost budget so vacuum actually finishes, watch transaction-ID age as your wraparound early warning, and eliminate long transactions that block cleanup. Tune per table, verify with the runtime statistics, and autovacuum becomes a quiet ally instead of the cause of a Friday-night incident.
Sources: PostgreSQL: Routine Vacuuming, PostgreSQL: autovacuum parameters, PostgreSQL: Monitoring statistics.
FAQ
- Is it safe to set autovacuum_vacuum_cost_delay to zero?
- On dedicated database hardware with spare I/O it is usually safe for the busiest tables, because finishing vacuum sooner keeps the table small. On shared storage, raise the cost limit gradually and watch query latency, since zero delay lets vacuum compete aggressively with foreground queries.
- Why does VACUUM report that it cannot remove dead tuples?
- Almost always because an old snapshot is still active: a long-running transaction or an abandoned replication slot pins the cleanup horizon so the dead rows might still be visible to someone. Terminate the idle transaction or drop the slot, then vacuum succeeds.
Report a problem with this articleOpens a pre-filled issue on GitHub.