max_connections Hell: The Anatomy of Connection Pool Exhaustion

It was 3:47 a.m. when my phone buzzed me awake. The monitoring system had kept it short and to the point: "API error rate 62%". I opened my laptop, and the logs were repeating a single line thousands of times: SQLSTATE[HY000] [1040] Too many connections. The strange part was that at 3:47 a.m. our traffic was a tenth of what it is during the day. How do you run out of connections when nobody is around? That night I learned that connection pool exhaustion is not a traffic disease; it is a latency disease. And latency can show up just fine in the middle of the night.

Finding the culprit took me two hours; telling the story will take five minutes. But let's go step by step, because the real value lies in the wrong hypotheses along the way.

Connection Math: The Calculation Everyone Thinks They Know

First, the groundwork: our architecture had 6 API servers, each running PHP-FPM with up to 80 workers. Every worker opens one MySQL connection per request. The ceiling math is simple: 6 × 80 = 480 potential connections, and max_connections was 500. On paper, it fits. But that calculation is static; in the real world, the critical variable is how long a connection stays open. Little's Law rules here too: concurrent connections = request rate × connection hold time per request. If your request rate stays flat but your queries start taking 2 seconds instead of 20 ms, your connection demand goes up 100-fold. The anatomy of pool exhaustion fits in one sentence: the connection count doesn't explode, the duration does.

In the static calculation, 480 connections fit under the 500 limit; per Little's Law, connection demand is request rate multiplied by hold time.
If queries slow down, connections run out even when the request rate stays flat.

A Parade of Wrong Hypotheses

First hypothesis: an attack or a traffic spike. I checked the Nginx logs; the request rate was normal, low even. Second hypothesis: a connection leak, with unclosed connections piling up. I dumped the SHOW PROCESSLIST output: 460 of the 500 connections were in the "Sleep" state, but their Time values were small, meaning the workers were holding their connections but leaving them idle. With a leak, the Time values would have stretched into hours. Third hypothesis: someone had broken wait_timeout. No, it was still at 28800 (an 8-hour default, by the way, which is a scandal of its own, but not the topic of that night).

The real clue was in the minority of PROCESSLIST that was "not Sleep": about 40 connections, all on the same query, had been "Waiting for table metadata lock" for minutes. I traced the metadata lock chain, and at the end of it sat an ALTER TABLE triggered by cron at 3:30 a.m.: an index-creation job a colleague had scheduled so it would "run at night when nobody's around." The ALTER was waiting for a long-running old reporting transaction to finish, and behind the ALTER, every new query touching that table had lined up. With no response coming back, the workers held their connections for minutes; FPM spawned new workers for new requests, and they asked for connections too. At 3:47 the 500 filled up. Not traffic, but a single lock chain: that is exactly what I mean by a latency disease.

The reporting transaction held up the ALTER TABLE, queries lined up behind it, workers held their connections and the 500 limit filled up.
The problem wasn't traffic; it was a single lock chain.

What We Did That Night and the Week After

The emergency response, in order: I killed the reporting transaction, the ALTER went through on its own, the queue drained in 90 seconds, and the error rate dropped to zero. By 4:20 a.m. everything was green. The real work happened the following week, because if this had happened once, it would happen again.

First, we put schema changes under a rule: every ALTER first sets lock_wait_timeout to 30 seconds before it runs (the default is one year! If it can't get the lock, it waits forever and grows a queue behind it), and if it can't get the lock, it gives up and retries. Second, we added query timeouts on the application side; no API query running longer than 30 seconds is allowed to hold a connection hostage. Waiting at the source of the queue is better than waiting in the pool.

Third, and the most structural: we put ProxySQL in between. FPM workers no longer connect to MySQL but to a local ProxySQL, which multiplexes a real pool of 120 connections on the back end. 480 front-end connections fold into 120 back-end connections, because a front-end connection sitting in "Sleep" has no need to occupy a back-end connection: while the worker is thinking between queries (building JSON on the PHP side, for example), the back-end connection is serving someone else. After we rolled it out, the peak Threads_connected value on the MySQL side dropped from 470 to 140. Same hardware, same traffic, three times the breathing room.

ProxySQL came with some bonus gifts, too. Because we could route queries with a rule table, splitting heavy report queries off to the replica and writes to the primary was done without touching application code. And the sweetest part: during a maintenance window where we had to restart the database, ProxySQL held the front-end connections for a few seconds and handed them over to new back-end connections; the application layer experienced the outage not as an error but as a single slow request.

Meanwhile, the FPM side got some budgeting discipline as well. Setting pm.max_children to "as much as the server's memory can handle" is a common reflex, but the real ceiling should be set by the concurrency the database can handle. We flipped the formula around: if the database can healthily carry 120 concurrent queries and 60 percent of requests touch the database, the total worker count across the whole cluster has to be budgeted accordingly. Extra workers aren't capacity; they just move the queue somewhere else. Instead of waiting in nginx, you wait on a database lock, and you occupy a connection while you're at it.

Lock timeout, query timeout, ProxySQL connection multiplexing and a worker budget based on the database were put in place.
Same hardware and traffic, three times the breathing room.

The Persistent Connection Myth and a Rundown of Small Tweaks

While I'm at it, let me make my position on PHP's persistent connections (the p: prefix, mysqli.allow_persistent) clear: in FPM, a persistent connection is not a pool. Each worker keeps its own connection until it dies; if you have 480 workers, you have 480 persistent connections, and all you save is the cost of opening them. On localhost, setting up a TCP connection takes around half a millisecond anyway; in exchange, a persistent connection's habit of passing a half-finished transaction or a changed session variable on to the next request produces oddities that take weeks to diagnose. Once, because of a SET time_zone from a previous request on a persistent connection, we sent some customers reports shifted by three hours. Since that day, persistent connections are banned on our team; anyone who wants a pool uses ProxySQL.

On the monitoring side, we added two indicators and wired both to alerts. The first is the utilization ratio: a warning if Threads_connected / max_connections exceeds 70 percent, so we hear about it while we're heading toward exhaustion, not at the moment it happens. The second is Threads_running: the number of queries actually executing concurrently. On our machine, once this value goes past 30, the latency curve gets steep; it is physically impossible for an 8-core database to "run" 300 queries at the same time; it just slows them all down through context switching. That is why raising max_connections is usually not a solution but a way to amplify the symptom: letting more people through the door just brings more spectators to the fire.

One more small footnote: that same week we also lowered wait_timeout from 28800 to 300. A connection kept in "Sleep" for eight hours does nobody any good; on top of that, when the firewall in between silently dropped an idle session, the application side only found out on the next query, with the infamous "MySQL server has gone away" error. A short timeout plus a single reconnect on error wiped out that phantom error at the root, too.

Let me repeat here the last sentence I wrote in the incident's root cause report: pool exhaustion is always the bill for an upper layer's sins, issued at the database. When the bill arrives, the place to look is not the connection count but whatever is holding the connections hostage: a slow query, a lock chain, a request stuck on an external service, or a well-intentioned ALTER scheduled for 3:30 a.m. If "Too many connections" keeps coming back from the dead in your system too, and you're tired of raising max_connections, write to us here; reading PROCESSLIST tells a more concrete future than reading tea leaves.