You run VACUUM VERBOSE on a bloated table, it finishes happily, and the table is exactly as big as before. The output says something like "N dead row versions cannot be removed yet". That message is almost always about the postgres xmin horizon: a single old snapshot somewhere in the system that forces Postgres to keep row versions it would otherwise throw away. This post builds the mental model, then shows how to find whatever is holding the horizon back.
Symptom: VACUUM runs but dead rows stay
Typical signs: n_dead_tup in pg_stat_user_tables keeps climbing, autovacuum shows up in logs regularly, and table or index size grows anyway. Running a manual vacuum prints a line like this:
INFO: table "orders": found 0 removable, 4210377 nonremovable row versions DETAIL: 4180022 dead row versions cannot be removed yet, oldest xmin: 81234567
The oldest xmin value is the horizon. Anything deleted or replaced by a transaction newer than it must stay. To see why, we need to look at how Postgres stores rows.
Mental model: every UPDATE writes a new row version
Postgres uses MVCC (multi-version concurrency control). An UPDATE does not edit a row in place. It marks the old version as ended and writes a new version, usually on the same page. A DELETE only marks the version as ended. Readers and writers therefore never block each other: a reader keeps looking at the version that was current for it.
Each physical row version (tuple) carries two transaction IDs in its header:
xmin: the transaction that created this version.xmax: the transaction that deleted or replaced it (0 if still live).
You can see them directly, since they are system columns:
CREATE TABLE demo (id int primary key, val text); INSERT INTO demo VALUES (1, 'a'); SELECT xmin, xmax, ctid, * FROM demo; UPDATE demo SET val = 'b' WHERE id = 1; SELECT xmin, xmax, ctid, * FROM demo; -- new xmin, new ctid
After the update the old version is still physically in the heap page, with its xmax set. It is now a dead tuple once nobody can possibly need it. That "once nobody can need it" condition is the whole story.
Snapshots and what xmin means
When a query starts (in READ COMMITTED) or when a transaction starts (in REPEATABLE READ and SERIALIZABLE), Postgres takes a snapshot: roughly, which transactions were committed and visible at that moment. A tuple is visible to a snapshot if its xmin committed before the snapshot and its xmax did not.
A backend that holds a snapshot also advertises the oldest transaction ID it might still need to see. That is its backend_xmin, exposed in pg_stat_activity. Note the two different uses of the word: a tuple's xmin is who created it, while a backend's backend_xmin is the oldest data it may still read.
The xmin horizon: the line VACUUM can't cross
VACUUM may remove a dead tuple only if no current or future snapshot could still see it. So it computes the minimum of all the xmin values that anything is holding, and that minimum is the horizon. A tuple whose xmax committed before the horizon is removable. One whose xmax is newer than the horizon is dead for most sessions but must be kept for the one old snapshot, so VACUUM reports it as "cannot be removed yet".
The consequence is easy to miss: the horizon is global to the database cluster for shared catalogs and per-database for ordinary tables, and it is not per table. A transaction that never touches orders still pins dead rows in orders, because Postgres cannot know what the transaction will read next (in repeatable read) and does not track it per table.
Four things that hold the postgres xmin horizon back
- Long-running or idle-in-transaction sessions. A
BEGINfollowed by a forgotten connection is the classic case. Idle sessions count, not only active queries. - Abandoned replication slots. A logical or physical slot that nobody consumes keeps its
xminorcatalog_xminforever, and also retains WAL. - Standbys with
hot_standby_feedback = on. A long query on a replica sends its xmin back to the primary so that the primary does not remove rows the replica still needs. - Prepared transactions left behind. A
PREPARE TRANSACTIONthat never gets committed or rolled back holds its xmin across restarts.
Monitoring only one of these is a common gap. The Postgres.ai guide on monitoring the xmin horizon covers all four.
Finding the culprit with SQL
Start with sessions, ordered by how old their snapshot is:
SELECT pid, usename, state, xact_start,
now() - xact_start AS xact_age,
age(backend_xmin) AS xmin_age,
left(query, 80) AS query
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC
LIMIT 10;
Then replication slots, prepared transactions and standby feedback:
-- slots
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;
-- prepared transactions
SELECT gid, prepared, owner, database,
age(transaction) AS xid_age
FROM pg_prepared_xacts
ORDER BY prepared;
-- standbys sending feedback show up here as backend_xmin
SELECT pid, application_name, state, backend_xmin
FROM pg_stat_replication
ORDER BY age(backend_xmin) DESC NULLS LAST;
Whichever has the largest age is your holder. Before terminating anything with pg_terminate_backend(pid), check what it is: it rolls back the open transaction, and it might be a legitimate batch job or migration. For a slot, pg_drop_replication_slot() is only safe if its consumer is really gone.
Why autovacuum tuning doesn't fix this
The usual advice is to lower autovacuum_vacuum_scale_factor, which defaults to 20% of the table, so autovacuum triggers earlier on large tables. That helps when autovacuum starts too late. It does nothing when vacuum runs fine but is not allowed to remove anything. Running it more often just does the same fruitless scan more often. Check the horizon first, then tune.
When the holder finally goes away, the horizon jumps forward and the next vacuum has a large backlog to clear in one go. This can look like a sudden I/O spike and is expected. Note also that vacuum frees space for reuse inside the table; it generally does not shrink the file, apart from trailing empty pages. Returning space to the OS needs VACUUM FULL (which takes an exclusive lock) or an online tool such as pg_repack. PostgreSQL 18 also added more vacuum timing in pg_stat_all_tables and eager freezing, per the release notes, but neither changes the horizon rule.
Keeping transactions short in Node.js
Most horizon problems in web apps come from application code that opens a transaction and then awaits something slow: an HTTP call, a queue publish, a user prompt. With pg, make sure the client is always released and the transaction is closed on error:
import pg from 'pg';
const pool = new pg.Pool({
idle_in_transaction_session_timeout: 15000, // ms, ends stuck sessions
statement_timeout: 30000,
});
export async function withTx(fn) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const result = await fn(client);
await client.query('COMMIT');
return result;
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
// Do the slow work BEFORE opening the transaction
const rate = await fetchExchangeRate();
await withTx((c) => c.query('UPDATE invoices SET rate = $1 WHERE id = $2', [rate, 42]));
The idle_in_transaction_session_timeout setting is a server-side safety net: Postgres terminates a session that sits idle inside a transaction longer than the limit, so a leaked connection cannot pin the horizon indefinitely. You can also set it per role with ALTER ROLE app SET idle_in_transaction_session_timeout = '15s'. If you want the same discipline for external calls, the timeout patterns in Node.js Fetch Timeout apply directly, and the transaction-scoping ideas carry over from Mongoose Transactions.
Common misconceptions
- "Autovacuum is broken." It is usually working; it is being told to keep the rows. Look at the "cannot be removed yet" count.
- "Only writes cause the problem." A read-only transaction in
REPEATABLE READholds a snapshot for its whole life and pins the horizon just as well. - "It only affects the table that session touches." The horizon is not per table; any old snapshot in the database affects all tables.
- "VACUUM FULL fixes it." It rewrites the table but still cannot drop tuples the horizon requires, and it blocks access while running.
- "READ COMMITTED means no snapshot." Each statement still has a snapshot; a single huge query, or an idle-in-transaction session that last ran a query, can still hold an old one.
Conclusion
When dead tuples will not go away, stop tuning autovacuum and find the oldest xmin. Check sessions, replication slots, prepared transactions and standby feedback in that order, set idle_in_transaction_session_timeout, and keep slow work outside your transactions. The official Routine Vacuuming chapter is the reference for the rest of the mechanics. If you cache or store short-lived data such as OTPs, see also Redis vs Database for OTP Storage: high-churn rows are exactly what makes this problem visible.





