PostgreSQL Connection Exhaustion & Slow Queries: Fix Guide
In this article
This guide walks you through diagnosing and fixing two common PostgreSQL performance problems: connection exhaustion (too many connections, errors like "too many clients already") and slow queries. You'll learn how to identify the root cause, apply practical fixes, and prevent recurrence. No prior PostgreSQL tuning experience is needed, but you should have superuser or pg_admin access to the database.
What You'll Need
- Access to the PostgreSQL server (psql or pgAdmin).
- Permission to run
SHOW,pg_stat_activity, andEXPLAINqueries. - Ability to edit PostgreSQL configuration files (postgresql.conf) and restart the service.
- Basic familiarity with SQL queries.
Step-by-Step
-
Check current connections and limits.
RunSHOW max_connections;to see the configured limit. Then querypg_stat_activityto see how many connections are active, idle, or stuck:SELECT state, count(*) FROM pg_stat_activity GROUP BY state;
If the count is near max_connections, you have connection exhaustion. -
Identify connection hogs.
RunSELECT pid, usename, application_name, client_addr, state, query FROM pg_stat_activity ORDER BY state;Look for many idle connections from the same app or IP. These are often caused by connection pools not releasing connections or apps not closing them. -
Kill stuck or idle connections (temporary fix).
Terminate idle connections withSELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle';Use with caution—only kill connections you recognize as stale. -
Fix the connection pool configuration.
If you use a connection pooler (PgBouncer, pgbouncer, or app-level pool), set a reasonablemax_client_connanddefault_pool_size. For app-level pools (like HikariCP), set maximumPoolSize to something like 10–20 per instance, not hundreds. Ensure your app closes connections in afinallyblock or uses try-with-resources. -
Find slow queries.
Enable query logging in postgresql.conf: setlog_min_duration_statement = 1000(logs queries taking over 1 second). Restart PostgreSQL or reload config. Then check the log file for slow queries. -
Analyze slow queries with EXPLAIN.
Take a slow query and runEXPLAIN (ANALYZE, BUFFERS) your_query;Look for sequential scans on large tables, high buffer usage, or nested loops. Note the actual vs. estimated row counts—big discrepancies suggest outdated statistics. -
Update statistics.
RunANALYZE;on the involved tables. If the data changes frequently, consider adjustingautovacuumsettings to run more often. -
Add missing indexes.
For columns used in WHERE, JOIN, or ORDER BY, create indexes:CREATE INDEX idx_name ON table (column);For composite conditions, create composite indexes. But don't over-index—each index slows writes. -
Optimize the query itself.
AvoidSELECT *, use LIMIT, rewrite subqueries as JOINs when possible, and useEXISTSinstead ofINfor large subqueries. Ensure you're not doing function calls on indexed columns (e.g.,WHERE lower(email) = ...). -
Check for lock contention.
If queries are slow but not CPU-bound, checkpg_locksfor blocked queries. RunSELECT * FROM pg_stat_activity WHERE wait_event_type IS NOT NULL;If you see locks, find the blocking query and consider terminating it or fixing the transaction that holds the lock. -
Adjust PostgreSQL memory settings (if needed).
If slow queries are due to disk I/O, increaseshared_buffers(typically 25% of RAM),effective_cache_size(50-75% of RAM), andwork_mem(start with 4-16MB). Be careful not to overcommit memory. -
Monitor and repeat.
After changes, monitor connection count and query times. Usepg_stat_statementsto track query performance over time. Continuously review and tune.
Common Mistakes
- Killing all idle connections without checking if they're part of a connection pool—this can crash your app.
- Setting max_connections too high (e.g., 1000) without increasing shared memory, causing startup failure.
- Adding indexes on every column, leading to slow writes and bloat.
- Forgetting to ANALYZE after bulk data changes, causing poor query plans.
- Using
SELECT *in production queries, which increases I/O.
Tips
- Use a connection pooler like PgBouncer to handle many client connections with a small number of actual DB connections.
- Set
idle_in_transaction_session_timeoutto 5 minutes to auto-kill stuck transactions. - Use
pg_stat_statementsto find the most frequent slow queries. - Schedule
VACUUMandANALYZEduring off-peak hours. - Consider using read replicas for heavy reporting queries.
Troubleshooting
If the steps above don't resolve the issue:
- Connection exhaustion persists: Check if your app is leaking connections by monitoring
pg_stat_activityover time. UseSELECT pid, usename, application_name, state, query_start FROM pg_stat_activity;to see if connections are being created and not closed. Look for connection pool settings in your app framework. - Queries still slow after indexing: Run
EXPLAIN (ANALYZE, BUFFERS)again. If the index isn't used, check if the query has a function on the indexed column, or if the planner thinks a seq scan is cheaper due to low statistics. Force index usage withSET enable_seqscan = off;(temporarily) to test. - Server crashes after changing shared_buffers: Revert to previous value. Shared_buffers should not exceed 40% of RAM. Check the PostgreSQL log for errors.
- Lock contention not resolved: Find the blocking query with
SELECT * FROM pg_stat_activity WHERE pid IN (SELECT pid FROM pg_locks WHERE NOT granted);Then terminate the blocking session or ask the developer to commit/rollback. - No slow queries in log: Ensure
log_min_duration_statementis set correctly and the log file is writable. Also checklog_statementif you need all queries.
Frequently Asked Questions
How do I know if I have connection exhaustion?
If you see errors like "FATAL: sorry, too many clients already" or the count of connections in pg_stat_activity is near max_connections, you have exhaustion.
What is a safe max_connections value?
It depends on your RAM. A rough formula: max_connections * (shared_buffers + work_mem) should be less than available RAM. Start with 100 and increase if needed.
Why is my query slow even with an index?
Possible reasons: the index isn't selective enough (returns too many rows), the query uses a function on the indexed column, or the planner chooses a seq scan because the table is small. Run EXPLAIN to see.
Should I use a connection pooler?
Yes, if you have many concurrent clients (e.g., web apps). PgBouncer in transaction mode is recommended for most workloads.
How often should I run ANALYZE?
After significant data changes (e.g., bulk inserts) or if you see stale statistics. Autovacuum runs it automatically, but you can adjust its frequency.
Can I kill a stuck query?
Yes, use SELECT pg_cancel_backend(pid); to cancel, or pg_terminate_backend(pid) to kill. Be careful not to kill critical processes.