# Fix PostgreSQL Too Many Clients Error

PostgreSQL returns "sorry, too many clients already" when the maximum number of connections is reached. New connections are rejected until existing connections close.

Introduction

This article covers troubleshooting steps and solutions for Fix PostgreSQL Too Many Clients Error. The error typically occurs in production environments and can cause service disruptions if not addressed promptly.

Symptoms

Common error messages include:

```sql -- Count connections SELECT count(*) FROM pg_stat_activity;

-- Connections by state SELECT state, count(*) FROM pg_stat_activity GROUP BY state;

-- Connections by database SELECT datname, count(*) FROM pg_stat_activity GROUP BY datname;

-- Connections by user SELECT usename, count(*) FROM pg_stat_activity GROUP BY usename; ```

```sql -- Show max connections SHOW max_connections;

-- Show superuser reserved SHOW superuser_reserved_connections; ```

sql
SELECT pid, usename, datname, state, query, query_start
FROM pg_stat_activity
ORDER BY query_start;

Common Causes

  • Configuration misconfiguration
  • Missing or incorrect credentials
  • Network connectivity issues
  • Version compatibility problems
  • Resource exhaustion or limits
  • Permission or access denied

Step-by-Step Fix

Check current connections:

```sql -- Count connections SELECT count(*) FROM pg_stat_activity;

-- Connections by state SELECT state, count(*) FROM pg_stat_activity GROUP BY state;

-- Connections by database SELECT datname, count(*) FROM pg_stat_activity GROUP BY datname;

-- Connections by user SELECT usename, count(*) FROM pg_stat_activity GROUP BY usename; ```

Check max connections:

```sql -- Show max connections SHOW max_connections;

-- Show superuser reserved SHOW superuser_reserved_connections; ```

View all connections:

sql
SELECT pid, usename, datname, state, query, query_start
FROM pg_stat_activity
ORDER BY query_start;

Common Causes and Solutions

Cause 1: Connection Leaks

sql
-- Many idle connections from same application
SELECT usename, application_name, count(*)
FROM pg_stat_activity
WHERE state = 'idle'
GROUP BY usename, application_name;

Solution:

```python # Fix connection leak in application import psycopg2 from contextlib import contextmanager

@contextmanager def get_connection(): conn = psycopg2.connect(DATABASE_URL) try: yield conn finally: conn.close()

# Usage with get_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT 1") ```

Cause 2: No Connection Pooling

sql
-- Each request opens new connection

Solution:

```python # Use connection pooling import psycopg2.pool

# Threaded connection pool pool = psycopg2.pool.ThreadedConnectionPool( minconn=5, maxconn=20, dsn=DATABASE_URL )

def get_connection(): return pool.getconn()

def release_connection(conn): pool.putconn(conn)

# Or use PgBouncer ```

Install PgBouncer:

```bash # Install apt-get install pgbouncer

# Configure /etc/pgbouncer/pgbouncer.ini [databases] mydb = host=localhost port=5432 dbname=mydb

[pgbouncer] listen_addr = 0.0.0.0 listen_port = 6432 auth_type = md5 auth_file = /etc/pgbouncer/userlist.txt pool_mode = transaction max_client_conn = 1000 default_pool_size = 25

# Start systemctl start pgbouncer ```

Cause 3: Long-Running Transactions

sql
-- Find long-running transactions
SELECT pid, usename, datname, state,
       now() - query_start AS duration,
       query
FROM pg_stat_activity
WHERE state = 'active'
  AND query_start < now() - interval '5 minutes'
ORDER BY duration DESC;

Solution:

```sql -- Terminate long-running queries SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'active' AND query_start < now() - interval '30 minutes' AND usename != 'postgres';

-- Set statement timeout ALTER DATABASE mydb SET statement_timeout = '300000'; -- 5 minutes

-- Set idle transaction timeout ALTER DATABASE mydb SET idle_in_transaction_session_timeout = '60000'; -- 1 minute ```

Cause 4: Insufficient max_connections

sql
-- max_connections too low for workload

Solution:

```bash # Edit postgresql.conf max_connections = 200

# Remember: max_connections * work_mem affects memory # Total memory = max_connections * work_mem + shared_buffers

# Restart PostgreSQL systemctl restart postgresql ```

Cause 5: Prepared Transactions Not Committed

```sql -- Check prepared transactions SELECT * FROM pg_prepared_xacts;

-- These hold connections ```

