Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

MySQL: ERROR 1040 (HY000) Too many connections

The server is out of slots because pools are too large or leaking. Read the counters, size pools against replicas, then raise the limit.

~6 min readSQL
#MySQL#Connection Pool#Performance#Troubleshooting
A database gate with a queue of client plugs backed up outside, an amber full counter and a cyan pool tray

Introduction & Quick Summary

ERROR 1040 (HY000): Too many connections means the server has already handed out every slot in max_connections and refuses new sessions. The database is usually healthy: it is doing exactly what it was configured to do, with a ceiling that no longer matches the number of clients. Two things cause that mismatch, and they look identical from the client side:

  • The application holds more connections than it needs. A pool sized at 20 per instance across 20 pods is 400 connections before anyone opens a page, and one leaked connection per request adds more over time.
  • The server limit is lower than the deployment assumes. The default is 151, a managed instance may sit on a small parameter group, and a failover to a replica with different settings resets the ceiling.
ObservationReadingNext step
Threads_connected at max_connectionsCeiling reachedFind who holds them
Threads_running much lower than connectedConnections idlePool too large or leak
Max_used_connections near the limitSustained pressureResize the pool before raising the limit
Impossible to log in as rootSlots exhausted, no admin reservationRaise the limit via console, then fix access
Errors start after a deployNew pod count or pool defaultPool size × replicas versus limit

Core Mechanics, Signatures & Reproducible Setup

MySQL allocates one thread per connection, and each thread costs memory: a thread stack, a buffer set, and per-session allocations that grow with the queries it runs. max_connections is therefore a memory ceiling as much as a count ceiling. Raising it to 5,000 on a small instance trades a clean error for an out-of-memory kill, which is worse because it takes the whole server down.

Three limits stack. max_connections is the global cap; max_user_connections caps one account; and the CONNECTION_ADMIN privilege lets an account open one session past the global limit in MySQL 8, which is how an operator gets in when the application has consumed everything. Managed services add their own parameter group layer on top.

The error reproduces with a low ceiling and a handful of clients:

sql
SET GLOBAL max_connections = 10; SHOW VARIABLES LIKE 'max_connections';
bash
for i in $(seq 1 12); do mysql -h 127.0.0.1 -u app -p"$PASS" app -e 'SELECT SLEEP(60)' & done wait

The eleventh and twelfth sessions receive ERROR 1040 (HY000): Too many connections, and the first ten stay open for a minute, holding the slots.

Key Comparison Table

The diagnosis starts with the two status counters, because they separate a leak from a sizing problem.

Variable / statusScopeTypical valueWhat it tells you
max_connectionsServer151 defaultHard ceiling
max_user_connectionsAccount0 (unlimited)Per-user ceiling
Threads_connectedRuntimeCurrentSlots in use right now
Max_used_connectionsRuntime peakCurrentHigh-water mark since start
wait_timeoutSession28800 sIdle time before the server closes

Pool sizing is arithmetic, not preference. The safe shape for a fleet is:

DeploymentPool per instanceInstancesTotalLimit needed
4 pods, pool 1010440151 is ample
20 pods, pool 202020400Raise to 500+ or shrink pools
2 workers, pool 50502100Leave headroom for admin

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Find who is holding the connections

PROCESSLIST shows command state and elapsed time, which is enough to spot idle-in-transaction sessions that a pool will never reuse:

SELECT id, user, host, db, command, time, state, LEFT(info, 60) AS query FROM information_schema.PROCESSLIST WHERE command <> 'Sleep' ORDER BY time DESC LIMIT 20; SELECT COUNT(*) AS connected, SUM(command = 'Sleep') AS sleeping FROM information_schema.PROCESSLIST;

A high sleeping count with a low Threads_running is the signature of a pool that is too large or a client that never returns connections. A high count of Sleep sessions with long time values and an open transaction means wait_timeout is not saving you, because the session is technically idle but inside a transaction.

Kill the idle sessions that should not exist

Killing is a mitigation, not a fix, but it buys time during an incident. Target sessions that have been idle outside a transaction:

