Fix "ERROR 1040: Too many connections" (MySQL) and "too many clients already" (PostgreSQL)
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"
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.
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
- 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, exceedsmax_connections. Same effect with serverless functions scaling out. - Connection leaks: code takes a connection without giving it back (
pool.connect()withoutclient.release()in Node, cursors never closed in Python). - Oversized pools: a pool of 20 per instance × 10 replicas = 200 connections, above MySQL’s default 151.
- Idle connections never closed: persistent connections, an 8-hour
wait_timeoutthat letsSleepsessions pile up. - Slow queries or locks: connections pile up waiting for a blocked query, until they hit the limit.
Step-by-step fix
-
MySQL: measure who holds the connections
Compare
Threads_connectedandMax_used_connectionswith the limit, then group sessions by user, host and state. ManySleepsessions from one host point to a pool or persistent connections. If you can no longer connect, use an account withCONNECTION_ADMIN: it gets the reserved slot.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; -
PostgreSQL: count the sessions
pg_stat_activityshows each connection with its application and state. Manyidlesessions mean oversized pools;idle in transactionpoints to code that opens a transaction without ending it.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; -
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
Idof aSleeprow with a largeTimefromSHOW PROCESSLIST. This is a band-aid: the real fix is in the next steps.-- 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'; -
Size the pools and fix leaks
Do the math: instances × (pool size or
pm.max_children) + workers + admin margin must stay belowmax_connections. Shrink pools (Prisma:?connection_limit=5in the URL), and always give the connection back to the pool, even on error.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(); } -
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
transactionmode, avoid server-side prepared statements and sessionSETif your version or driver does not support them.[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 -
Raise the limit if memory allows
Each connection uses RAM (especially in PostgreSQL, one process per connection). In MySQL 8,
SET PERSISTapplies and keeps the value; also lowerwait_timeoutto close forgotten sessions. In PostgreSQL, changingmax_connectionsrequires a restart (sudo systemctl restart postgresql).-- 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_connectedor the row count ofpg_stat_activity, with an alert around 80% ofmax_connections. - Redo the connection budget math every time you add a server, a replica or a worker.
- In PostgreSQL, set
idle_in_transaction_session_timeoutto 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
- Fix "ERROR 1045 (28000): Access denied for user 'root'@'localhost'" (MySQL, MariaDB)
- Fix "ERROR 1062 (23000): Duplicate entry for key" (MySQL, MariaDB, PostgreSQL)
- Fix "Deadlock found when trying to get lock; try restarting transaction" (MySQL, PostgreSQL)
- Fix FATAL: password authentication failed for user "postgres" (PostgreSQL)
- Fix "ERROR 2006 (HY000): MySQL server has gone away"
- Fix "ERROR 1054 (42S22): Unknown column in 'field list'" (MySQL)
- Fix "ERROR: relation "users" does not exist" (PostgreSQL)