Sub topic 10
lock_timeout, statement_timeout and idle-in-transaction timeouts
This chapter assumes you can run two concurrent psql sessions, you know how BEGIN, COMMIT and ROLLBACK work, and you have read the earlier chapters on row locks, table locks and the lock queue. Here you will learn how to put an upper bound on waiting, so that one stuck transaction cannot stall an application indefinitely.
Why waiting needs a limit
By default, PostgreSQL waits for a lock forever. If session A holds a row lock and never finishes, session B waits for as long as A stays open. Deadlock detection does not help here, because a plain wait is not a cycle. Nothing is wrong from the server's point of view, so nothing is aborted.
Three settings put a limit on this kind of waiting. Each one bounds a different thing:
| Setting | What it bounds | Default |
|---|---|---|
| `lock_timeout` | Time spent waiting to acquire a single lock | 0 (disabled) |
| `statement_timeout` | Total run time of one statement, including lock waits | 0 (disabled) |
| `idle_in_transaction_session_timeout` | Time a session sits idle inside an open transaction | 0 (disabled) |
All three are measured in milliseconds unless you give a unit, so '2s', '500ms' and '1min' are all valid values. A value of 0 disables the check.
A related setting, transaction_timeout, was added in PostgreSQL 17. It limits the total length of a whole transaction. Check your server version before relying on it.
lock_timeout: bound the wait for one lock
lock_timeout aborts a statement that has waited longer than the given time for a lock. The lock can be a table lock, a row lock or an advisory lock. The timer applies to each separate lock acquisition, not to the statement as a whole.
Try it with the accounts table from the earlier chapters.
-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- Session B
SET lock_timeout = '2s';
UPDATE accounts SET balance = balance + 5 WHERE id = 1;
-- After two seconds:
-- ERROR: canceling statement due to lock timeout
-- SQLSTATE 55P03 (lock_not_available)Session B fails after two seconds. Session A is untouched and still holds its lock. In session B, only the statement fails. If B was inside a transaction, that transaction is now in an aborted state and must be rolled back (or rolled back to a savepoint) before it can run more commands.
The error code 55P03 is the same one raised by NOWAIT. An application can therefore handle both with one retry path.
Scope: session, transaction or role
You can set these parameters at several levels. The narrowest level that fits is usually the best choice.
-- For the current session
SET lock_timeout = '5s';
-- For the current transaction only; reverts at COMMIT or ROLLBACK
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE accounts ADD COLUMN note text;
COMMIT;
-- As a default for every new session of a role
ALTER ROLE app_user SET lock_timeout = '5s';
-- As a default for every new session on a database
ALTER DATABASE appdb SET lock_timeout = '5s';ALTER ROLE ... SET and ALTER DATABASE ... SET only affect sessions that start afterwards. Existing connections keep their old values. Connection poolers add a further wrinkle. In transaction-pooling mode, a plain SET can leak to the next client that receives the same server connection, so prefer SET LOCAL inside a transaction there.
Why DDL needs lock_timeout most
Most ALTER TABLE forms need an ACCESS EXCLUSIVE lock. As the lock queue chapter explained, a waiting ACCESS EXCLUSIVE request blocks every later request on that table, even plain SELECT statements. A migration that waits behind one long transaction can therefore freeze all traffic to the table.
A short lock_timeout turns that outage into a quick, harmless failure that you can retry.
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE accounts ADD COLUMN note text;
COMMIT;If the lock is not available within two seconds, the ALTER TABLE fails, the transaction aborts, and the queue behind it drains. The cost of the failed attempt is at most two seconds of delay for other queries.
statement_timeout: bound the whole statement
statement_timeout cancels any statement that runs longer than the limit. The clock starts when the server receives the command and includes time spent waiting for locks, reading data and computing results.
SET statement_timeout = '3s';
SELECT pg_sleep(10);
-- ERROR: canceling statement due to statement timeout
-- SQLSTATE 57014 (query_canceled)Because it includes lock waits, statement_timeout also limits blocking. The difference from lock_timeout is what it cannot tell you. A statement that fails with 57014 might have been slow because of a lock wait, a poor query plan or a large result. A lock_timeout failure (55P03) always means a lock was the cause.
The two settings work together. A common arrangement is a short lock_timeout for fast failure on contention and a longer statement_timeout as a safety net for runaway queries.
ALTER ROLE app_user SET lock_timeout = '3s';
ALTER ROLE app_user SET statement_timeout = '30s';Be careful with a global statement_timeout. Long-running legitimate work, such as backups with pg_dump, index builds and bulk loads, will be cancelled by it. Give maintenance roles a higher limit or set it to 0 for them.
With the extended query protocol, statement_timeout applies to each protocol message (parse, bind, execute) separately. With the simple query protocol and several statements in one string, it applies to the whole string. This matters for drivers that send multi-statement strings.
idle_in_transaction_session_timeout: close the leak at its source
Most long lock waits have a single cause: another session opened a transaction, took locks and then stopped doing anything. The application may have crashed, a developer may have forgotten to commit in a console, or code may be waiting on a slow network call between two statements.
In pg_stat_activity these sessions show state = 'idle in transaction'. They hold their locks, and they also keep old row versions from being cleaned up by vacuum.
idle_in_transaction_session_timeout terminates the whole session if it stays idle inside a transaction for longer than the limit.
-- Session A
SET idle_in_transaction_session_timeout = '10s';
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- ... do nothing for more than 10 seconds ...
-- Later, any command in session A fails with:
-- FATAL: terminating connection due to idle-in-transaction timeout
-- SQLSTATE 25P03 (idle_in_transaction_session_timeout)Unlike the other two timeouts, this one does not cancel a statement. It closes the connection. The transaction rolls back, and every lock it held is released. Sessions that were waiting on A can continue.
This is the setting that fixes the root cause rather than the symptom. Setting it for application roles is a common safeguard. Pick a value comfortably above your slowest legitimate pause between statements. Values from 30 seconds to a few minutes are typical.
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '1min';There is also idle_session_timeout (PostgreSQL 14 and later), which closes sessions that are idle outside a transaction. It matters for connection limits, not for locks.
How the three settings interact
The following diagram shows which setting fires in each situation.
When both limits apply to a lock wait, whichever expires first wins. With lock_timeout = '5s' and statement_timeout = '3s', a lock wait is cancelled at three seconds with error 57014, because the statement limit is reached before the lock limit.
Handling the errors in application code
A timeout is only useful if the application reacts correctly. Three rules cover most cases.
- Roll back the transaction. After
55P03or57014inside a transaction block, every further command fails withcurrent transaction is aborteduntil you issueROLLBACK. - Retry only operations that are safe to repeat. A lock timeout means the statement did not run, so retrying it is usually safe. Retry the whole transaction, not just the failed statement, and use a limited number of attempts with a short randomized delay.
- Reconnect after
25P03. The session is gone, so the connection object is no longer valid.
A sketch of this logic in Python with psycopg 3 looks like this.
import random
import time
import psycopg
from psycopg import errors
def transfer(conninfo: str, src: int, dst: int, amount: int) -> None:
for attempt in range(1, 4):
try:
with psycopg.connect(conninfo) as conn:
with conn.transaction():
conn.execute("SET LOCAL lock_timeout = '2s'")
conn.execute(
"UPDATE accounts SET balance = balance - %s WHERE id = %s",
(amount, src),
)
conn.execute(
"UPDATE accounts SET balance = balance + %s WHERE id = %s",
(amount, dst),
)
return
except (errors.LockNotAvailable, errors.DeadlockDetected):
if attempt == 3:
raise
time.sleep(random.uniform(0.05, 0.2) * attempt)The with conn.transaction() block rolls back automatically when an exception leaves it, so the aborted state never leaks into the retry. Note that this example also catches DeadlockDetected, because deadlock victims should be retried in the same way.
Common mistakes and edge cases
- Setting
lock_timeoutonly on the migration's connection pool, not on the migration itself. PutSET LOCAL lock_timeoutinside the migration transaction so the protection travels with the script. - Expecting
lock_timeoutto limit a slow statement. It limits only waiting. A query that holds all its locks and then runs for an hour is not affected. Usestatement_timeoutfor that. - Setting a very low
lock_timeoutglobally. Ordinary short contention, such as two updates to a popular row, will start failing. Start with several seconds for application roles and use shorter values for migrations. - Forgetting that
statement_timeoutincludes the time before the first row is returned. For a cursor or a streaming read, the clock restarts for eachFETCH, so a long-lived cursor is not bounded by one value. - Expecting timeouts to resolve deadlocks. Deadlocks are handled by
deadlock_timeout, which only decides when the check runs. A lock timeout that is shorter thandeadlock_timeout(default 1s) fires first, so the session fails with55P03and the deadlock check never runs. - Treating
idle_in_transaction_session_timeoutas a substitute for fixing the code. It limits damage, but the application still needs to commit or roll back promptly.
Checking what is configured
The pg_settings view shows the active values and where each came from.
SELECT name, setting, unit, source
FROM pg_settings
WHERE name IN (
'lock_timeout',
'statement_timeout',
'idle_in_transaction_session_timeout',
'deadlock_timeout'
);The source column tells you whether a value came from the server configuration file, a role or database setting, or the current session. If a value is not what you expect, check pg_db_role_setting for ALTER ROLE and ALTER DATABASE overrides.
Exercise
A migration runs ALTER TABLE orders ADD COLUMN note text; with lock_timeout = '2s' and statement_timeout = '1s'. Another session holds a lock on orders that conflicts with the ALTER TABLE and never commits. Which error does the migration get, and after how long? What would change if the other session were idle inside a transaction and idle_in_transaction_session_timeout were set to 30 seconds on its role?
Show answer
The migration fails after one second with canceling statement due to statement timeout (SQLSTATE 57014), because the statement limit expires before the lock limit. To get a lock_timeout error (55P03), the lock limit would have to be shorter than the statement limit. If the blocking session is idle in a transaction with a 30-second idle timeout, the server terminates that session after 30 seconds and releases its locks. A migration that is still waiting at that moment (it would need larger timeouts than in this scenario) could then proceed. With the 1-second statement limit, the migration fails first and has to be retried after the blocker is gone.
Exercise
Why does SET LOCAL lock_timeout = '2s' placed before an ALTER TABLE inside a transaction make a migration safer than running the ALTER TABLE with no timeout?
Show answer
Without a timeout, the ALTER TABLE waits indefinitely for its ACCESS EXCLUSIVE lock. While it waits in the lock queue, every later query on the table, including plain SELECT statements, queues behind it, so the table becomes unavailable. With a 2-second limit, the statement fails after two seconds, the queue drains, and the migration can be retried later. SET LOCAL also reverts at the end of the transaction, so the setting does not leak into other work on the connection.