Skip to content
FR
  1. LuzineDebug
  2. Databases (SQL)
  3. ERROR 1040 (HY000): Too many connections
Databases (SQL) Intermediate ≈ 20 min to fix

Fix "ERROR 1040: Too many connections" (MySQL) and "too many clients already" (PostgreSQL)

Error message
ERROR 1040 (HY000): Too many connections
  • SQLSTATE[HY000] [1040] Too many connections
  • SQLSTATE[08004] [1040] Too many connections
  • FATAL: sorry, too many clients already
  • FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute
  • Data source rejected establishment of connection, message from server: "Too many connections"
In short

The server reached its maximum number of simultaneous connections (max_connections) and refuses new ones. Count who holds the connections (SHOW PROCESSLIST, pg_stat_activity), fix leaks and size pools and PHP-FPM workers under the limit; only raise max_connections afterwards, if RAM allows it.

Be the first to confirm this fix

What this error means

Every client connection takes a slot on the server: a thread in MySQL, a whole process in PostgreSQL. When their number reaches max_connections (151 by default in MySQL, 100 in PostgreSQL), the server refuses the next ones. MySQL keeps one extra connection for an account with the CONNECTION_ADMIN (or SUPER) privilege, so an administrator can step in. PostgreSQL reserves a few slots (superuser_reserved_connections, 3 by default), hence the "remaining connection slots are reserved" message. It is almost never a server bug: the sum of pools and workers exceeds the limit, or connections stay open doing nothing.

Common causes

  1. Too many clients for the limit: every PHP-FPM process opens its own connection, so pm.max_children × number of servers, plus queue workers and crons, exceeds max_connections. Same effect with serverless functions scaling out.
  2. Connection leaks: code takes a connection without giving it back (pool.connect() without client.release() in Node, cursors never closed in Python).
  3. Oversized pools: a pool of 20 per instance × 10 replicas = 200 connections, above MySQL’s default 151.
  4. Idle connections never closed: persistent connections, an 8-hour wait_timeout that lets Sleep sessions pile up.
  5. Slow queries or locks: connections pile up waiting for a blocked query, until they hit the limit.

Step-by-step fix

  1. MySQL: measure who holds the connections

    Compare Threads_connected and Max_used_connections with the limit, then group sessions by user, host and state. Many Sleep sessions from one host point to a pool or persistent connections. If you can no longer connect, use an account with CONNECTION_ADMIN: it gets the reserved slot.

    sql
    SHOW VARIABLES LIKE 'max_connections';
    SHOW GLOBAL STATUS LIKE 'Threads_connected';
    SHOW GLOBAL STATUS LIKE 'Max_used_connections';
    
    SELECT user, host, db, command, COUNT(*) AS n
    FROM information_schema.processlist
    GROUP BY user, host, db, command
    ORDER BY n DESC;
  2. PostgreSQL: count the sessions

    pg_stat_activity shows each connection with its application and state. Many idle sessions mean oversized pools; idle in transaction points to code that opens a transaction without ending it.

    sql
    SHOW max_connections;
    
    SELECT usename, application_name, client_addr, state, count(*)
    FROM pg_stat_activity
    GROUP BY 1, 2, 3, 4
    ORDER BY 5 DESC;
  3. Free slots in an emergency

    Only cut sessions that have been idle for a long time: the application concerned will lose its connection and must reconnect. In MySQL, take the Id of a Sleep row with a large Time from SHOW PROCESSLIST. This is a band-aid: the real fix is in the next steps.

    sql
    -- MySQL
    KILL 12345;
    
    -- PostgreSQL
    SELECT pg_terminate_backend(pid)
    FROM pg_stat_activity
    WHERE datname = 'app'
      AND state = 'idle'
      AND state_change < now() - interval '10 minutes';
  4. Size the pools and fix leaks

    Do the math: instances × (pool size or pm.max_children) + workers + admin margin must stay below max_connections. Shrink pools (Prisma: ?connection_limit=5 in the URL), and always give the connection back to the pool, even on error.

    javascript
    import pg from 'pg';
    
    const pool = new pg.Pool({ max: 10, idleTimeoutMillis: 30000 });
    
    const client = await pool.connect();
    try {
      await client.query('SELECT 1');
    } finally {
      client.release();
    }
  5. Put a pooler in front of the database

    When many clients open short connections (PHP-FPM, serverless), a pooler multiplexes hundreds of clients over a few real connections: PgBouncer for PostgreSQL, ProxySQL for MySQL. The application then connects to the pooler port (6432 here). In transaction mode, avoid server-side prepared statements and session SET if your version or driver does not support them.

    ini
    [databases]
    app = host=127.0.0.1 port=5432 dbname=app
    
    [pgbouncer]
    listen_addr = 127.0.0.1
    listen_port = 6432
    auth_type = scram-sha-256
    auth_file = /etc/pgbouncer/userlist.txt
    pool_mode = transaction
    max_client_conn = 1000
    default_pool_size = 20
  6. Raise the limit if memory allows

    Each connection uses RAM (especially in PostgreSQL, one process per connection). In MySQL 8, SET PERSIST applies and keeps the value; also lower wait_timeout to close forgotten sessions. In PostgreSQL, changing max_connections requires a restart (sudo systemctl restart postgresql).

    sql
    -- MySQL 8
    SET PERSIST max_connections = 300;
    SET PERSIST wait_timeout = 600;
    
    -- PostgreSQL (restart required)
    ALTER SYSTEM SET max_connections = 200;

Did this fix work for you?

Confirm it in one click: it will rise for the next developers stuck on the same error.

Keep it from coming back

  • Monitor Threads_connected or the row count of pg_stat_activity, with an alert around 80% of max_connections.
  • Redo the connection budget math every time you add a server, a replica or a worker.
  • In PostgreSQL, set idle_in_transaction_session_timeout to cut forgotten transactions.

Frequently asked questions

What is the default value of max_connections?

151 in MySQL 8, 100 in PostgreSQL. Managed databases (RDS, Cloud SQL, Azure) often compute the limit from the instance RAM.

Is raising max_connections enough?

Rarely. Each connection costs memory, and a leak will end up filling the new limit too. First find who uses the connections, then shrink the pools or add a pooler.

With Laravel or PHP, do I need to close the connection myself?

Not for a web request: PHP closes it at the end of the request. The problem comes from the number of PHP-FPM workers, persistent connections (PDO::ATTR_PERSISTENT) or long-running workers; in the latter, DB::disconnect() frees the connection between two jobs.

Useful tools for this error

More Databases (SQL) errors

All Databases (SQL) errors →