← Back to PostgreSQL, page 3

postgresql-0055 · Medium mid

Stop runaway queries with statement_timeout, and set it per role or per transaction.

statement_timeout cancels any statement that runs longer than the limit with an error. Set it per session, per transaction with SET LOCAL, or as a default for an application role with ALTER ROLE ... SET, so one bad query cannot hold connections indefinitely. Reporting roles can be given longer limits than web-request roles.

Full answer

Sample schema and data:

sql
CREATE TABLE numbers (n int);
INSERT INTO numbers SELECT generate_series(1, 10);
sql
SET statement_timeout = '100ms'; SELECT pg_sleep(1);

Result on PostgreSQL 17:

text
ERROR:  canceling statement due to statement timeout
sql
BEGIN; SET LOCAL statement_timeout = '5s'; SELECT count(*) AS rows_counted FROM numbers; SHOW statement_timeout;

Result:

text
 statement_timeout
-------------------
 5s
(1 row)
sql
COMMIT; SHOW statement_timeout;

Output:

text
 statement_timeout
-------------------
 0
(1 row)

The one-second sleep is cancelled after 100 ms with 'canceling statement due to statement timeout'. SET LOCAL changes the value for the current transaction only: inside it the limit shows 5s, and after COMMIT the setting is back to 0, meaning no limit. It is 0 rather than 100ms because the first script ran as one implicit transaction that failed, and a SET inside a failed transaction is rolled back along with everything else. In production, a typical pattern is ALTER ROLE web_app SET statement_timeout = '5s' and a longer limit for a reporting role, with exceptions raised by SET LOCAL in the few transactions that need more time.

sql
CREATE TABLE numbers (n int);
INSERT INTO numbers SELECT generate_series(1, 10);

SET statement_timeout = '100ms'; SELECT pg_sleep(1);

BEGIN; SET LOCAL statement_timeout = '5s'; SELECT count(*) AS rows_counted FROM numbers; SHOW statement_timeout;

COMMIT; SHOW statement_timeout;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • statement_timeout cancels long statements
  • SET LOCAL scopes to a transaction
  • ALTER ROLE sets defaults per role
  • Different roles need different limits
  • Pair with lock_timeout and idle timeouts

Common mistakes

  • No timeout on web-facing roles
  • Setting a global timeout that breaks maintenance jobs

Follow-ups

  • What is idle_in_transaction_session_timeout for?
  • How does a timeout interact with connection poolers?

Tips

  • Show SET LOCAL scope