Practical technical guides / Core IT: databases (PostgreSQL 18.4 session timeouts)

PostgreSQL statement_timeout, idle_in_transaction_session_timeout and transaction_timeout: What Each Ends and What the Client Sees

Measured on PostgreSQL 18.4: statement_timeout cancels a statement, while idle-in-transaction and transaction timeouts close the session. Handle each one.

By Sandeep Belgavi · Published 2026-11-20

Which PostgreSQL timeout ends what
Original explanatory diagram; synthetic values where shown.

Measured on PostgreSQL 18.4: statement_timeout cancels a statement, while idle-in-transaction and transaction timeouts close the session. Handle each one.

An agent tool that held a row lock for four seconds

Hansini looks after the stock database at Belgavi's Book Store, a PostgreSQL 18 cluster. A new agent tool adjusted stock for damaged copies: it opened a transaction, read the row for a title with SELECT ... FOR UPDATE, asked a model to classify the damage from a photo, and then wrote the new quantity. The model call took about four seconds. For those four seconds the row was locked, and every checkout for that title waited behind it.

The team already had statement_timeout = 500ms on the agent's database role. It did nothing, because no statement was slow. Each statement finished in a few milliseconds; the time went into the gap between statements while the transaction sat open. PostgreSQL has four timeouts that look similar in a configuration file and do quite different things. This guide measures each one and shows what the client sees, so you can choose the right one and handle its failure correctly.

Four timeouts, four different targets

The PostgreSQL 18 documentation defines them precisely:

SettingWhat it measuresWhat happens when it fires
statement_timeoutOne statement, from arrival at the server to completionThe statement is cancelled; the session survives
idle_in_transaction_session_timeoutTime idle, waiting for the client, inside an open transactionThe session is terminated
transaction_timeout (PostgreSQL 17 and later)Total time in a transaction, explicit or the implicit one around a single statementThe session is terminated
idle_session_timeoutTime idle outside a transactionThe session is terminated

Three of the four end the connection, not just the work. That difference decides how the application must react, and it is the part most often missed.

What a psycopg client sees, measured

The companion example's live probe creates a throwaway PostgreSQL 18.4 cluster with initdb, runs eight checks with psycopg 3.3.9 and records the results.

CheckError raisedConnection after
statement_timeout 500 ms, SELECT pg_sleep(2) in autocommitQueryCanceled, SQLSTATE 57014, after 0.5 sopen, next query works
Same, inside BEGIN after an updateQueryCanceled 57014open, but the next statement fails with 25P02 until ROLLBACK
idle_in_transaction_session_timeout 1 s, holding a row lock, idle 2 sOperationalError: server closed the connection unexpectedly, on the next callclosed
transaction_timeout 1 s, statements of 0.3 s in one transactionTransactionTimeout, SQLSTATE 25P04, after 3 statementsclosed
transaction_timeout 1 s, one 3 s statement in autocommitTransactionTimeout 25P04 after 1.0 sclosed
statement_timeout 2 s and transaction_timeout 1 s, one 3 s statementTransactionTimeout 25P04 after 1.0 sclosed
idle_session_timeout 1 s, idle 1.6 sOperationalError on the next callclosed

