Home / Databases / PostgreSQL

DatabasesHow-toIntermediate

PostgreSQL timeouts that protect production: statement_timeout, lock_timeout, idle and transaction timeouts per role and database

Stop runaway queries, lock pile-ups and forgotten sessions by setting PostgreSQL timeouts per role and database instead of one global value, and handle the errors they raise.

Deepak Bhardwaj7 min read

Applies toPostgreSQL 12-18 (idle_session_timeout 14+, transaction_timeout 17+), Amazon RDS/Aurora PostgreSQL, Azure Database for PostgreSQL Flexible Server

Goal

One report query runs for six hours, or a migration waits on a lock and every application query queues behind it, or a crashed app server leaves sessions sitting idle in transaction overnight. PostgreSQL has a timeout for each of these, and all of them default to 0 (disabled).

This guide sets them where they belong: per application role and per database, with a short override for the jobs that need more time.

The timeouts and what they stop

Setting What it limits Error the client sees SQLSTATE Version
statement_timeout Run time of one statement canceling statement due to statement timeout 57014 All supported
lock_timeout Time one statement waits to get a lock canceling statement due to lock timeout 55P03 All supported
idle_in_transaction_session_timeout Time a session sits idle inside an open transaction terminating connection due to idle-in-transaction timeout 25P03 9.6+
idle_session_timeout Time a session sits idle outside a transaction terminating connection due to idle-session timeout 57P05 14+
transaction_timeout Total time of one transaction, idle time included terminating connection due to transaction timeout 25P04 17+

The first two cancel the statement and leave the session connected. The idle and transaction timeouts end the whole session. Message text can differ slightly between versions, so match on SQLSTATE in application code.

Check what is set today

Settings can come from the server config, the database, the role, or the session. This shows the effective value and where it came from:

SELECT name, setting, unit, source
FROM pg_settings
WHERE name IN ('statement_timeout','lock_timeout',
               'idle_in_transaction_session_timeout',
               'idle_session_timeout','transaction_timeout');

Per-role and per-database overrides live in pg_db_role_setting:

SELECT coalesce(r.rolname, '(all roles)') AS role,
       coalesce(d.datname, '(all databases)') AS database,
       s.setconfig
FROM pg_db_role_setting s
LEFT JOIN pg_roles r    ON r.oid = s.setrole
LEFT JOIN pg_database d ON d.oid = s.setdatabase
ORDER BY 1, 2;

In psql, \drds shows the same thing.

Set timeouts per role, not globally

A global statement_timeout in postgresql.conf also hits your ALTER TABLE, CREATE INDEX, VACUUM runs and maintenance scripts. Set it on the roles that run application traffic instead.

Warning

A global statement_timeout can cancel a long CREATE INDEX CONCURRENTLY partway through and leave an INVALID index behind. Keep the global value at 0 or generous, and set the tight limits per role.

OLTP application role

ALTER ROLE app_web SET statement_timeout = '30s';
ALTER ROLE app_web SET lock_timeout = '5s';
ALTER ROLE app_web SET idle_in_transaction_session_timeout = '60s';

Reporting and BI role

ALTER ROLE app_reporting SET statement_timeout = '15min';
ALTER ROLE app_reporting SET idle_in_transaction_session_timeout = '5min';

A role in one database only

ALTER ROLE app_web IN DATABASE orders SET statement_timeout = '10s';

A database-wide default

ALTER DATABASE orders SET idle_in_transaction_session_timeout = '10min';

If several levels set the same parameter, the most specific one wins: role-in-database beats role, which beats database, which beats the server config. A SET in the session beats all of them.

These values are applied at login. Existing sessions keep their old values until they reconnect, so recycle connection pools after a change. Check a new session with:

SHOW statement_timeout;

To remove an override:

ALTER ROLE app_web RESET statement_timeout;

Use lock_timeout for every DDL change

The most common outage pattern: an ALTER TABLE waits for an ACCESS EXCLUSIVE lock behind one long transaction, and every new query on that table queues behind the ALTER. A short lock_timeout makes the DDL give up instead of freezing the table.

