What the message looks like
FATAL: sorry, too many clients already
connection to server at "db" (10.0.0.5), port 5432 failedCommon causes
- The application opens connections and never closes them, for example after a deploy or in a worker without
finally. - The sum of all pool sizes exceeds
max_connections, especially with several instances or containers. - A PgBouncer in
sessionmode passes every client connection through and defeats pooling. - Transactions stay
idle in transactionand hold slots without doing work. - Backup, monitoring and migration jobs add to the application pools.
Check
- Used and allowed connections
psql -c "SELECT count(*) AS used, current_setting('max_connections')::int AS max FROM pg_stat_activity;" - Who holds the connections?
psql -c "SELECT usename, state, count(*) FROM pg_stat_activity GROUP BY 1,2 ORDER BY 3 DESC;" - Long idle transactions
psql -c "SELECT pid, now()-state_change AS idle_for, query FROM pg_stat_activity WHERE state LIKE 'idle in transaction%' ORDER BY 2 DESC LIMIT 10;" - Reserved slots
psql -c "SHOW superuser_reserved_connections;"
Fix
- Measure first, then raise: a bigger
max_connectionsonly hides a leak and costs memory per backend. - Close the leak: use context managers or
finally, and keep each pool smaller thanmax_connections / instances. - For many short connections put PgBouncer in
transactionmode in front. - Set
idle_in_transaction_session_timeoutso stuck transactions are terminated. - Raise the limit only with memory headroom for autovacuum and backups, and remember it needs a restart.
FAQ
Is raising max_connections enough?
Briefly, yes. With a leak the error returns within hours. Measure who holds the slots first.
Why are fewer connections free than max_connections suggests?
Reserved slots for superusers and background processes count against the limit, so a normal client hits it earlier.