Two results deserve attention. First, the idle-in-transaction case: the server terminated the session at the timeout, its uncommitted update rolled back, and the writer that had been blocked on the row lock went through within the 2 s idle period, so the quantity ended at 15 (5 at the start, the idle decrement discarded, the waiting writer's +10 applied). The client learned about it only when it next tried to use the connection. Second, transaction_timeout also covers a single statement in autocommit, because that statement runs in an implicit transaction. The server log line is FATAL: terminating connection due to transaction timeout.

Which timeout fires first

The documentation adds a rule for combinations: if transaction_timeout is shorter than or equal to idle_in_transaction_session_timeout or statement_timeout, the longer timeout is ignored. The probe confirms it: with a 2 s statement timeout and a 1 s transaction timeout, the transaction timeout fired at 1.0 s and closed the session.

The example includes a small model that answers the question for a transaction described as statements and idle gaps:

def first_to_fire(segments, statement_timeout=0, idle_in_transaction_session_timeout=0,
                  transaction_timeout=0, explicit_transaction=True):
    """Return (timeout name or None, ms into the transaction when it fires, segment index)."""
    t = 0
    for i, (kind, ms) in enumerate(segments):
        candidates = []
        if transaction_timeout:
            candidates.append((transaction_timeout - t, 'transaction_timeout'))
        if kind == 'stmt' and statement_timeout:
            candidates.append((statement_timeout, 'statement_timeout'))
        if kind == 'idle' and explicit_transaction and idle_in_transaction_session_timeout:
            candidates.append((idle_in_transaction_session_timeout, 'idle_in_transaction_session_timeout'))
        fire = [(d, name) for d, name in candidates if 0 <= d < ms]
        if fire:
            d, name = min(fire)
            return name, t + d, i
        t += ms
    return None, t, None

For the agent tool (a 20 ms read, a 4,000 ms idle gap, a 30 ms write), statement_timeout alone never fires. Adding idle_in_transaction_session_timeout = 1s ends the session 1,020 ms in. Adding transaction_timeout = 2s instead ends it at 2,000 ms.

The real fix is the shape of the transaction

Timeouts are a backstop. The tool should never hold a transaction open across a model call. Ask the model first, then open a short transaction that re-reads the row, checks it has not changed in a way that matters, and writes. In the model, that version takes 50 ms and none of the three timeouts fires. If the decision depends on the exact row version, carry it with optimistic concurrency: read the row and its version outside the transaction, then UPDATE ... WHERE isbn = $1 AND version = $2 and treat zero rows updated as a conflict.

Setting them where they belong

The documentation recommends against setting statement_timeout or transaction_timeout in postgresql.conf, because that affects every session, including maintenance jobs and migrations. Set them per role or per database instead:

ALTER ROLE agent_tools SET statement_timeout = '500ms';
ALTER ROLE agent_tools SET idle_in_transaction_session_timeout = '1s';
ALTER ROLE agent_tools SET transaction_timeout = '2s';

Role settings apply to new sessions only, and they are defaults, not limits. The probe's eighth check shows a role default of 1500ms visible in a new session, which then ran SET transaction_timeout = '10min' successfully. If you need a hard ceiling for untrusted code, a role default is not one; enforce it in the connection layer or with a supervisor that cancels backends.

idle_session_timeout deserves caution with connection pools. The documentation warns that pooling software may not react well to unexpected connection closure. Most pools hold idle connections outside transactions by design, so this timeout mostly creates reconnect churn. Use it for interactive sessions, if at all.

How the application must react

  • 57014 QueryCanceled: the session is fine. In autocommit, the statement can be retried if it is idempotent. Inside a transaction, roll back first; every statement fails with 25P02 until you do.
  • 25P04 TransactionTimeout: the connection is gone. Discard it, take a fresh one, and retry the whole transaction, not the last statement.
  • Connection closed after idle in transaction: the error arrives on the next use, often far from the cause. The transaction rolled back. Retry the whole unit of work, and log it loudly, because it means code held a transaction open while doing something else.
  • Pools: make sure the pool checks or discards broken connections. A pool that hands out a terminated connection turns one timeout into a stream of errors for unrelated requests.

Failure modes

  • Relying on statement_timeout for lock holding. It measures statements, not idle time, so it misses the most common cause of long-held locks in agent tools.
  • Retrying the last statement after a session-ending timeout. The earlier statements in the transaction were rolled back; retrying only the last one applies half a change.
  • Server-wide settings. A global transaction timeout kills migrations and long reports.
  • Prepared transactions. The documentation notes they are not subject to transaction_timeout; two-phase commit needs its own monitoring.

Tradeoffs

Short session-ending timeouts protect the database and everyone waiting on locks, at the cost of more reconnects and retries in the application. Long ones are gentle on the application and hard on everyone else. A sensible split for agent tools is a short idle-in-transaction timeout (the agent should never idle inside a transaction), a transaction timeout set from the longest legitimate unit of work, and a statement timeout slightly below it for the clean, session-preserving failure on slow queries.

Verification

Run the probe against your version and driver, because drivers word the closed-connection error differently. Then check three things in production: count FATAL: terminating connection due to idle-in-transaction timeout and transaction timeout lines in the server log; query pg_stat_activity for sessions in state idle in transaction older than a second; and confirm the role settings with SELECT rolname, rolconfig FROM pg_roles.

Running the companion code

cd examples/python/postgres_session_timeouts
python example.py
python -m unittest -v test_example.py
PG_BIN=/path/to/pg/bin python live_probe.py > recorded.json

The first two commands need only the standard library and the recording; the live probe needs PostgreSQL 17 or newer binaries and psycopg.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/postgres_session_timeouts. Views are my own and do not represent any employer, past or present.