← Back to SQL, page 12

sql-0236 · Medium mid

Why are long-running transactions a problem, even when they only read?

An open transaction holds its locks and its snapshot. In PostgreSQL, a snapshot prevents VACUUM from removing row versions that the transaction might still see, so tables and indexes bloat. In SQLite WAL mode, an open reader stops checkpoints from resetting the WAL, so the file keeps growing. Writers queue behind held locks, and replicas may lag or cancel queries.

Full answer

Typical causes are a report that runs for an hour inside one transaction, an application that opens a transaction and then waits for a remote API, and an idle session left in "idle in transaction" state by a forgotten BEGIN.

Effects to name in an interview:

  • Bloat in MVCC engines, because dead row versions cannot be cleaned.
  • Lock waits that pile up behind the long transaction, sometimes cascading into timeouts across the application.
  • Growing WAL or undo logs.
  • On PostgreSQL replicas, conflicts that cancel queries or delay replay.

Mitigations: keep transactions to the database work only, use idle_in_transaction_session_timeout and statement_timeout in PostgreSQL, run large reports on a replica or from a snapshot export, and monitor pg_stat_activity for old xact_start values.

In SQLite, the same advice holds: end read transactions promptly so WAL checkpoints can complete.

Key points

  • Open transactions hold locks and snapshots
  • Old snapshots block cleanup and cause bloat
  • WAL files grow while readers stay open
  • Use timeouts and monitoring for idle transactions

Common mistakes

  • Calling external services inside a database transaction
  • Leaving sessions idle in transaction

Follow-ups

  • What does idle_in_transaction_session_timeout do?
  • How would you run a large consistent report without a long lock?

Tips

  • Mention both locks and MVCC cleanup