Database Connection Timeouts
Configuring time limits for establishing database connections and executing queries to prevent resource exhaustion from hanging operations.
Description
Database timeout settings are essential safety nets that prevent a single misbehaving query or network issue from cascading into a system-wide outage. There are several distinct timeouts to configure: connect_timeout (how long to wait when establishing a new connection), statement_timeout (maximum execution time for a single SQL statement), lock_timeout (how long to wait for a lock before aborting), and idle_in_transaction_session_timeout (how long a session can sit idle inside an open transaction before being terminated).
Without proper timeouts, a slow query can hold a connection from the pool indefinitely, eventually exhausting all available connections and causing the entire application to hang. A query stuck waiting for a lock can hold its own locks, creating a cascading chain of blocked transactions. An application bug that opens a transaction but never commits it can hold locks and prevent vacuum from reclaiming dead tuples, leading to table bloat and degraded performance over hours.
Set timeouts at multiple levels for defense in depth: at the PostgreSQL server level (postgresql.conf) as a safety net, at the connection pool level (PgBouncer query_timeout), and at the application level (per-query timeouts in your database driver). Use shorter timeouts for user-facing web requests (5-30 seconds) and longer timeouts for background jobs and migrations (minutes to hours). Monitor timeout events in your logs and alert on sudden increases, which indicate emerging performance problems.
Prompt Snippet
Configure layered timeouts: set statement_timeout = 30s globally in postgresql.conf as a safety net, lock_timeout = 5s to fail fast on lock contention, and idle_in_transaction_session_timeout = 60s to kill abandoned transactions. In PgBouncer, set query_timeout = 30s and client_idle_timeout = 300s. At the application level, set per-query timeouts: 5s for API handlers, 60s for background jobs, and disable statement_timeout for migrations (SET LOCAL statement_timeout = 0 within the migration transaction). Monitor pg_stat_activity for queries exceeding 10s and log them with auto_explain for investigation.
Tags
Related Terms
Database Connection Pooling
Maintaining a reusable pool of database connections to avoid the overhead of establishing new connections for every query.
Deadlock Detection & Prevention
Strategies for detecting when two or more transactions are permanently blocked waiting for each other's locks, and design patterns to prevent this from occurring.
Connection String Security
Protecting database connection strings containing credentials from exposure in code, logs, and configuration files.