BEGIN;
SET LOCAL lock_timeout = '3s';
SET LOCAL statement_timeout = '0';   -- the change itself may take time once it has the lock
ALTER TABLE orders ADD COLUMN source text;
COMMIT;

If it fails with SQLSTATE 55P03, find and deal with the blocker, then retry. A simple retry loop in your migration tool works well:

for i in 1 2 3 4 5; do
  psql "$PGURL" -v ON_ERROR_STOP=1 -c "SET lock_timeout='3s'; ALTER TABLE orders ADD COLUMN source text;" && break
  echo "lock not acquired, retry $i"; sleep 10
done

SET LOCAL lasts until the end of the transaction, so it does not leak into the next statement on a pooled connection.

Override for a single long job

When a known batch needs more time than its role allows, raise the limit inside the job's own transaction instead of loosening the role:

BEGIN;
SET LOCAL statement_timeout = '2h';
CALL nightly_rollup();
COMMIT;

pg_dump sets statement_timeout and idle_in_transaction_session_timeout to 0 for its own session, so role limits do not cancel a dump. Your own scripts and ETL tools get no such protection; give those roles their own, looser limits.

idle_session_timeout and connection poolers

idle_session_timeout closes sessions that sit idle outside a transaction. That is useful for interactive users who leave psql or a GUI open. It works against connection pools.

Caution

Do not set idle_session_timeout for roles used through PgBouncer, RDS Proxy or an application pool. The server closes pooled connections, and the next request on that connection fails with a connection error. Set it only on roles used by people.

ALTER ROLE analyst_jane SET idle_session_timeout = '30min';

transaction_timeout (PostgreSQL 17 and later)

transaction_timeout caps a whole transaction, including the time spent idle between statements. It catches the case where each statement is quick but the application holds the transaction open for minutes.

ALTER ROLE app_web SET transaction_timeout = '2min';

Set it higher than statement_timeout, or it ends the session before the statement timeout ever fires. On older versions, idle_in_transaction_session_timeout plus statement_timeout is the closest you can get.

Managed services

On RDS and Aurora PostgreSQL, ALTER ROLE ... SET and ALTER DATABASE ... SET work as normal and are the preferred approach. Server-wide defaults go in the parameter group:

aws rds modify-db-parameter-group \
  --db-parameter-group-name pg16-prod \
  --parameters "ParameterName=idle_in_transaction_session_timeout,ParameterValue=600000,ApplyMethod=immediate"

On Aurora, use modify-db-cluster-parameter-group if the parameter lives in the cluster parameter group; check which group holds it in your engine version.

On Azure Database for PostgreSQL Flexible Server:

az postgres flexible-server parameter set \
  --resource-group rg-db-prod --server-name pg-orders-prod \
  --name idle_in_transaction_session_timeout --value 600000

Values without a unit are in milliseconds.

Handle the errors in the application

SQLSTATE Meaning What the app should do
57014 Statement took too long Log the query and parameters; do not retry blindly, fix the query or the limit
55P03 Could not get a lock in time Safe to retry with backoff; the transaction was not applied
25P03 Session idle in transaction too long Connection is gone; the pool must discard it. Fix the code path that left the transaction open
57P05 Idle session closed Reconnect; should only affect human users
25P04 Transaction ran too long Connection is gone; shorten the transaction

Count how often each one fires. Turn on log_min_error_statement = error (the default) and search the server log for the messages above, or count by SQLSTATE if you log %e in log_line_prefix.

Prevent it next time

  • Give every application its own role and set statement_timeout, lock_timeout and idle_in_transaction_session_timeout on that role when you create it.
  • Make SET LOCAL lock_timeout part of every migration script template.
  • Keep global statement_timeout at 0 and leave maintenance, backup and DBA roles unrestricted or loosely restricted.
  • Review pg_db_role_setting in your monthly configuration check so overrides don't drift.
  • Alert on a rising count of 57014 and 55P03 errors. A sudden increase usually means a plan change or a new blocking job.