brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ALTER ROLE … SET statement_timeout caps query time for one PostgreSQL user

Postgresql
~/tips/tip-postgresql-role-statement-timeout

ALTER ROLE report SET statement_timeout = '30s';

Gives one login a maximum query time so its runaway queries stop on their own.

A reporting tool or a read-only user can start queries that run for an hour. A time limit for that role stops them without affecting anybody else.

ALTER ROLE report SET statement_timeout = '30s';

Every new session of report now has a 30 second limit. A statement that runs longer stops with canceling statement due to statement timeout. Units such as ms, s and min work; a bare number is milliseconds. A related setting is useful for the same kind of user:

ALTER ROLE report SET idle_in_transaction_session_timeout = '5min';

That closes a session that opened a transaction and then sat idle, which otherwise holds locks and blocks vacuum.

The docs advise against setting statement_timeout in postgresql.conf, because it would hit every session, including your own maintenance and dumps. Per role, or per role and database with ALTER ROLE report IN DATABASE appdb SET ..., is the scoped version, and the one I’d use.

Role settings take effect at login only, so sessions that are already open keep the old value, and pooled connections may stay old for a long time. The user can also override it with a plain SET statement_timeout in their session, so it is a safety net and not a hard security limit. Check what is set with \drds in psql.

Further reading: ALTER ROLE, Client connection defaults (statement_timeout)

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link