Sub topic 6
Autovacuum: the background cleaner
This chapter assumes you know what dead tuples are, how VACUUM removes them, and how to read pg_stat_user_tables. It covers how autovacuum decides when to act, what it does, and how to check that it is working.
What autovacuum is
Autovacuum is a built-in background subsystem that runs VACUUM and ANALYZE for you. You rarely run manual vacuums on a healthy system because autovacuum does it continuously.
It has two kinds of process:
- The autovacuum launcher is a single process that wakes up periodically and decides which databases need attention.
- Autovacuum workers are processes the launcher starts. Each worker connects to one database, picks tables that need work, and vacuums or analyzes them one at a time.
Three settings control the basic rhythm:
| Setting | Default | Meaning |
|---|---|---|
| `autovacuum` | `on` | Master switch for the launcher |
| `autovacuum_naptime` | `1min` | Time between launcher rounds for each database |
| `autovacuum_max_workers` | `3` | Most workers that can run at once across the cluster |
Autovacuum also depends on track_counts being on (the default). The statistics collector supplies the dead-row counts that autovacuum reads. If you turn it off, autovacuum cannot decide anything.
How a table gets picked
On each pass, a worker examines every table in its database and compares activity counters with a threshold. A table qualifies when its estimated dead tuples exceed:
autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor * reltuplesreltuples is the planner's row count estimate from pg_class. The defaults are a threshold of 50 and a scale factor of 0.2. A table of 10 million rows is therefore vacuumed only after about 2,000,050 dead tuples have piled up. A table of 1,000 rows qualifies after 250.
The scale factor makes the trigger proportional to table size. That is sensible for small tables and lax for large ones. A 20% bloat allowance on a table of 500 GB is 100 GB of dead space before cleaning starts. The tuning chapter returns to this.
Autovacuum uses two other triggers with the same shape:
- Insert-driven vacuum (PostgreSQL 13 and later) fires when inserted rows since the last vacuum exceed
autovacuum_vacuum_insert_threshold(1000) plusautovacuum_vacuum_insert_scale_factor(0.2) timesreltuples. Append-only tables produce no dead tuples, but they still need the visibility map and freezing work that vacuum does. - Auto-analyze fires when rows changed since the last analyze exceed
autovacuum_analyze_threshold(50) plusautovacuum_analyze_scale_factor(0.1) timesreltuples. This keeps planner statistics fresh.
flowchart TDReplace nothing above; the actual diagram follows.
Anti-wraparound vacuum
A separate trigger ignores the dead-row counts. When a table's oldest unfrozen transaction ID reaches autovacuum_freeze_max_age (default 200 million), autovacuum starts an anti-wraparound vacuum. It runs even if autovacuum is off. The visibility map and freezing chapter explains why. For now, note that these vacuums are not optional and are harder to interrupt than ordinary ones.
Cost-based throttling
A manual VACUUM runs at full speed. Autovacuum is deliberately slowed so it does not starve normal queries of I/O. Each page vacuum reads or dirties adds to a cost counter. When the counter reaches the limit, the worker sleeps.
autovacuum_vacuum_cost_delayis the sleep length. It defaults to2msin PostgreSQL 12 and later. Older versions used20ms, which is very slow on modern hardware.autovacuum_vacuum_cost_limitis the budget before each sleep. The default of-1means "usevacuum_cost_limit", which is 200.
The cost budget is shared among all running workers. Raising autovacuum_max_workers alone does not speed up cleanup, because the workers split the same budget. Each one just works more slowly. If vacuums are too slow, raise the cost limit.
Seeing what autovacuum is doing
Worked example: is a table due?
This query compares each table's dead tuples to the global trigger point:
SELECT s.relname,
s.n_dead_tup,
round(current_setting('autovacuum_vacuum_threshold')::numeric
+ current_setting('autovacuum_vacuum_scale_factor')::numeric
* c.reltuples) AS trigger_at,
s.last_autovacuum,
s.autovacuum_count
FROM pg_stat_user_tables AS s
JOIN pg_class AS c ON c.oid = s.relid
ORDER BY s.n_dead_tup DESC
LIMIT 10;If n_dead_tup is well above trigger_at and last_autovacuum is old, something is wrong. The usual causes are that workers are busy, the table is being skipped, or a blocker is holding the rows. The query uses global settings only. A table with per-table overrides (set with ALTER TABLE ... SET (autovacuum_...)) can have a different trigger point. Check pg_class.reloptions for those.
Running workers
Workers show up in pg_stat_activity:
SELECT pid,
datname,
xact_start,
wait_event_type,
query
FROM pg_stat_activity
WHERE backend_type = 'autovacuum worker';The query column reads like autovacuum: VACUUM public.orders. An anti-wraparound run appends (to prevent wraparound). For a live view of one vacuum, query pg_stat_progress_vacuum. It reports the current phase and how many heap pages have been scanned and vacuumed.
The log
Set log_autovacuum_min_duration to record each autovacuum run that lasts at least that long. The default is 10min in PostgreSQL 15 and later, and -1 (off) before that. Setting it to 0 logs every run, which is useful when you investigate a single table. The log lines have the same kind of detail as VACUUM VERBOSE: pages removed, dead tuples removed, and tuples that could not yet be removed.
ALTER SYSTEM SET log_autovacuum_min_duration = '1min';
SELECT pg_reload_conf();What autovacuum does not do
- It does not shrink files. Like plain
VACUUM, it only returns empty pages at the very end of the table to the operating system. Space in the middle is reused but not given back. That needsVACUUM FULLor a repack. - It does not process temporary tables. Only the session that owns a temporary table can see it. If a long session fills one with churn, run
VACUUMon it yourself. - It does not override blockers. A worker removes only tuples that no snapshot can still see. A long transaction holds back every vacuum, automatic or not.
- It gives way to locks. Autovacuum takes a
SHARE UPDATE EXCLUSIVElock. If another session requests a conflicting lock, such asALTER TABLEorCREATE INDEX, the worker cancels itself after about a second (deadlock_timeout) and tries again later. Anti-wraparound runs are not cancelled this way.
If a table is cancelled repeatedly, last_autovacuum stays old while the other symptoms look normal. Look for frequent schema changes or explicit LOCK TABLE calls.
Common errors
- Assuming autovacuum is working because it is enabled. Check
last_autovacuumandn_dead_tup, not only the setting. - Adding workers to speed up cleanup. The cost budget is shared, so more workers do not add throughput.
- Leaving the defaults on very large tables. The 20% scale factor is too lax once a table has hundreds of millions of rows.
- Reading
n_dead_tupas exact. It is a statistics-based estimate. Usepgstattuplewhen you need a precise figure. - Blaming autovacuum for dead tuples that it cannot remove. Look for old snapshots first (the next chapters cover how).
Exercise
A table has 5,000,000 rows and uses the default autovacuum settings. About how many dead tuples must accumulate before autovacuum vacuums it, and why might adding more workers not make a slow vacuum finish sooner?
Show answer
The trigger is 50 + 0.2 * 5,000,000 = 1,000,050 dead tuples. More workers do not help because autovacuum's cost-based throttling budget (autovacuumvacuumcost_limit) is shared among all running workers, so each worker gets a smaller share and the total I/O rate stays the same. To speed up a vacuum, raise the cost limit or lower the cost delay.
Exercise
Autovacuum is on, but last_autovacuum for a busy table is three days old and n_dead_tup is far above the trigger point. Name two likely causes and one query or view you would check for each.
Show answer
One cause is that a long-running transaction or other old snapshot prevents removal; check pg_stat_activity for the oldest backend_xmin. Another is that the worker keeps cancelling itself because of conflicting lock requests; check the server log (with log_autovacuum_min_duration set) and look for frequent DDL or explicit locks on the table. A third possibility is that all workers are busy on other tables, which you can check with pg_stat_activity where backend_type = 'autovacuum worker'.