Sub topic 7
Why VACUUM sometimes cannot remove dead tuples
This chapter assumes you know what a dead tuple is and what VACUUM does, from the earlier chapters. You should be comfortable with psql, transactions, and the difference between READ COMMITTED and REPEATABLE READ.
A common production symptom is that VACUUM and autovacuum run on schedule, yet n_dead_tup stays high and the table keeps growing. The usual cause is that VACUUM is working correctly but is not allowed to remove the rows. This chapter explains the rule that decides that, the usual blockers, and how to find and remove them.
The rule: a dead row must be invisible to everyone
A row version can be removed only when no current or future snapshot can still see it. PostgreSQL tracks this with a cleanup horizon, the oldest transaction ID that something still needs. VACUUM removes only dead tuples whose deleting transaction is older than that horizon.
Older, still-needed snapshots hold the horizon back. The cleanup horizon is the minimum of these values:
- The
xminof every backend's snapshot. - The transaction ID of every open transaction that has written data.
- The
xminof every replication slot. - The transaction ID of every prepared transaction.
- The feedback value from standbys that have
hot_standby_feedbackon.
The horizon is global, not per table. A transaction that never touches orders can still stop VACUUM from cleaning orders, because the transaction might read it later under the same snapshot.
Reproducing the problem
You can see this with two psql sessions. First, create a table.
CREATE TABLE blocker_demo (id int PRIMARY KEY, val text);
INSERT INTO blocker_demo
SELECT g, 'x' FROM generate_series(1, 100000) AS g;In session A, open a transaction and take a snapshot. Leave it open.
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM blocker_demo;In session B, update every row and then vacuum.
UPDATE blocker_demo SET val = 'y';
VACUUM (VERBOSE) blocker_demo;The output contains a line about tuples that cannot be removed. The wording depends on the version. Older releases print 100000 dead row versions cannot be removed yet, oldest xmin: .... Newer releases print tuples: 0 removed, 200000 remain, 100000 are dead but not yet removable. Session A needs the old versions to answer repeated reads, so VACUUM must leave them.
Now end session A with COMMIT; and run VACUUM (VERBOSE) blocker_demo; again in session B. This time the dead versions are removed.
Read two numbers in every VERBOSE report: the count removed and the count "not yet removable". A large not-removable count means a blocker exists. A large removed count means VACUUM did its job. A small count of both on a bloated table points to other causes, such as a rewrite being needed.
Finding the blocking session
Start with the sessions holding the oldest snapshots.
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;xmin_age counts how many transactions have started since that snapshot was taken. A session with a very large age is a suspect. Check state and xact_start as well.
idle in transactionmeans a client opened a transaction and stopped. This is the most common cause, usually from an application that forgot to commit or a developer who left a console open.activewith an oldxact_startis a long query or a long batch job.
The query above shows only backend_xmin. A session that is idle in a READ COMMITTED transaction after writing has no snapshot but still holds a transaction ID in backend_xid. Include backend_xid IS NOT NULL in the filter when you suspect that case.
Isolation level changes how long a snapshot lives. Under READ COMMITTED, each statement takes a new snapshot, so a long transaction holds the horizon back only while a statement runs, or if it has written data. Under REPEATABLE READ or SERIALIZABLE, the snapshot lasts until the transaction ends. A dump with pg_dump, which uses a single snapshot, also holds the horizon for its whole duration.
The other blockers
Sessions are not the only holders. Check each of these when pg_stat_activity looks clean.
Replication slots
A replication slot makes the server keep data a consumer still needs. A physical slot can carry an xmin, and a logical slot carries a catalog_xmin that holds back cleanup of system catalogs. An abandoned slot holds these values indefinitely.
SELECT slot_name,
slot_type,
active,
age(xmin) AS xmin_age,
age(catalog_xmin) AS catalog_xmin_age
FROM pg_replication_slots
ORDER BY greatest(age(xmin), age(catalog_xmin)) DESC NULLS LAST;An inactive slot (active = false) with a large age is a leak. An unused slot also makes the server retain WAL files, which can fill the disk. If the consumer is gone for good, drop the slot with SELECT pg_drop_replication_slot('slot_name');. Do not drop a slot that a consumer will still use, because that consumer will then need a full resync.
Prepared transactions
A two-phase commit that was prepared and never committed or rolled back keeps its transaction ID alive. It survives disconnects and server restarts, so it is easy to forget.
SELECT gid,
prepared,
owner,
database,
age(transaction) AS xid_age
FROM pg_prepared_xacts
ORDER BY prepared;Resolve each one with COMMIT PREPARED 'gid'; or ROLLBACK PREPARED 'gid';. Check with the owning application or transaction manager first, because the choice affects data consistency.
Standbys with hot_standby_feedback
When hot_standby_feedback = on, a standby reports its oldest snapshot to the primary so that the primary does not remove rows a standby query still needs. This avoids query cancellations on the standby, but a long query there now holds back cleanup on the primary. Look at backend_xmin in pg_stat_replication to see what each standby reports.
| Blocker | Where to look | Typical fix |
|---|---|---|
| Long or idle-in-transaction session | `pg_stat_activity` | Fix the application, set timeouts, or terminate the session |
| Replication slot | `pg_replication_slots` | Restart the consumer or drop an abandoned slot |
| Prepared transaction | `pg_prepared_xacts` | `COMMIT PREPARED` or `ROLLBACK PREPARED` |
| Standby feedback | `pg_stat_replication.backend_xmin` | Shorten standby queries or turn feedback off |
Removing the blocker and preventing a repeat
For a single stuck session, ask the application owner first. If you must act, SELECT pg_terminate_backend(pid); ends the session and rolls back its transaction. This discards uncommitted work, so confirm it is safe.
To stop the problem from recurring, set limits so the server enforces them.
ALTER SYSTEM SET idle_in_transaction_session_timeout = '5min';
ALTER SYSTEM SET statement_timeout = '30min';
SELECT pg_reload_conf();Global timeouts can break legitimate jobs such as migrations and reports. Set them per role or per database where the workload differs, for example ALTER ROLE reporting SET statement_timeout = '2h';. PostgreSQL 17 and later also offer transaction_timeout, which limits total transaction length. For slots, max_slot_wal_keep_size caps how much WAL a lagging slot can retain, and a slot that exceeds the cap is invalidated instead of filling the disk.
What happens after the blocker is gone
Once the horizon moves forward, the next VACUUM or autovacuum run removes the backlog. Space in the table is marked reusable, but the file does not shrink. If the backlog was large, the table is now bloated and VACUUM alone will not return the space to the operating system. The later chapters on VACUUM FULL, pg_repack, and REPACK cover that step.
Autovacuum behaves badly while a blocker exists. It sees dead tuples above its threshold, starts, removes nothing, and starts again on the next cycle. This wastes I/O and worker slots that other tables need. If autovacuum on one table is busy all the time and n_dead_tup does not fall, check blockers before changing autovacuum settings. Tuning cannot fix a horizon that does not move.
A short diagnostic order
Work through these steps when dead tuples do not go down:
- Run
VACUUM (VERBOSE)on the table and read the not-yet-removable count and the oldest xmin. - Check
pg_stat_activityfor old snapshots and idle-in-transaction sessions. - Check
pg_replication_slotsfor inactive or lagging slots. - Check
pg_prepared_xactsfor forgotten prepared transactions. - Check standby feedback if you use replicas.
Exercise
A table has 5 million dead tuples. VACUUM VERBOSE reports 0 removed and 5 million "dead but not yet removable". pgstatactivity shows one session, in state "idle in transaction", with an xmin_age of 40 million. That session has never touched this table. Why can't VACUUM remove the rows, and what are two actions you could take?
Show answer
The cleanup horizon is global. The idle session's snapshot (or transaction ID) is older than the deleting transactions, so the server must assume it could still need those row versions, even though it never read this table. VACUUM therefore keeps them. You could end the session after confirming it is safe, using pgterminatebackend(pid), or have the application commit or roll back. To prevent a repeat, set idleintransactionsessiontimeout for that role or database.
Exercise
pgstatactivity shows no old sessions, but dead tuples are still not removable. Name two other places to check and what you would look for in each.
Show answer
Check pgreplicationslots for an inactive slot with a large age(xmin) or age(catalogxmin), and drop it if its consumer is gone. Check pgpreparedxacts for an old prepared transaction, and resolve it with COMMIT PREPARED or ROLLBACK PREPARED. You can also check pgstatreplication.backendxmin for a standby using hotstandbyfeedback.