SELECT id, user, host, time FROM information_schema.PROCESSLIST WHERE command = 'Sleep' AND time > 600; KILL 4211;

Do not loop KILL over Threads_connected: a client that reconnects immediately will refill the slots and you end up in a kill-reconnect cycle. Fix the pool or raise the limit, then let the connections age out naturally.

Size the pool from the database's perspective

Most pools default to 10 and most teams multiply that by the replica count without checking. The formula that keeps you under the ceiling is:

text
max_connections >= (instances × pool_max) + admin_headroom + migration_jobs

In code, set the pool explicitly rather than accepting a framework default, and set a connection timeout so saturation fails fast instead of queueing forever:

ts
import mysql from "mysql2/promise"; export const pool = mysql.createPool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, waitForConnections: true, connectionLimit: 10, maxIdle: 10, idleTimeout: 60_000, queueLimit: 50, connectTimeout: 5_000, });

queueLimit is what prevents an unbounded queue of waiting requests from turning a slow database into an unresponsive API. When the queue is full, the request fails with an error you can map to a 503 instead of hanging.

Raise the limit without breaking memory

When the pool math genuinely needs more slots, raise the ceiling in steps and watch memory. On a self-managed server:

sql
SET GLOBAL max_connections = 500; -- persistent across restarts: -- /etc/mysql/mysql.conf.d/mysqld.cnf -- [mysqld] -- max_connections = 500

On RDS or Aurora the change goes through a parameter group and needs a reboot for a static parameter:

bash
aws rds modify-db-parameter-group \ --db-parameter-group-name app-mysql8 \ --parameters "ParameterName=max_connections,ParameterValue=500,ApplyMethod=pending-reboot"

Check the instance's memory before doubling the number: each connection can cost a few hundred KB to several MB depending on sort_buffer_size and join_buffer_size, and those are per-session, not global.

Leaks in long-lived processes

In Node, Go, and Python, a missing release or defer rows.Close() does not always show as an error until the pool is empty and every request queues. The pattern that avoids it is a single acquire per unit of work:

go
row := db.QueryRowContext(ctx, "SELECT status FROM orders WHERE id = ?", id) var status string if err := row.Scan(&status); err != nil { return err }

QueryRowContext releases its connection when Scan finishes. The leak appears when Query is used and rows.Close() is skipped on an early return; a linter such as sqlclosecheck catches it before production does.

Common Compilation/Runtime Mistakes & Version Gotchas

Raising max_connections as the first response. If the pool is 40 and the limit is 151, the cause is a leak, not the ceiling. The error returns within hours at a higher limit.

Setting wait_timeout very low to force cleanup. A pool that keeps idle connections will reconnect constantly, which adds handshake load and can exhaust max_connect_errors. Keep the server timeout above the pool's idle timeout.

Forgetting max_user_connections. A single account serving several services hits the per-user limit first, and the message is the same 1040. Check SHOW VARIABLES LIKE 'max_user_connections' before blaming the global ceiling.

Assuming replicas share the setting. A failover to a replica with a smaller parameter group brings the error back at the worst moment. Apply parameter groups to every member of the cluster.

Leaving the pool unbounded in serverless. Each function instance creates its own pool, so a traffic spike creates hundreds of connections at once. Use a proxy such as ProxySQL or the provider's pooler for serverless workloads, or connect over HTTP where the platform offers it.

Confusing 1040 with 1203. 1203 is User already has more than 'max_user_connections' active connections, a per-account limit; 1040 is the global one. The fix differs: one is pool sizing per service, the other is the server ceiling.

Version behaviour. MySQL 8 reserves one connection for accounts with CONNECTION_ADMIN, so an admin login can still succeed at the limit. MySQL 5.7 does not, which is why older incidents read as "root cannot log in either".

When you are working through an incident, run the diagnostic queries through the SQL formatter so the ones you paste into a runbook are readable, and keep the pool settings in the environment variable reference format that your deployment templates already use.

Official references: Too many connections and the max_connections system variable.

Official references

primary documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.