Sub topic 8
Tuning autovacuum for busy tables
This chapter assumes you know what dead tuples are, how VACUUM differs from VACUUM FULL, and what autovacuum does in the background. It also assumes you can run queries in psql and edit settings with ALTER TABLE and ALTER SYSTEM. The defaults suit small and medium tables. On large tables with heavy UPDATE or DELETE traffic, they leave autovacuum starting too late and working too slowly. This chapter covers how to tell which problem you have and how to fix it per table.
How autovacuum decides to run
The autovacuum launcher wakes up every autovacuum_naptime (default 1 minute). It checks each table's statistics and starts a worker for any table over its threshold. A table is vacuumed when:
dead tuples > autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor * reltuplesThe defaults are a threshold of 50 and a scale factor of 0.2, so the table needs about 20% dead rows plus 50 before it qualifies. The scale factor is a percentage of the table's size, so the trigger point grows with the table.
| Table size | Dead tuples needed (defaults) |
|---|---|
| 10,000 rows | 2,050 |
| 1,000,000 rows | 200,050 |
| 100,000,000 rows | 20,000,050 |
On the 100-million-row table, autovacuum waits until 20 million dead rows have piled up. Then it has to clean all of them in one run. The table has already bloated by then, and the long run is likely to hold back other work.
PostgreSQL 13 and later also trigger vacuum on inserts, using autovacuum_vacuum_insert_threshold (default 1000) and autovacuum_vacuum_insert_scale_factor (default 0.2). This keeps the visibility map and freezing current on append-only tables. Analyze has its own pair of settings, autovacuum_analyze_threshold (50) and autovacuum_analyze_scale_factor (0.1).
See which tables are over the line
This query compares each table's dead tuples with the global trigger point. It ignores per-table overrides, so treat it as an approximation for tables you have not tuned.
SELECT s.relname,
s.n_dead_tup,
c.reltuples::bigint AS est_rows,
(current_setting('autovacuum_vacuum_threshold')::int
+ current_setting('autovacuum_vacuum_scale_factor')::float8 * c.reltuples)::bigint AS trigger_at,
s.last_autovacuum
FROM pg_stat_user_tables s
JOIN pg_class c ON c.oid = s.relid
ORDER BY s.n_dead_tup DESC
LIMIT 10;Two patterns are common:
n_dead_tupis far belowtrigger_atbut the table is visibly bloated. The trigger is too lax for this table. Lower the scale factor.n_dead_tupis abovetrigger_atandlast_autovacuumis old. Autovacuum is not getting to the table, or it starts and cannot finish. Look at worker slots, throttling, and blockers.
Lower the trigger for big, hot tables
The standard fix is a per-table override. Storage parameters set with ALTER TABLE replace the global values for that table only.
ALTER TABLE public.orders SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_vacuum_threshold = 1000
);With this setting on a 100-million-row table, autovacuum starts at 2,001,000 dead tuples rather than 20,000,050. Each run is about ten times smaller, so each finishes sooner and the table stays closer to its steady-state size.
The usual advice is to leave the global defaults alone and override only the few tables that need it. A very low scale factor on a small table means constant vacuum runs for little gain. A fixed threshold with a scale factor of 0 is sometimes used for huge tables, for example 500,000 dead tuples regardless of size, so the trigger stops growing with the table.
To see what is set on a table, or to undo it:
SELECT relname, reloptions FROM pg_class WHERE relname = 'orders';
ALTER TABLE public.orders RESET (autovacuum_vacuum_scale_factor, autovacuum_vacuum_threshold);Make each run faster: cost-based throttling
Starting early does not help if the run cannot keep up. Autovacuum is deliberately slowed down so it does not saturate disk I/O. Every page it touches adds to a cost counter: a page found in shared buffers costs vacuum_cost_page_hit (1), a page read from disk costs vacuum_cost_page_miss (2), and a page it dirties costs vacuum_cost_page_dirty (20). When the counter reaches the limit, the worker sleeps for the cost delay and then resumes.
| Setting | Default | Effect |
|---|---|---|
| `autovacuum_vacuum_cost_delay` | 2 ms (PostgreSQL 12+) | Sleep length once the cost limit is reached |
| `autovacuum_vacuum_cost_limit` | -1 (uses `vacuum_cost_limit`, 200) | Work allowed before sleeping |
| `autovacuum_max_workers` | 3 | Number of concurrent workers. Changing it needs a restart |
| `autovacuum_work_mem` | -1 (uses `maintenance_work_mem`) | Memory for tracking dead tuple locations |
The global cost limit is shared among all running workers. Adding workers does not add I/O budget. It splits the same budget into smaller slices, and each worker gets slower. If you raise autovacuum_max_workers to handle many busy tables, raise autovacuum_vacuum_cost_limit as well.
To speed up one table without changing the others, override the cost parameters on that table:
ALTER TABLE public.orders SET (
autovacuum_vacuum_cost_limit = 2000,
autovacuum_vacuum_cost_delay = 2
);Per-table cost settings are exempt from the global balancing, so a table with a high limit gets its own share of I/O. Check that your storage can absorb that I/O alongside normal traffic.
Memory also matters. Before PostgreSQL 17, a vacuum run could use at most 1 GB to hold the dead tuple locations it had found. When that array filled up, VACUUM had to scan all of the table's indexes and then continue scanning the heap. A table with many dead tuples and several indexes could need several index passes, which multiplies the run time. Raising autovacuum_work_mem reduces the number of passes. PostgreSQL 17 stores dead tuple locations more compactly and removes that 1 GB cap.
Watch what autovacuum is doing
Turn on logging so every slow run is recorded, with row counts, index scans, and timing:
ALTER SYSTEM SET log_autovacuum_min_duration = '250ms';
SELECT pg_reload_conf();A value of 0 logs every run, which is noisy on busy systems. To watch a run in progress, query the progress view:
SELECT p.pid,
p.relid::regclass AS table_name,
p.phase,
p.heap_blks_total,
p.heap_blks_scanned,
p.index_vacuum_count
FROM pg_stat_progress_vacuum p;A rising index_vacuum_count means the worker ran out of dead-tuple memory and is repeating index passes. Raise autovacuum_work_mem if you see that on large tables.
When tuning does not help
If a table is still bloating after you have lowered its trigger and raised its speed, the cause is usually not the settings. VACUUM can remove a dead tuple only when no running transaction could still need to see it. A long-open transaction, an idle-in-transaction session, a stale replication slot, or a forgotten prepared transaction holds back the cleanup horizon for the whole database. Autovacuum then runs on schedule but removes nothing. Use the backend_xmin query from the previous chapter on blockers to check. Any amount of tuning is wasted until that holder is gone.
Also watch for workers that never get a turn. If all worker slots are busy with long runs on other tables, a small hot table can wait. The launcher does not prioritize by bloat, so seeing last_autovacuum stale on a table that is over its trigger usually means the slots are saturated.
A tuning routine
- Run the over-the-line query and find tables where
n_dead_tupis large orlast_autovacuumis old. - Rule out blockers. If the oldest
backend_xminis far behind, fix that first. - Lower the scale factor and threshold on the affected tables.
- Enable
log_autovacuum_min_durationand read a few runs. If runs are long or show multiple index scans, raise the per-table cost limit orautovacuum_work_mem. - If runs queue behind each other, raise
autovacuum_max_workers(restart required) and the global cost limit together. - Re-check after a few days of real traffic.
Exercise
A table has 50,000,000 rows and the default autovacuum settings. You set autovacuumvacuumscalefactor = 0.01 and autovacuumvacuum_threshold = 5000 on it. How many dead tuples must accumulate before autovacuum starts on it, and how does that compare with the default trigger point?
Show answer
The new trigger is 5000 + 0.01 50,000,000 = 505,000 dead tuples. The default trigger is 50 + 0.2 50,000,000 = 10,000,050 dead tuples. The new setting starts autovacuum at roughly 5% of the default amount, so each run is about twenty times smaller.
Exercise
You raise autovacuummaxworkers from 3 to 10 and leave autovacuumvacuumcost_limit at its default. Vacuum runs on your busiest table get slower, not faster. Why, and what do you change?
Show answer
The cost limit is a shared budget divided among all active workers, so more workers each get a smaller share and sleep more often. Raise autovacuumvacuumcostlimit globally to give the larger pool more total I/O budget, or set a higher autovacuumvacuumcostlimit on the busy table, which exempts it from the shared balancing.
Exercise
A table's autovacuum runs every few minutes, and the log shows each run completing, yet the table keeps growing and ndeadtup stays high. What should you check before changing any autovacuum settings?
Show answer
Check for something holding back the cleanup horizon: long-running or idle-in-transaction sessions (pgstatactivity.backendxmin), replication slots with an old xmin or catalogxmin, and prepared transactions in pgpreparedxacts. If one of these holds an old snapshot, VACUUM cannot remove recently dead rows regardless of how often it runs.