الانتقال إلى المحتوى
قواعد البياناتPostgreSQL· 8 دقائق للقراءة

The Hidden Cost of Long Read-Only Transactions: MVCC, Bloat and Blocking

A transaction that never writes can still stop VACUUM in every table and make a routine migration freeze a busy one. What it costs depends on the snapshot and the locks it keeps.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • PostgreSQL 18
محتويات المقال

On the night the monthly statements job runs, the 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

The belief: a long-running transaction that only reads data doesn't affect anyone else.

It sounds like the whole point of . PostgreSQL's own introduction says that reading never blocks writing and writing never blocks reading, and a read-only transaction has nothing to commit and nothing to roll back. Developers coming from SQL Server's default level are used to readers releasing their locks as soon as a statement ends. And the cost is invisible where the code runs: the job finishes, the emails go out, and nothing in its logs mentions bloat or blocked migrations.

What actually happens

Old row versions wait for the oldest snapshot

In PostgreSQL, an 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

Not every open transaction holds it. A snapshot exists while a statement runs, for the whole transaction at 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:

Open sessionHolds back VACUUMpg_stat_activity showsBlocks DDL on tables it read
READ COMMITTED, read-only, idle in transactionNo (tested)No backend_xminYes (tested)
One long query, or an open cursorYes (tested)backend_xminYes, until it ends
REPEATABLE READ or SERIALIZABLE, idleYes (tested at REPEATABLE READ)backend_xminYes, until it ends
Any transaction that wrote one row, idleYes (tested: 99,998 dead rows kept)backend_xidYes, until it ends

The PostgreSQL docs put it more generally in the description of 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

When the idle transaction in the test ended, the next 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

A 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

C#
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}

Both versions ran against the same table with EF Core 10 and Npgsql 10, while another session updated all 100,000 rows and ran 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:

SQL guardrails.sql
-- 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

  1. Look for old transactions nowRun the query above and look at xact_age, state and which of backend_xid or backend_xmin is set. Anything idle in transaction for minutes needs an owner.
  2. Move slow work out of transactionsEmails, HTTP calls, file uploads and waiting for a user don't belong between BEGIN and COMMIT. Check middleware or unit-of-work code that opens one transaction per request or per job.
  3. Keep consistent reads shortIf a report needs REPEATABLE READ, make the transaction as short as the reads themselves, and process the results after committing.
  4. Add guardrailsSet idle_in_transaction_session_timeout and transaction_timeout for application roles, and lock_timeout in every migration.
  5. Watch VACUUM outputRun VACUUM (VERBOSE) on a growing table: a large "dead but not yet removable" count and a removable cutoff that stays put mean an old snapshot is holding it back.

Key takeaways

  • A read-only transaction can hold a snapshot, and that snapshot stops VACUUM in 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 READ and SERIALIZABLE; any write holds a transaction ID with the same effect.
  • Even a harmless-looking idle READ COMMITTED transaction keeps its table locks, so an ALTER TABLE waits and every query on the table queues behind it.
  • VACUUM makes 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_timeout and lock_timeout as guardrails.

📚 المصادر

  1. Routine Vacuuming — PostgreSQL 18 documentation
  2. Concurrency Control: Introduction (MVCC) — PostgreSQL 18 documentation
  3. Client Connection Defaults: timeouts — PostgreSQL 18 documentation
  4. Explicit Locking: table-level locks — PostgreSQL 18 documentation
  5. PostgreSQL 17 release notes (transaction_timeout added, old_snapshot_threshold removed)

التعليقات (0)