Skip to content

Postgres VACUUM: what it does and how to tell autovacuum is behind

VACUUM removes the dead row versions that UPDATE and DELETE leave behind, so the space can be reused and queries stay fast. Autovacuum runs it for you, and you only need to step in when the dead-tuple count keeps growing. This guide shows how to check, which settings matter, and when VACUUM FULL is worth its lock.

What VACUUM does and why Postgres needs it

Postgres uses MVCC: an UPDATE does not change a row in place. It writes a new version and marks the old one as dead once no transaction can still see it. A DELETE only marks the row. The dead versions stay in the table file until something cleans them.

That something is VACUUM. According to the PostgreSQL documentation it does four jobs: it recovers or reuses the space of dead rows, it can update the planner statistics, it updates the visibility map that index-only scans depend on, and it protects old data from transaction ID wraparound.

Plain VACUUM does not shrink the file in the general case. It marks the space as reusable inside the table, so new rows fill the holes. It runs next to normal reads and writes. The only thing it blocks is schema changes such as ALTER TABLE on that table.

VACUUM, VACUUM FULL, ANALYZE and autovacuum

CommandWhat it doesLock
VACUUMMarks dead row space reusable, updates the visibility map, freezes old rowsDoes not block reads or writes
VACUUM (ANALYZE)The same, then refreshes planner statisticsDoes not block reads or writes
ANALYZEOnly refreshes the statistics the planner uses to pick plansDoes not block reads or writes
VACUUM FULLRewrites the whole table into a new file and returns space to the operating systemACCESS EXCLUSIVE: nothing else can use the table
AutovacuumA background process that runs VACUUM and ANALYZE when a table crosses a thresholdSame as plain VACUUM
Run by hand on one table
VACUUM (VERBOSE, ANALYZE) public.orders;

Keep autovacuum on. The documentation says explicitly to use plain VACUUM and avoid VACUUM FULL where possible. Most teams that turn autovacuum off to save I/O pay for it later in bloat and in slow queries.

How to tell autovacuum is falling behind

The view pg_stat_user_tables keeps, per table, the estimated live and dead rows and the time of the last vacuum. Look for tables where dead rows are a large share of the total and the last autovacuum is old or empty.

Dead rows by table
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), 1) AS dead_pct,       last_autovacuum,       last_autoanalyze,       autovacuum_countFROM pg_stat_user_tablesWHERE n_live_tup + n_dead_tup > 1000ORDER BY n_dead_tup DESCLIMIT 25;

A dead share above roughly 20% on a table that is read often is worth attention. The numbers are estimates from the statistics collector, so treat them as a signal, not an exact count. A single snapshot tells you little. The trend tells you more: a table whose n_dead_tup climbs every day is one autovacuum cannot keep up with.

To see what autovacuum is doing right now, query pg_stat_progress_vacuum. For table size and bloat suspects, sort by pg_total_relation_size.

Running vacuums and biggest tables
SELECT pid, relid::regclass AS table_name, phase,       heap_blks_scanned, heap_blks_totalFROM pg_stat_progress_vacuum; SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) AS total_sizeFROM pg_stat_user_tablesORDER BY pg_total_relation_size(relid) DESCLIMIT 15;

The settings that matter

Autovacuum starts a VACUUM on a table when dead rows pass this threshold: autovacuum_vacuum_threshold plus autovacuum_vacuum_scale_factor times the number of rows. With the defaults, 50 rows and 0.2, a table of 100 million rows waits for about 20 million dead rows. That is the usual reason a big table bloats.

SettingDefaultWhat to do with it
autovacuum_vacuum_scale_factor0.2Lower it on large tables, per table, to 0.01 to 0.05
autovacuum_vacuum_threshold50Raise it on tiny, busy tables to avoid constant vacuums
autovacuum_analyze_scale_factor0.1Lower it where plans go bad after bulk changes
autovacuum_vacuum_cost_delay2msLower it if vacuum is too slow on fast storage
autovacuum_vacuum_cost_limit-1 (uses vacuum_cost_limit, 200)Raise it; the budget is shared by all running workers
autovacuum_max_workers3More workers only help if the cost limit rises too; needs a restart
autovacuum_naptime1minRarely needs a change

Change the large, hot tables first, and do it per table rather than for the whole server. Most of these settings can be set as storage parameters. The exceptions are autovacuum_naptime and autovacuum_max_workers, which are server-wide.

Per-table settings
ALTER TABLE public.orders SET (
  autovacuum_vacuum_scale_factor = 0.02,
  autovacuum_vacuum_threshold = 1000,
  autovacuum_analyze_scale_factor = 0.01
);

