MySQL "Too many connections" (error 1040): causes and fixes

MySQL error 1040 means every connection slot is taken. How to see who holds them, raise max_connections safely, and fix leaks and idle connections for good.

· 6 min read · By the Spot Downtime team

The message is ERROR 1040 (HY000): Too many connections. MySQL (and MariaDB) caps how many clients can be connected at the same time. When the cap is reached, the next client is refused. For a web app that usually means visitors see a 500 error, a blank page, or "Error establishing a database connection" on WordPress, while the web server itself is perfectly healthy.

Raising the limit is the quick fix, but it is rarely the real one. This post shows how to get back in, see what is using the connections, and stop it happening again.

Step 1: get a shell on the server

MySQL keeps one extra connection in reserve for an account with the CONNECTION_ADMIN or SUPER privilege, usually root. That is how you can log in when everyone else is locked out. If your app connects as root, it will use that slot and you will be locked out too, so give the app its own user.

bash
mysql -u root -p
mysql> SHOW VARIABLES LIKE 'max_connections';
mysql> SHOW STATUS LIKE 'Threads_connected';
mysql> SHOW STATUS LIKE 'Max_used_connections';

The default max_connections is 151. Max_used_connections is the high-water mark since the server started: if it equals max_connections, you have hit the limit at least once.

Step 2: see who is holding the connections

sql
-- Every connection and what it is doing
SHOW FULL PROCESSLIST;

-- Connections grouped by user, host and state
SELECT user, SUBSTRING_INDEX(host, ':', 1) AS client, command, COUNT(*) AS n
FROM information_schema.processlist
GROUP BY user, client, command
ORDER BY n DESC;

Two patterns account for most incidents:

  • Many connections in the Sleep command. The app opened them and is not using them. This is a connection leak, or a pool that is bigger than it needs to be.
  • Many connections running the same slow query. Queries pile up behind a lock or a missing index, each one holding a slot until it finishes. Look at the Time and State columns.

Step 3: raise the limit, carefully

You can change it without a restart:

sql
SET GLOBAL max_connections = 300;

That is lost on restart, so also set it in the configuration file:

ini
# /etc/mysql/my.cnf or /etc/mysql/conf.d/limits.cnf
[mysqld]
max_connections = 300

Each connection uses memory for its thread and per-session buffers, so a bigger number needs more RAM. A server that is already near its memory limit can be killed by the kernel after you raise this, which turns a partial outage into a full one. Check Linux out of memory if mysqld disappears after the change.

Step 4: remove idle connections

wait_timeout is how long MySQL keeps a non-interactive connection that is doing nothing. The default is 28800 seconds, 8 hours, which lets leaked connections pile up all day.

sql
SHOW VARIABLES LIKE 'wait_timeout';
SET GLOBAL wait_timeout = 300;

Pick a value longer than the idle time your app expects, and make sure the app reconnects cleanly when MySQL closes a connection. Otherwise you trade this error for "MySQL server has gone away".

Step 5: fix the cause in the application

Size the pool on purpose

Total possible connections is the pool size times the number of app processes. Ten app servers with a pool of 20 each is 200 connections before any background workers. Work out the sum and keep it under max_connections with room to spare.

PHP and WordPress

Each PHP-FPM worker opens its own connection, so pm.max_children is effectively a connection count. See PHP-FPM 502 and 504 errors for sizing it. Avoid persistent connections (mysqli with a p: prefix) unless you have counted them.

Always release connections

Close or return the connection in a finally block or with your framework's context manager. A request that throws an exception before the close call is the classic leak.

Fix the slow queries

Enable the slow query log and look at what holds connections open:

sql
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;

Then run EXPLAIN on the worst offenders. One missing index can use up every slot during a traffic peak.

Put a proxy in front

If many short-lived clients (serverless functions, for example) each open their own connection, a connection pooler such as ProxySQL multiplexes them onto a smaller number of real MySQL connections.

PostgreSQL has the same problem

The Postgres equivalent is FATAL: sorry, too many clients already, with max_connections defaulting to 100. The same steps apply: find idle connections in pg_stat_activity, size pools deliberately, and use PgBouncer for many short-lived clients.

Checklist

  1. Log in as an account that can use the reserved connection.
  2. Compare Max_used_connections with max_connections.
  3. Read the processlist: idle Sleep connections or a pile of identical slow queries?
  4. Raise max_connections only as far as memory allows, in the config file as well.
  5. Lower wait_timeout and fix leaks in the code.
  6. Add up pool sizes across all app processes.

Catch it before the limit is reached

This failure is gradual: connections creep up until the last slot goes. A website monitor on a page that queries the database sees the failure within a check interval, and it is confirmed from all three regions before you are alerted. Use a page or health endpoint that actually runs a query, because a cached page can look healthy while the database refuses connections. A server monitor on the database host shows memory and CPU trending the wrong way while you still have time to act.

Get new guides by email

Practical posts on monitoring, outages, error fixes and on-call, when they're published. No spam.

Unsubscribe from any email with one click. See our privacy policy.

Keep reading