VACUUM & Autovacuum
Because MVCC leaves dead tuples behind on UPDATE and DELETE, PostgreSQL relies on VACUUM and ANALYZE to keep tables healthy, fast, and safe from transaction ID wraparound.
What VACUUM does#
- Reclaims dead tuples so their space inside the table can be reused by future writes (without shrinking the OS file in most cases).
- Updates the Visibility Map (VM), enabling fast Index-Only Scans and letting future vacuums skip all-visible pages.
- Updates the Free Space Map (FSM) so PostgreSQL knows where free space is available.
- Freezes old transaction IDs to prevent XID wraparound.
VACUUM vs VACUUM FULL vs ANALYZE#
-- Standard non-blocking vacuum + planner statistics refresh
VACUUM (VERBOSE, ANALYZE) my_table;
-- Refresh planner statistics only (fast, non-blocking)
ANALYZE VERBOSE my_table;
Avoid
VACUUM FULLin production unless you have a maintenance window — it acquires anACCESS EXCLUSIVElock (blocking all reads and writes) and rewrites the entire table. For online bloat removal, use tools likepg_repack.
Checking dead tuples and last vacuum#
Inspect tables with the highest dead tuple counts and when they were last vacuumed/analyzed:
SELECT
schemaname || '.' || relname AS table_name,
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_autovacuum,
last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;Monitoring active vacuum progress#
Watch running VACUUM and autovacuum workers in real time:
SELECT
p.pid,
a.datname,
p.relid::regclass AS table_name,
p.phase,
round(100.0 * p.heap_blks_scanned / NULLIF(p.heap_blks_total, 0), 1) AS scanned_pct,
round(100.0 * p.heap_blks_vacuumed / NULLIF(p.heap_blks_total, 0), 1) AS vacuumed_pct,
now() - a.xact_start AS duration
FROM pg_stat_progress_vacuum p
JOIN pg_stat_activity a ON a.pid = p.pid;How autovacuum triggers#
Autovacuum automatically runs on a table when:
dead_tuples > autovacuum_vacuum_threshold + (autovacuum_vacuum_scale_factor * reltuples)
For very large tables (tens of millions of rows), the default autovacuum_vacuum_scale_factor = 0.2 (20%) can wait too long. You can tune high-churn tables individually without changing the whole cluster:
ALTER TABLE high_churn_table SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_analyze_scale_factor = 0.01
);
Check current global autovacuum settings:
SELECT name, setting, unit
FROM pg_settings
WHERE name LIKE 'autovacuum%'
ORDER BY name;