How-To Guide

How to Avoid Long-Running Transactions

Keep database transactions short: move slow work outside the transaction, detect a long transaction, and understand the vacuum and lock damage it causes.

On this page

  1. Introduction
  2. Understand why long transactions hurt
  3. Move slow work outside the transaction
  4. Acquire locks late and hold them briefly
  5. Detect and kill the offenders
  6. Bound the transaction with timeouts
  7. Test that nothing holds a transaction open
  8. Common pitfalls
  9. Conclusion

Introduction

A transaction is not just a unit of atomicity; it is a window during which the database must keep a consistent view of the data and may hold locks. The longer that window, the more it hurts. A long transaction blocks writers, delays readers behind locks, and, in a database with multiversion concurrency control, prevents vacuum from reclaiming row versions that the transaction’s snapshot might still see. The damage is often invisible until bloat and lock queues appear.

This tutorial explains why long transactions are dangerous, how to move slow work outside them, how to acquire locks late, how to detect the offenders including idle-in-transaction sessions, and how to bound a transaction with timeouts. The examples use PostgreSQL, but the multiversion and locking reasoning applies to any MVCC database.

Understand why long transactions hurt

In an MVCC database, each transaction works from a snapshot of the data. When a row is updated or deleted, the old version is kept until no active transaction needs it. A long transaction keeps its snapshot, so every row version created since it began cannot be reclaimed. Vacuum cannot remove them, and the table grows even though the old rows are logically gone.

Locks compound the problem. A transaction that holds a row lock blocks every writer that wants that row; a transaction that holds a table lock blocks a whole operation. The longer the transaction, the more likely two of them form a deadlock and the longer any lock wait. Reducing transaction duration reduces all of these at once, which is why keeping transactions short is a first-order rule.

-- find the oldest running and idle-in-transaction sessions
SELECT pid, state, now() - xact_start AS xact_age, left(query, 60) AS query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start;

Move slow work outside the transaction

The most common cause of a long transaction is doing something slow inside it. A network call to another service, a file upload, a user prompt, or a large report can take seconds to minutes, and every one of those seconds is a second the transaction is open. Do the slow part before you begin the transaction and after you commit, and keep only the database writes inside.

Structure the code so the transaction wraps the minimum. Fetch or validate inputs first, call external services and await their responses, prepare the payload, and only then open the transaction, write, and commit. If the external call must be reflected in the database, do the call first and write its result inside a short transaction, accepting that a failure between them needs a compensating step, rather than holding the transaction across the call.

// slow work outside the transaction
const quote = await pricingService.getQuote(orderId);   // network call, no txn open
await db.transaction(async (tx) => {
  await tx.query('UPDATE orders SET total = $1 WHERE id = $2', [quote.total, orderId]);
  await tx.query('INSERT INTO order_events(order_id, type) VALUES ($1, $2)', [orderId, 'priced']);
}); // transaction is short: only two writes

Acquire locks late and hold them briefly

Take locks as late as possible. A transaction that locks a row at its start and then does untracked work before the write holds the lock for all of that work. Select the row, do the computation on the values, then issue the UPDATE that takes the lock only when it is actually needed. Where the logic requires reading under lock, keep the locked section as small as possible.

Prefer optimistic concurrency to a long pessimistic lock. Reading a version, computing, and then updating conditionally on that version avoids holding a lock across the compute. Use a lock only when the compute is short or when correctness demands it, and drop the lock as soon as the protected work is done, not at the end of an unrelated sequence.

Detect and kill the offenders

Monitor transaction age and lock waits. A query that lists sessions ordered by transaction start time shows the offenders; an idle-in-transaction session is especially damaging because it holds a snapshot with no work in progress. Add an idle-in-transaction timeout so the database closes such a session automatically, and alert on any transaction older than a threshold.

When one transaction blocks many others, terminating it releases the queue. Terminate deliberately and with a record of why, because killing a session rolls back its transaction and any work in it. The goal is not to kill routinely but to catch the rare runaway and to fix the code that produced it, so the timeout is the backstop and the code change is the fix.

-- bound any single statement and close idle transactions
SET statement_timeout = '10s';
SET idle_in_transaction_session_timeout = '30s';

-- identify who is blocking whom
SELECT blocking.pid AS blocker, blocked.pid AS blocked_by, blocked.query
FROM pg_stat_activity blocked
JOIN pg_stat_activity blocking ON blocking.pid = ANY(pg_blocking_pids(blocked.pid));

Bound the transaction with timeouts

Timeouts turn a policy into an enforced behavior. A statement timeout aborts any single query that runs too long, so a runaway query cannot hold the transaction open indefinitely. An idle-in-transaction timeout closes a session that opened a transaction and stopped, reclaiming its snapshot. Set both to values appropriate for the workload, and remember they are backstops for the code, not a substitute for keeping transactions short by design.

Choose the values with care. Too short a statement timeout aborts legitimate long-running analytical queries; set it per role or per connection so an OLTP connection is bounded tightly and a reporting connection is given more room. The goal is that no transaction, by design or by accident, lives long enough to cause bloat or a lock queue.

Test that nothing holds a transaction open

Add a test that asserts a request does not make a network call while a transaction is open, for example by injecting a fake slow service that fails if called inside a transaction scope. Add a test that a slow query is aborted by the statement timeout rather than holding the transaction. Assert that the idle-in-transaction timeout closes a session that opens a transaction and sleeps. These tests catch the two ways a transaction grows long.

# open a transaction, then sleep; the server should abort it
psql -d app -c "BEGIN; SELECT pg_sleep(60);" &
sleep 35
psql -d app -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'idle in transaction';"
# expect 0: the idle_in_transaction_session_timeout closed it

Common pitfalls

Calling a network service inside a transaction, holding a row lock across unrelated computation, leaving a transaction open while awaiting user input, ignoring idle-in-transaction sessions that block vacuum, and setting no timeout at all are the recurring mistakes. Moving slow work outside, late and brief locks, idle timeouts, and a statement timeout address them.

Conclusion

A transaction is a snapshot and a lock window, so its length is a cost. Move network calls, I/O, and user interaction outside it, acquire locks late and release them early, monitor transaction age including idle sessions, and bound transactions with statement and idle timeouts. Self-check by asserting no external call happens inside a transaction and that a slow query is aborted. Short transactions keep writers, readers, and vacuum all moving.

Sources: PostgreSQL: VACUUM and long transactions, PostgreSQL: Client connection defaults and timeouts, PostgreSQL: Lock monitoring.

FAQ

Why does an idle transaction matter?
A transaction that is open but idle holds a snapshot and can block vacuum from reclaiming rows it might still see. In PostgreSQL this causes table bloat even though no query is running. Closing the transaction releases the snapshot.
Can I set a transaction timeout?
Yes. Set a statement timeout to bound any single query and an idle-in-transaction timeout to close sessions that opened a transaction and stopped. Together they limit how long a transaction can live.

Related Examples