Prompt
Why am I hitting too many connections in PostgreSQL?
Latest observation
Oct 7, 2026
OpenAI APIWeb search: off
“Too many connections” in PostgreSQL usually means your application is opening more sessions than PostgreSQL is configured to allow, or it’s not reusing/closing connections efficiently.
Common causes:
- Connection leaks: code opens a connection and never closes it.
- Too many app instances: multiple web servers, workers, cron jobs, or autoscaled pods each create their own pool.
- Pool misconfiguration: connection pool size is set too high per process, so total connections exceed PostgreSQL’s
max_connections. - Burst traffic / thundering herd: many requests start at once and each tries to grab a DB connection.
- Long-lived idle sessions: connections sit idle but still count against the limit.
- Background jobs / migrations / admin tools: these can quietly consume many connections.
- Database proxies absent or misused: without PgBouncer or similar, every client may connect directly to Postgres.
What to check first:
-
See current connection usage
SELECT state, count(*) FROM pg_stat_activity GROUP BY state; -
Find who is connecting
SELECT usename, application_name, client_addr, state, count(*) FROM pg_stat_activity GROUP BY usename, application_name, client_addr, state ORDER BY count(*) DESC; -
Check PostgreSQL limit
SHOW max_connections; -
Inspect idle connections
SELECT pid, usename, application_name, state, query, state_change FROM pg_stat_activity WHERE state = 'idle' ORDER BY state_change ASC;
How to fix it:
- Close connections properly in application code.
- Use a connection pool and set a sensible pool size.
- Lower per-process pool sizes if you run many app workers.
- Use PgBouncer to multiplex many clients onto fewer DB connections.
- Set
idle_timeout/maxLifetimein pools to prevent stale connections. - Avoid opening a connection per request if your framework already supports pooling.
- Increase
max_connectionsonly if necessary; it uses more memory and isn’t the best first fix.
Rule of thumb:
If you have N app instances and each has pool size P, your worst-case DB connections are roughly N × P plus extras for migrations, admin, monitoring, and background jobs.
If you want, I can help you diagnose it with a few queries from pg_stat_activity and your app’s pool settings.
Brands