VACUUM and Autovacuum

What VACUUM Does — Step by Step

VACUUM does not rewrite the table. It is a targeted reclamation pass:

  1. Scan heap pages — identify tuples where xmax is committed and no running transaction can still see the old version (past the global xmin horizon).
  2. Mark dead tuples free — set their ItemId status to LP_UNUSED in the page header. Space becomes available for new inserts into that page.
  3. Update the Free Space Map (FSM) — the _fsm fork records free space per page; future INSERTs reuse it without extending the file.
  4. Update planner statistics in pg_class.relpages / reltuples — this is what feeds the planner in the Reading the planner part.
  5. Truncate trailing empty pages (briefly locks, only if possible) — the only time regular VACUUM shrinks the file.
VACUUM VERBOSE accounts;
-- INFO:  vacuuming "public.accounts"
-- INFO:  scanned index "accounts_pkey" to remove 4200 row versions
-- INFO:  "accounts": removed 4200 row versions in 180 pages
-- INFO:  "accounts": found 4200 removable, 95800 nonremovable row versions
-- INFO:  free space map contains 180 pages with free space

VACUUM vs. VACUUM FULL

VACUUMVACUUM FULL
Rewrites tableNoYes — new heap file
Lock heldShareUpdateExclusive (allows reads & writes)AccessExclusive — blocks all queries
Shrinks fileOnly trailing empty pagesAlways, fully compacted
Index rebuildNoYes
Use caseRoutine maintenanceEmergency bloat reduction

Autovacuum Trigger Condition

Autovacuum fires on a table when:

n_dead_tup > autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × reltuples

Defaults:
  autovacuum_vacuum_threshold    = 50
  autovacuum_vacuum_scale_factor = 0.2  (20%)

For a 10M-row table: 50 + 0.2 × 10,000,000 = 2,000,050 dead tuples before autovacuum fires

That is a lot of dead tuples to tolerate on a high-write table. Always tune per-table:

ALTER TABLE events SET (
  autovacuum_vacuum_scale_factor = 0.01,  -- trigger at 1% dead tuples
  autovacuum_vacuum_threshold    = 1000,
  autovacuum_vacuum_cost_delay   = 2      -- ms between cost-limit pauses
);