If autovacuum runs often but dead rows still grow, the cost limit is the next suspect. Workers pause to respect the cost budget, and the budget is split among all workers. Raise autovacuum_vacuum_cost_limit before you add workers.

Long transactions stop the cleanup

VACUUM can only remove a dead row version when no open transaction could still need to see it. One session left in "idle in transaction" for hours holds the cleanup horizon back for the whole database. Autovacuum runs, finds nothing it may remove, and dead rows keep growing.

Oldest open transactions
SELECT pid, usename, state,       now() - xact_start AS xact_age,       left(query, 80) AS queryFROM pg_stat_activityWHERE xact_start IS NOT NULLORDER BY xact_startLIMIT 10;

Replication slots that nobody reads and prepared transactions hold the horizon in the same way. Check pg_replication_slots and pg_prepared_xacts if the list above looks clean and dead rows still grow. A safety net for application bugs is idle_in_transaction_session_timeout.

Transaction ID wraparound, in plain words

Transaction IDs are 32-bit numbers, and Postgres compares them in a circle. For any ID, about two billion IDs count as older and two billion as newer. If a row version is never cleaned and two billion transactions pass, it would suddenly look like it is in the future and vanish.

VACUUM prevents this by freezing old row versions, which marks them as older than every normal ID. Tables that have not been vacuumed for autovacuum_freeze_max_age transactions (200 million by default) are autovacuumed even if autovacuum is switched off. If you ignore the warnings, the server starts warning roughly 40 million transactions before the limit and finally refuses to assign new IDs.

Distance to the forced vacuum, per database
SELECT datname,       age(datfrozenxid) AS xid_age,       current_setting('autovacuum_freeze_max_age')::int AS freeze_max_ageFROM pg_databaseORDER BY age(datfrozenxid) DESC;

If xid_age is far above freeze_max_age on a database, something is blocking the freeze. The usual cause is the long transaction, replication slot or prepared transaction from the previous section.

When VACUUM FULL is worth its lock

VACUUM FULL builds a fresh copy of the table and swaps it in. It returns space to the operating system, and it takes an ACCESS EXCLUSIVE lock for the whole run, so even SELECT waits. It also needs free disk space for the new copy.

  • Worth it: after a one-off mass delete or a bad bloat incident, on a table that is mostly empty space, in a maintenance window.
  • Not worth it: as a weekly job, or to fix a table that will bloat again tomorrow. Fix the autovacuum settings or the long transaction first.
  • Alternatives that avoid the long lock: the pg_repack extension, or partitioning so you can drop old partitions instead of deleting rows.

Always check the size of the table and the free disk before VACUUM FULL. It needs room for a second copy.

Watching it without opening psql every time

The queries above are plain SQL, which makes them easy to schedule. In DataRunner you can connect the database, save the dead-tuples query and run it every morning, delivered to e-mail or Slack. A rule that skips the send when the result is empty means you only hear about it when a table crosses your limit.

  1. Connect the PostgreSQL database in DataRunner. For a private network, use the bridge agent.
  2. Start from the dead-tuples, open-transactions and largest-tables templates, or paste the queries from this guide.
  3. Add a WHERE clause for your limit, for example dead_pct > 20.
  4. Schedule it daily in your time zone and choose Slack or e-mail.
  5. Turn on the rule that skips the send when no row comes back.

This is a daily check of the numbers, not a live metrics system. It does not draw time series. If you need minute-by-minute graphs of vacuum activity, pair it with a metrics stack.

Frequently asked questions

Does VACUUM lock the table?
Plain VACUUM and autovacuum do not block SELECT, INSERT, UPDATE or DELETE. They only block schema changes such as ALTER TABLE. VACUUM FULL takes an ACCESS EXCLUSIVE lock and blocks everything on the table until it finishes.
What is the difference between VACUUM and VACUUM FULL?
VACUUM marks the space of dead rows as reusable inside the table, and the file usually keeps its size. VACUUM FULL rewrites the table into a new file and gives the space back to the operating system, at the cost of an exclusive lock and extra disk space.
How do I know if autovacuum is running?
Query pg_stat_user_tables and look at last_autovacuum and autovacuum_count. For a run in progress, query pg_stat_progress_vacuum. Setting log_autovacuum_min_duration to 0 also writes every autovacuum run to the server log.
Why are dead tuples not going down after VACUUM?
Usually an old open transaction, an unused replication slot or a prepared transaction is holding the cleanup horizon back. VACUUM cannot remove a row version that some transaction may still need to see.
How often should I run VACUUM manually?
In most databases, never, because autovacuum handles it. Run it by hand after a large one-off delete or bulk load, or when you tune a table and want the effect now. A VACUUM (ANALYZE) after a bulk load also refreshes the statistics.