Sub topic 2
What VACUUM Does and Does Not Do
This chapter assumes you know basic SQL (SELECT, UPDATE, DELETE, CREATE TABLE), can use psql, and understand that transactions group statements and can run concurrently.
What VACUUM does and does not do
PostgreSQL uses MVCC (multiversion concurrency control). An UPDATE writes a new row version and leaves the old one in place, so concurrent transactions can still read the old data. A DELETE only marks a row version as deleted. Once no transaction can see an old version, it is a dead tuple.
VACUUM finds dead tuples and:
- Makes their space reusable inside the table.
- Removes index entries that point to them.
- Updates the visibility map, which speeds up some reads.
- Freezes old row versions to prevent transaction ID wraparound.
VACUUM does not:
- Usually shrink the table file. It returns space to the operating system only when empty pages sit at the end of the file.
- Block reads or writes. A plain VACUUM runs alongside normal traffic.
- Rebuild bloated indexes.
Run it with VERBOSE to see what it did:
VACUUM (VERBOSE, ANALYZE) public.orders;Autovacuum: the background cleaner
Autovacuum is a group of background processes that run VACUUM and ANALYZE for you. A table qualifies for vacuum when its dead tuple count passes this threshold:
- autovacuumvacuumthreshold (default 50) plus
- autovacuumvacuumscale_factor (default 0.2) times the table's estimated row count.
Why VACUUM sometimes cannot remove dead tuples
A dead tuple can be removed only when no running transaction could still need it. These things hold cleanup back:
- Long-running or "idle in transaction" sessions.
- Replication slots and standby feedback that keep an old snapshot alive.
- Forgotten prepared transactions.
Find the oldest sessions with this query:
SELECT pid, state, xact_start,
age(backend_xmin) AS xmin_age,
left(query, 60) AS query
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC
LIMIT 5;> Note: If VERBOSE output reports "dead row versions cannot be removed yet," an open snapshot is the likely cause. Fix the blocker first, then vacuum again.
Tuning autovacuum for busy tables
The default 20% scale factor is too lax for a large table. On a 50-million-row table, the default waits for about 10 million dead rows. Lower the values for that table only:
ALTER TABLE public.orders SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_vacuum_threshold = 1000
);With these settings, autovacuum starts after about 1,001,000 dead rows on that 50-million-row table.
Exercise
Exercise
A table has 2,000,000 rows and uses the default autovacuum settings. How many dead tuples must accumulate before autovacuum starts?
Show answer
50 + 0.2 × 2,000,000 = 400,050 dead tuples.