Solution:

```sql -- Commit or rollback prepared transactions COMMIT PREPARED 'transaction_id'; -- or ROLLBACK PREPARED 'transaction_id';

-- Set limit on prepared transactions # postgresql.conf max_prepared_transactions = 10 ```

Cause 6: Replication Slots Holding Connections

sql
-- Check replication slots
SELECT * FROM pg_replication_slots;

Solution:

```sql -- Drop unused replication slots SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots WHERE active = false;

-- Configure WAL retention # postgresql.conf wal_keep_size = 1GB max_replication_slots = 5 ```

Emergency Recovery

When completely locked out:

```bash # Connect as superuser (reserved connections) psql -U postgres

# Or use single-user mode postgres --single -D /var/lib/postgresql/data

# Then kill connections SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename != 'postgres'; ```

Connection Pooling Best Practices

PgBouncer Configuration

```ini # /etc/pgbouncer/pgbouncer.ini [databases] mydb = host=localhost port=5432 dbname=mydb pool_size=25

[pgbouncer] listen_addr = 0.0.0.0 listen_port = 6432 auth_type = scram-sha-256 auth_file = /etc/pgbouncer/userlist.txt

# Pool settings pool_mode = transaction max_client_conn = 1000 default_pool_size = 25 min_pool_size = 5 max_db_connections = 50 reserve_pool_size = 5 reserve_pool_timeout = 3

# Timeouts server_idle_timeout = 300 server_lifetime = 3600 server_connect_timeout = 15 client_idle_timeout = 0 client_lifetime = 0

# Logging log_connections = 1 log_disconnections = 1 log_pooler_errors = 1 ```

Application Configuration

```python # SQLAlchemy with pooling from sqlalchemy import create_engine

engine = create_engine( DATABASE_URL, pool_size=10, max_overflow=20, pool_timeout=30, pool_recycle=3600, pool_pre_ping=True ) ```

Monitoring

```sql -- Create monitoring view CREATE VIEW connection_stats AS SELECT datname, usename, application_name, state, count(*) AS connections, max(now() - query_start) AS max_duration FROM pg_stat_activity GROUP BY datname, usename, application_name, state;

-- Alert query SELECT * FROM connection_stats WHERE connections > 10 OR max_duration > interval '10 minutes'; ```

Verification

```sql -- Check connection count SELECT count(*) FROM pg_stat_activity;

-- Verify max_connections SHOW max_connections;

-- Test connection psql -h localhost -U myuser -d mydb -c "SELECT 1"

-- Check pool stats (if using PgBouncer) psql -h localhost -p 6432 pgbouncer -c "SHOW POOLS" ```

Prevention

  1. 1.[ ] Check current connection count
  2. 2.[ ] Identify connection sources
  3. 3.[ ] Find and fix connection leaks
  4. 4.[ ] Implement connection pooling
  5. 5.[ ] Set appropriate timeouts
  6. 6.[ ] Configure max_connections properly
  7. 7.[ ] Monitor connection metrics
  8. 8.[ ] Set up alerting
  9. 9.[ ] Test failover scenario
  10. 10.[ ] Document recovery procedure
  • [Database troubleshooting: Fix Backup Exclusive Lock Table Production Writes ](backup-exclusive-lock-table-production-writes)
  • [Fix Connection Pool Leak Application Not Closing Issue in Database](connection-pool-leak-application-not-closing)
  • [Fix Connection Reset Idle Timeout Firewall Issue in Database](connection-reset-idle-timeout-firewall)
  • [Fix Connection Reset Idle Timeout Serverless Database Issue in Database](connection-reset-idle-timeout-serverless-database)
  • [Fix Connection String Encoding Special Characters Issue in Database](connection-string-encoding-special-characters)

<script type="application/ld+json"> { "@context": "https://schema.org", "@type": "TechArticle", "headline": "Fix PostgreSQL Too Many Clients Error", "description": "Step-by-step guide to fix PostgreSQL too many clients error. Configure connection limits, implement pooling, and manage connections.", "url": "https://www.fixwikihub.com/fix-postgres-too-many-clients", "publisher": { "@type": "Organization", "name": "FixWikiHub", "url": "https://www.fixwikihub.com" }, "author": { "@type": "Person", "name": "FixWikiHub Editorial Team" }, "datePublished": "2026-04-27T10:32:00.000Z", "dateModified": "2026-04-27T10:32:00.000Z" } </script>