Sub topic 12
Long-running transactions and why they cause bloat
This chapter assumes you know how snapshots decide which row versions a query sees, and that you know what VACUUM does to dead tuples. It uses two psql sessions. It explains why one old transaction can stop VACUUM from cleaning a whole database, and how to find and prevent that.
The rule that makes old transactions expensive
A dead tuple is a row version that no transaction needs any more. VACUUM may remove one only if no current or future snapshot can still see it. PostgreSQL checks this with a single cutoff called the xmin horizon:
- Every backend that holds a snapshot has an
xmin. This is the oldest transaction ID whose effects that snapshot still treats as possibly in progress. - The horizon is the oldest of these values across the whole cluster. (Cluster-wide is a slight simplification, since vacuum looks at the current database plus shared catalogs, but it is a good working model.)
- VACUUM removes a dead tuple only if its
xmaxcommitted and is older than the horizon.
The horizon is global, not per table. A transaction that never touches accounts still holds back cleanup of accounts, because VACUUM cannot know what that transaction will read next.
Reproducing the problem
Use the accounts table from earlier chapters. Open two sessions.
Session A starts a Repeatable Read transaction, takes a snapshot, and then does nothing:
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1;
-- leave this transaction openSession B produces many dead tuples, then tries to clean them up. The \gexec meta-command runs each generated statement separately, so each update is its own transaction:
-- Session B
SELECT 'UPDATE accounts SET balance = balance + 1 WHERE id = 1'
FROM generate_series(1, 1000) \gexec
VACUUM (VERBOSE) accounts;The output includes a line similar to this (numbers will differ):
tuples: 0 removed, 1001 remain, 1000 are dead but not yet removable
removable cutoff: 748, which was 1000 XIDs old when operation endedOn older versions the wording is "dead row versions cannot be removed yet, oldest xmin: 748". In both cases the message means the horizon is held by something else, not that VACUUM failed. Now end Session A and vacuum again:
-- Session A
COMMIT;
-- Session B
VACUUM (VERBOSE) accounts;This time the dead versions are removed and their space becomes reusable.
What bloat means here
Bloat is space in a table or index file occupied by dead tuples or free space that is not reused. A held-back horizon causes it in three ways:
- Dead tuples pile up faster than they can be removed, so new row versions go onto new pages and the table file grows.
- Indexes keep entries pointing at dead tuples, so they bloat too, and index scans have more to skip.
- Even after the old transaction ends, the file does not shrink. VACUUM makes space reusable inside the file. It returns space to the operating system only when the empty pages are at the end of the file.
VACUUM FULLor a table rewrite tool reclaims the rest, at the cost of an exclusive lock.
The result is slower scans and more cache pressure. Autovacuum may also run again and again on the same table without getting anywhere, because each run finds the same non-removable tuples.
Finding who holds the horizon
Start with sessions, ordered by how old their snapshot is:
SELECT pid, state, xact_start, backend_xid, backend_xmin
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL OR backend_xid IS NOT NULL
ORDER BY greatest(age(backend_xmin), age(backend_xid)) DESC NULLS LAST;The two columns mean different things:
backend_xminis the oldest transaction ID the session's snapshot still depends on.backend_xidis the session's own transaction ID. It exists only once the session has written something. A transaction with an assigned ID holds the horizon at least as far back as that ID.
Which sessions hold a snapshot depends on the isolation level:
| Situation | Does it hold the horizon? |
|---|---|
| Read Committed, idle between statements, no writes yet | No. The snapshot is released when each statement ends. |
| Read Committed, one very long query | Yes, for the whole query. |
| Read Committed, `idle in transaction` after an INSERT, UPDATE or DELETE | Yes, through its own `backend_xid`. |
| Repeatable Read or Serializable, open for a long time | Yes, for the whole transaction, even when idle. |
A session in the state idle in transaction is the classic culprit. An application opened a transaction, then waited on a network call, a user, or a crashed worker, and never finished.
Holders that are not ordinary sessions
If the session query shows nothing suspicious, check these other sources:
-- Prepared transactions left behind by two-phase commit
SELECT gid, prepared, owner, database FROM pg_prepared_xacts;
-- Replication slots that have not advanced
SELECT slot_name, active, xmin, catalog_xmin
FROM pg_replication_slots;
-- Standbys that report their oldest snapshot back to the primary
SELECT pid, application_name, backend_xmin
FROM pg_stat_replication;- A prepared transaction survives disconnects and restarts. If nobody runs
COMMIT PREPAREDorROLLBACK PREPARED, it holds the horizon indefinitely. - A replication slot with a stale
xminorcatalog_xminholds the horizon for as long as the consumer is not advancing it. - With
hot_standby_feedback = on, a long query on a standby pushes its snapshot'sxminto the primary and holds back cleanup there. This is a trade-off. Without feedback, the standby cancels such queries on replication conflicts instead.
Measuring the damage
pg_stat_user_tables gives an estimate of dead tuples and the last autovacuum time:
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;A high n_dead_tup with a recent last_autovacuum is the signature of this problem: vacuum ran, but could not remove the tuples. A high count with an old last_autovacuum points to a different cause, such as autovacuum thresholds or workers being too slow. The pgstattuple extension gives exact figures, but it reads the whole table.
Preventing it
Limit how long a transaction can hold anything. The settings below can be set per role, per database, or for the server:
-- Abort sessions that sit idle inside an open transaction
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '5min';
-- Abort any single statement that runs too long
ALTER ROLE app_user SET statement_timeout = '30s';PostgreSQL 17 and later also has transaction_timeout, which caps the total length of a transaction. Pick values from your workload. Reporting roles may need minutes, web application roles seldom need more than seconds.
Other habits that help:
- Keep transactions short. Do network calls and user interaction outside them.
- Run long analytical queries on a replica, and decide knowingly whether it sends feedback to the primary.
- Use
COMMITorROLLBACKin scripts, including their error paths. Connection pools should roll back when they take a connection back. - Monitor the age of the oldest snapshot, and alert before the age reaches minutes or hours.
- Drop replication slots that nobody consumes, and resolve forgotten prepared transactions.
Exercise
A table receives constant updates. Autovacuum runs every few minutes, but n_dead_tup keeps growing, and VACUUM VERBOSE reports many dead tuples that are "not yet removable". Which three queries would you run to find what holds the horizon, and what would you look for in each?
Show answer
First, query pg_stat_activity for backend_xmin and backend_xid, ordered by age, looking for old transactions, especially in the state idle in transaction. Second, query pg_prepared_xacts for forgotten prepared transactions. Third, query pg_replication_slots (and pg_stat_replication if standbys send feedback) for an old xmin or catalog_xmin. Whichever holder has the oldest value sets the horizon. Fix it by ending the transaction, resolving the prepared transaction, or advancing or dropping the slot. Then run VACUUM again.
Exercise
Session A is in Read Committed, has run only SELECT statements, and is now idle in transaction. Does it hold back VACUUM? What changes if it runs an UPDATE first, or if it uses Repeatable Read?
Show answer
Without writes in Read Committed, it holds nothing while idle, because each statement's snapshot is released when the statement ends and no transaction ID has been assigned. After an UPDATE, the session has a backend_xid, which holds the horizon until the transaction ends. In Repeatable Read, the snapshot taken by the first query lasts for the whole transaction, so the session holds the horizon even when it only reads.