Connection timeouts prevent long-running connection attempts or queries from hanging your PostgreSQL resources.
Timeouts free up server resources, avoid app hangs, and surface network issues quickly. They act as safety nets for slow connects, runaway queries, and forgotten sessions.
Client side: connect_timeout
in the libpq connection string or PGCONNECT_TIMEOUT
env var. Server side: statement_timeout
, idle_in_transaction_session_timeout
, and from v14+ idle_session_timeout
.
connect_timeout
?Add the parameter to any libpq URL or keyword string. The value is in seconds and limits how long the client waits while opening a TCP socket and authenticating.
postgresql://app_user:secret@db.example.com:5432/shop?connect_timeout=5
statement_timeout
?Apply at session, user, or database level. When a single statement exceeds the limit, PostgreSQL cancels it automatically.
SET statement_timeout TO '8s';
Use idle_in_transaction_session_timeout
or idle_session_timeout
. These parameters terminate sessions that sit idle, preventing table locks and conserving connections.
ALTER DATABASE shop SET idle_session_timeout = '30min';
Short connect_timeout
(2-5s) keeps APIs snappy. Moderate statement_timeout
(5-15s) stops cart queries from monopolizing CPU. Use idle_session_timeout
to auto-close abandoned dashboard tabs.
Embed connect_timeout
in application connection strings. Set server-side limits in postgresql.conf
, ALTER ROLE
, or per request with SET
.
No. It only limits the initial connection attempt. Use statement_timeout for running queries.
Yes. Once EXECUTE starts, statement_timeout applies exactly as it does to ad-hoc SQL.
PostgreSQL ends the session, which implicitly rolls back any uncommitted work.