Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Connection Exhaustion & Slow Queries: Fix Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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, and EXPLAIN queries.
  • Ability to edit PostgreSQL configuration files (postgresql.conf) and restart the service.
  • Basic familiarity with SQL queries.

Step-by-Step

  1. Check current connections and limits.
    Run SHOW max_connections; to see the configured limit. Then query pg_stat_activity to 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.
  2. Identify connection hogs.
    Run SELECT 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.
  3. Kill stuck or idle connections (temporary fix).
    Terminate idle connections with SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle'; Use with caution—only kill connections you recognize as stale.
  4. Fix the connection pool configuration.
    If you use a connection pooler (PgBouncer, pgbouncer, or app-level pool), set a reasonable max_client_conn and default_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 a finally block or uses try-with-resources.
  5. Find slow queries.
    Enable query logging in postgresql.conf: set log_min_duration_statement = 1000 (logs queries taking over 1 second). Restart PostgreSQL or reload config. Then check the log file for slow queries.
  6. Analyze slow queries with EXPLAIN.
    Take a slow query and run EXPLAIN (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.
  7. Update statistics.
    Run ANALYZE; on the involved tables. If the data changes frequently, consider adjusting autovacuum settings to run more often.
  8. 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.
  9. Optimize the query itself.
    Avoid SELECT *, use LIMIT, rewrite subqueries as JOINs when possible, and use EXISTS instead of IN for large subqueries. Ensure you're not doing function calls on indexed columns (e.g., WHERE lower(email) = ...).
  10. Check for lock contention.
    If queries are slow but not CPU-bound, check pg_locks for blocked queries. Run SELECT * 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.
  11. Adjust PostgreSQL memory settings (if needed).
    If slow queries are due to disk I/O, increase shared_buffers (typically 25% of RAM), effective_cache_size (50-75% of RAM), and work_mem (start with 4-16MB). Be careful not to overcommit memory.
  12. Monitor and repeat.
    After changes, monitor connection count and query times. Use pg_stat_statements to 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_timeout to 5 minutes to auto-kill stuck transactions.
  • Use pg_stat_statements to find the most frequent slow queries.
  • Schedule VACUUM and ANALYZE during 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_activity over time. Use SELECT 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 with SET 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_statement is set correctly and the log file is writable. Also check log_statement if 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.