
The Hidden Cost of Long Read-Only Transactions: MVCC, Bloat and Blocking
- كاتب موثّق
- PostgreSQL 18
محتويات المقال
accounts table keeps growing, autovacuum runs without removing anything, and at 2 a.m. a routine migration adds a column and the API stops answering. The job only reads: it opens a REPEATABLE READ transaction "for a consistent view", loads the accounts, and sends one email per account before committing. In a test on PostgreSQL 18 with one such idle transaction open, five rounds of updating 100,000 rows followed by VACUUM grew the table from 8,696 kB to 25 MB, and VACUUM reported 500,000 rows "dead but not yet removable". Without the idle transaction, the same five rounds kept the table at 8,696 kB.
The common misconception
What actually happens
Old row versions wait for the oldest snapshot
UPDATE or DELETE doesn't remove the old version of a row. The docs explain why: the row version must not be deleted while it is still potentially visible to other transactions. That leftover is a , and VACUUM reclaims it only once no snapshot can see it. The oldest snapshot or transaction still open sets that limit, the , and it applies to every table in the database, not only those the old transaction read. In the test, a REPEATABLE READ transaction that had read only an inventory table still left 100,000 updated accounts rows not removable. VACUUM (VERBOSE) makes this visible: its removable cutoff stayed at the same transaction ID for all five rounds.
Which transactions hold the horizon
REPEATABLE READ and SERIALIZABLE, and while a cursor is open; a transaction that has written holds its own transaction ID. The test checked each case through backend_xmin and backend_xid in pg_stat_activity, then ran VACUUM:
READ COMMITTED, read-only, idle in transaction | backend_xmin | ||
backend_xmin | |||
REPEATABLE READ or SERIALIZABLE, idle | REPEATABLE READ) | backend_xmin | |
backend_xid |
idle_in_transaction_session_timeout: an open transaction prevents vacuuming away recently-dead tuples that may be visible only to it, so staying idle for a long time contributes to table bloat.
Bloat stays after the transaction ends
VACUUM removed all 500,000 dead rows, and the table stayed at 25 MB. That's documented behavior: standard VACUUM marks the space as available for reuse but doesn't return it to the operating system, except for completely empty pages at the end of the table. VACUUM FULL compacts the table, but it needs an ACCESS EXCLUSIVE lock, so the table is unusable while it runs. Very old horizons also matter for transaction ID wraparound: the docs' recovery steps include ending long-running transactions found through age(backend_xmin) and age(backend_xid).
The lock you forgot you were holding
SELECT takes an ACCESS SHARE lock on each table it reads, and the docs say a lock is normally held until the end of the transaction. ACCESS SHARE conflicts only with ACCESS EXCLUSIVE, which many forms of ALTER TABLE need. In the test, a READ COMMITTED session ran one SELECT and sat idle in its transaction. A migration's ALTER TABLE ... ADD COLUMN waited 8.5 seconds for it, and an API query reading one account by primary key, queued behind the ALTER, took 7.4 seconds. pg_blocking_pids showed the chain: the API waited for the migration, and the migration waited for the idle report.
Keep slow work out of the transaction
using System.Data;using Microsoft.EntityFrameworkCore;static async Task SendStatementsAsync( BankDb db, IMailer mailer, CancellationToken ct){ // One snapshot "for safety", held while every email goes out await using var tx = await db.Database.BeginTransactionAsync( IsolationLevel.RepeatableRead, ct); var accounts = await db.Accounts.AsNoTracking().ToListAsync(ct); foreach (var account in accounts) await mailer.SendStatementAsync(account, ct); // slow, external await tx.CommitAsync(ct); // Test: 100,000 dead rows not removable}using Microsoft.EntityFrameworkCore;static async Task SendStatementsAsync( BankDb db, IMailer mailer, CancellationToken ct){ // One statement, one snapshot, released once the rows have arrived var accounts = await db.Accounts.AsNoTracking().ToListAsync(ct); foreach (var account in accounts) await mailer.SendStatementAsync(account, ct); // no transaction open // Test: backend_xmin stayed null and VACUUM removed every dead row}VACUUM. One SELECT already sees a consistent snapshot, so the transaction added nothing but cost. Then add guardrails, so a forgotten transaction ends on its own:
-- Who holds back VACUUM, oldest firstSELECT pid, application_name, state, backend_xid, backend_xmin, now() - xact_start AS xact_age, left(query, 50) AS last_queryFROM pg_stat_activityWHERE (backend_xid IS NOT NULL OR backend_xmin IS NOT NULL) AND pid <> pg_backend_pid()ORDER BY xact_start;-- Guardrails for the application's role (example values)ALTER ROLE app_user SET idle_in_transaction_session_timeout = '30s';ALTER ROLE app_user SET transaction_timeout = '5min';transaction_timeout arrived in PostgreSQL 17, and the same release removed old_snapshot_threshold, the setting that let VACUUM remove rows old snapshots could still need. In the test, the two timeouts ended their sessions with FATAL: terminating connection due to idle-in-transaction timeout and FATAL: terminating connection due to transaction timeout.
How to apply it in your project
Look for old transactions now Run the query above and look at xact_age,stateand which ofbackend_xidorbackend_xminis set. Anything idle in transaction for minutes needs an owner.Move slow work out of transactions Emails, HTTP calls, file uploads and waiting for a user don't belong between BEGINandCOMMIT. Check middleware or unit-of-work code that opens one transaction per request or per job.Keep consistent reads short If a report needs REPEATABLE READ, make the transaction as short as the reads themselves, and process the results after committing.Add guardrails Set idle_in_transaction_session_timeoutandtransaction_timeoutfor application roles, andlock_timeoutin every migration.Watch VACUUM output Run VACUUM (VERBOSE)on a growing table: a large "dead but not yet removable" count and aremovable cutoffthat stays put mean an old snapshot is holding it back.
Key takeaways
A read-only transaction can hold a snapshot, and that snapshot stops VACUUMin every table of the database: in the test, 500,000 dead rows stayed and the table grew from 8,696 kB to 25 MB.Snapshots come from long queries, open cursors, REPEATABLE READandSERIALIZABLE; any write holds a transaction ID with the same effect.Even a harmless-looking idle READ COMMITTEDtransaction keeps its table locks, so anALTER TABLEwaits and every query on the table queues behind it.VACUUMmakes space reusable but doesn't shrink the table, so bloat outlives the transaction that caused it.Keep slow work outside transactions, and set idle_in_transaction_session_timeout,transaction_timeoutandlock_timeoutas guardrails.
📚 المصادر
Routine Vacuuming — PostgreSQL 18 documentation Concurrency Control: Introduction (MVCC) — PostgreSQL 18 documentation Client Connection Defaults: timeouts — PostgreSQL 18 documentation Explicit Locking: table-level locks — PostgreSQL 18 documentation PostgreSQL 17 release notes (transaction_timeout added, old_snapshot_threshold removed)
التعليقات (0)