MySQL "Error 1040: Too many connections"

max_connections (often 151 by default!) is exhausted. Emergency: raise it or kill sleepers. Durable: connection pooling and fixing leaks.

What you'll see

Root causes

Default max_connections far too low for real apps

151 is the MySQL default; a few app servers each with 100-connection pools will exhaust it instantly. SHOW VARIABLES LIKE 'max_connections'; SHOW STATUS LIKE 'Threads_connected';

Connection leaks or missing pooling

Apps opening a connection per request without closing, or long-running sleepers: SHOW PROCESSLIST with hundreds of 'Sleep' rows, mostly from one host.

Fix it

  1. See who holds connections
    SHOW PROCESSLIST;   -- or: SELECT user, host, db, COUNT(*) FROM information_schema.processlist GROUP BY user, host, db ORDER BY 4 DESC;
  2. Emergency: kill pooled sleepers or raise the ceiling
    KILL <id>;   -- for confirmed-idle sleepers ; SET GLOBAL max_connections = 300;   -- takes effect immediately, resets on restart
  3. Persist the tuned value
    # my.cnf [mysqld]: max_connections = 300   -- and budget: each connection ≈ thread stack + sort buffers, check RAM headroom
  4. Durable: put a pooler in front
    # ProxySQL or app-level pools sized ~ (cores*2)+spindles; the pool's max must be < mysql's max_connections minus admin headroom
  5. Shorten idle timeouts for leaky apps you can't fix today
    SET GLOBAL wait_timeout = 120; SET GLOBAL interactive_timeout = 120;   -- sleepers get reaped sooner

Field note

Scale max_connections with RAM: thousands of threads = tens of GB of hidden allocations. Pooling beats a bigger number. Cloud-managed MySQL: check the plan's cap — Provider-managed instances often refuse values above a threshold.

Common questions

What's a safe max_connections?

Depends on RAM and per-connection buffers; a common sane range is 300-1000 with pooling in front. Beyond ~1000 raw app connections, you want ProxySQL rather than a bigger ceiling.

Why do 'Sleep' connections pile up?

Clients open a connection and idle past what they need (no pool eviction, no close). Wait_timeout eventually reaps them — until then each occupies a max_connections slot. Fix the app's pool, or shorten wait_timeout.

Ship it right the first time

Our most-documented failures, packaged as ready-to-ship starter kits: Docker, Kubernetes, and Terraform.

Browse the template store →

One-time. Yours to modify. Instant download from the NinjaOps template store.