PostgreSQL’s MVCC design means every UPDATE and DELETE leaves a dead tuple behind. VACUUM reclaims that space; autovacuum runs VACUUM in the background according to per-table thresholds. When autovacuum keeps up, you never think about it. When it falls behind, tables bloat, query plans degrade, and in the worst case the database goes into emergency mode to prevent transaction-ID wraparound. This article covers the mental model, the tuning parameters, the queries that surface a struggling autovacuum, and the manual VACUUM patterns that get you out of trouble.
How to verify
To see how autovacuum is doing across the database:
-- Tables with the most dead tuples (bloat suspects)
SELECT schemaname, relname,
n_live_tup, n_dead_tup,
round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) AS dead_pct,
last_vacuum, last_autovacuum,
last_analyze, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;
-- Tables approaching wraparound danger
SELECT relname, age(relfrozenxid) AS xid_age,
(SELECT setting::int FROM pg_settings WHERE name='autovacuum_freeze_max_age') AS freeze_max,
round(100.0 * age(relfrozenxid)
/ NULLIF((SELECT setting::int FROM pg_settings WHERE name='autovacuum_freeze_max_age'), 0), 1) AS pct_to_freeze
FROM pg_class
WHERE relkind = 'r'
ORDER BY age(relfrozenxid) DESC
LIMIT 10;
-- Is autovacuum running right now?
SELECT pid, query, state, query_start
FROM pg_stat_activity
WHERE query LIKE 'autovacuum:%';
dead_pct over 20% on a high-traffic table is a sign autovacuum is being out-paced. pct_to_freeze over 50% means freezing is overdue and an aggressive autovacuum is imminent.
What’s happening
Postgres MVCC keeps multiple versions of each row. An UPDATE writes a new row version and marks the old one as deleted-at-transaction-X; a DELETE just marks the row deleted-at-transaction-X. The old versions become dead tuples once no running transaction can still see them. VACUUM scans the table, identifies dead tuples no transaction needs, and marks the space as reusable — without re-locking the table.
Autovacuum is a launcher daemon (autovacuum launcher) that periodically inspects each table’s stats and triggers a worker process when thresholds are exceeded. The default trigger is “20% of the table is dead tuples.” For a 10-million-row table that means 2 million dead tuples before vacuum kicks in — far too lazy for high-throughput tables. Per-table tuning is the fix.
Beyond reclaiming space, VACUUM also freezes old row versions to prevent transaction-ID wraparound. PostgreSQL’s transaction ID is a 32-bit counter that wraps around at 2^31. Without freezing, the wrap would make all old data appear to be in the future and disappear. Autovacuum runs aggressively when a table’s oldest unfrozen XID approaches autovacuum_freeze_max_age (default 200 million).
The procedure
-
Confirm autovacuum is enabled globally. Should always be on.
SHOW autovacuum; -- on SHOW autovacuum_max_workers; -- 3 by default — increase for many-table workloads -
Tune autovacuum for busy tables. Per-table thresholds (in
postgresql.confor viaALTER TABLE) override the global defaults.ALTER TABLE orders SET ( autovacuum_vacuum_scale_factor = 0.02, -- 2% of table is dead → trigger autovacuum_vacuum_threshold = 1000, -- floor of 1000 dead tuples autovacuum_analyze_scale_factor = 0.01, -- 1% changed → analyze autovacuum_vacuum_cost_limit = 2000, -- give this table more IO budget per cycle autovacuum_vacuum_cost_delay = 10ms -- shorter pauses between work bursts );For very high-churn tables (session stores, job queues), set scale factor to 0.01 and threshold to 50.
-
Increase global IO budget on modern storage. Defaults assume slow disks. On SSDs:
# /etc/postgresql/16/main/postgresql.conf autovacuum_vacuum_cost_limit = 2000 autovacuum_vacuum_cost_delay = 2ms autovacuum_max_workers = 6 maintenance_work_mem = 1GBReload.
-
Manually vacuum a bloated table (without locking out other queries):
VACUUM (VERBOSE, ANALYZE) orders;Verbose output tells you how many pages were scanned, how many tuples removed, and how much free space was reclaimed. ANALYZE updates statistics for the planner.
-
For severe bloat, use VACUUM FULL or pg_repack.
VACUUM FULL orders; -- EXCLUSIVE lock for the duration; rewrites the tableVACUUM FULLrewrites the table to a fresh file and rebuilds indexes — it reclaims all bloat but holds an exclusive lock the whole time. For a production table that cannot tolerate downtime, use thepg_repackextension instead — it does the same compaction without long locks. -
Watch for transaction-ID wraparound danger.
SELECT datname, age(datfrozenxid) AS xid_age FROM pg_database ORDER BY xid_age DESC;If any database’s
xid_ageis over 1 billion, intervene immediately. The fix is a targeted VACUUM FREEZE on the oldest tables — let autovacuum do it if it can keep up, but be ready to issue manual VACUUM if it cannot. -
Enable autovacuum logging to see what is being missed:
log_autovacuum_min_duration = 1s # log any autovacuum that took >1 secondReload. Then tail the postgres log to see the work autovacuum is doing.
-
Schedule periodic ANALYZE in addition to autovacuum’s. Autovacuum’s analyze threshold (10% by default) is too lax for query-plan quality on large tables — schedule a nightly
VACUUM ANALYZEon critical schemas to keep statistics fresh.
Common pitfalls
- A long-running transaction holds back vacuum across the cluster — until that transaction commits or rolls back, no tuple newer than its snapshot can be removed. The fix: kill the offending session (
SELECT pg_cancel_backend(pid)) or refactor the app to commit sooner.SELECT * FROM pg_stat_activity WHERE backend_xmin IS NOT NULL ORDER BY backend_xmin LIMIT 5;shows the candidates. VACUUM FULLon a multi-hundred-GB table can take hours and holds an exclusive lock the whole time. Plan for downtime or usepg_repack.- Autovacuum slowness on one table because of the cost-delay mechanism causes a cascading buildup — the next autovacuum gets behind too. Increase cost-limit per table or globally.
- The “n_dead_tup” stat from
pg_stat_user_tablesis approximate — it updates from autovacuum runs. A 0 reading does not mean no dead tuples; it means autovacuum has not updated the counter recently. - Disabling autovacuum on a hot table (a temporary “fix” for IO pressure) is a path to wraparound and forced single-user mode. Never set
autovacuum = offon a production table.
In the engagements we run, autovacuum tuning is part of the platform default for each managed Postgres workload — per-table thresholds for the top 20 churn tables, weekly review of bloat trends, and an alert that fires when any table’s wraparound age exceeds 800 million. Operated under Managed Operations.