MySQL Too Many Connections Error: Causes and a Permanent Fix

Short answer
What does the MySQL too many connections error mean?
The MySQL too many connections error means the number of open client connections has reached the limit set by the max_connections variable, so the server refuses new connection attempts. In other words, the database has not crashed; the door is simply full. Until existing connections close or the limit rises, your application cannot open a new session.
Your site suddenly stops loading and the log says "Too many connections." That message means your MySQL server has hit the maximum number of client connections it will accept at the same time. The short-term job is to get the server answering again; the permanent fix is to find out who holds those connections and why. In this guide we walk through the mysql too many connections error in two stages: a five-minute emergency routine, then the architectural changes that stop it from coming back.
The official MySQL manual describes it plainly: all available connections are in use by other clients. It also adds a detail that matters during an incident. The server actually permits max_connections + 1 connections, and that one extra slot is reserved for accounts with the CONNECTION_ADMIN privilege (or the deprecated SUPER privilege). As a result, an administrator can still log in and diagnose the problem when ordinary clients have filled every slot. You can read the details in the MySQL Too many connections reference.
So your first reflex should not be "let's raise the limit." The limit is usually the symptom, not the disease.
Where do you see the error, and what does it look like?
The error looks different depending on the layer that catches it. For example, a PHP application throws a connection exception, while a WordPress site usually shows a generic database connection message. Our guide to the WordPress error establishing a database connection helps you tell that case apart from wrong credentials or a stopped server.
- Application logs: Laravel, Symfony or Node.js logs show the phrase "Too many connections" next to a connection failure.
- Web server: Visitors often get a blank page or a generic 500 error.
- Command line: The mysql client returns the same message when you try to connect.
- Monitoring: The connections graph flattens against a ceiling and stays there.
That said, seeing the message once is not enough. Write down when it started, how much traffic you had and whether a deploy or campaign happened just before; half of the diagnosis lives in that timeline.
What should you do in the first five minutes?
When you are under pressure, the goal is to bring the site back without destroying the evidence. Therefore, before you restart anything, follow this order:
- Connect with an administrator account. The reserved extra connection usually makes this possible.
- Run
SHOW PROCESSLIST;and save the output to a file. - Count connections by user, by database and by state (Sleep, Query, Locked).
- If one long query blocks everything else, consider killing only that query.
- Raise the limit temporarily if you must, but do not treat that as the fix.
- Finally, check web server and PHP process logs for a traffic spike in the same minute.
In short, a saved process list from the first five minutes will save you more time than anything else later. If you restart the server first, that snapshot disappears, and you start from zero the next time the error returns.
How do you check and change max_connections?
You can read the current limit with SHOW VARIABLES LIKE 'max_connections';. The default can differ by version and distribution, so read the value on your own server instead of trusting a number from memory, and confirm the current default on the MySQL server system variables page.
The manual shows two routes. SET GLOBAL max_connections = ... changes the value immediately, but the server forgets it after a restart. To make it stick, you use SET PERSIST or write the value into the configuration file. The value of 500 in the manual is only an example, not a recommendation.
So how high should you go? Every connection uses memory. Consequently, if you push the limit beyond what your RAM can carry, you trade "too many connections" for memory exhaustion and swapping. We cover that relationship together with buffer settings in our guide on installing MySQL on Ubuntu and tuning performance. Set the limit only after you understand why connections pile up, and base it on the observed peak plus a sensible margin.
How should you think about memory before raising the limit?
Each connection uses its own thread and its own per-connection buffers. Some of those buffers appear only during operations such as sorting or joins, so the real cost of a connection depends on the queries it runs. For that reason, we do not quote a fixed "memory per connection" number.
Instead, we suggest a safe order of thinking:
- First, subtract the database's fixed memory (the buffer pool is usually the largest share) from total RAM.
- Next, leave room for the web server, PHP workers and any other service on the same machine.
- Then compare the remaining room with the number of concurrent connections you see at peak.
- Finally, watch swap usage; if swap grows, the limit is already too high.
For example, if the web server and the database share one machine, a higher limit also squeezes the memory your PHP workers need. In that situation, moving the database to its own server can be a healthier decision than raising the number.
Also keep in mind that the operating system's open file limit can cap connections. If you raise the limit and the effective value does not match, check the server log for warnings and the related notes in the official manual.
What does Max_used_connections tell you?
The Max_used_connections status variable shows the highest number of connections open at the same time since the server started. You read it with SHOW GLOBAL STATUS LIKE 'Max_used_connections'; and put it next to max_connections.
- If the peak equals the limit: The server filled up at least once; the error log should confirm it.
- Peak far below the limit: The problem may come from another server, a per-user limit or the application pool.
- If it hits the ceiling at the same hour every day: Suspect a scheduled job, a backup or a reporting query.
Also note that a restart resets this value. Without a regular monitoring record, you lose past peaks. For instance, a simple job that logs the connection count every five minutes gives you a real traffic profile within a few days.
What actually causes the MySQL too many connections error?
In our field experience, this error is almost never just "the limit is too low." The table below links what you see in the process list to the likely cause:
| What the process list shows | Likely cause | Direction of the permanent fix |
|---|---|---|
| Many connections in Sleep | Persistent or unclosed connections | Fix the connection lifecycle, lower idle timeouts |
| Few connections, very long queries | Slow queries, missing indexes | Query and index optimization |
| Rows waiting for locks | Long transactions and table locks | Shorten transactions, fix lock order |
| Short queries, very high concurrency | Bot traffic or a sudden campaign spike | Caching, rate limiting, bot filtering |
| Connections from a single user | A faulty cron job or queue worker | Limit job concurrency |
| App server count just increased | Pool sizes add up past the limit | Size pools against a total budget |
Do not lock onto a single row, because real incidents often combine two causes. For example, a slow query holds connections open while a crawler fills the remaining slots.
You can run most of these checks yourself. However, if the cause sits deep in the application code, or you inherited the software from another team, the technical audit step in custom software development is an orderly way to inspect connection handling layer by layer.
Why do Sleep connections pile up?
Sleep means the connection is open but not running a query right now. A few sleeping connections are normal. However, if most of the list sleeps, your application does not release connections after it finishes its work.
The three most common patterns look like this:
- The app opens a new connection on every request and skips the close step when an error occurs.
- Persistent connections are on, and every PHP worker holds its own connection indefinitely.
- A long-running process, such as a queue worker or websocket server, keeps a connection it no longer uses.
This is where wait_timeout comes in. It sets how long the server waits before closing an idle noninteractive connection, while interactive_timeout covers interactive clients such as the mysql command-line tool. A lower value reduces the pile-up. Still, it is a bandage, because the real bug is code that never lets go. Check the current defaults on the official variables page.
Do persistent connections make the problem worse?
Yes, when you size them badly. A persistent connection lets a PHP process keep the same database connection between requests instead of reconnecting. On paper, it cuts connection setup cost; in practice, it ties your connection count to the number of processes rather than the number of requests.
Example calculation: say your PHP-FPM pool allows up to 60 workers and two sites run on the same machine. With persistent connections, if each worker holds one connection, 120 connections can stay open even at low traffic. Add cron jobs and an admin panel, and you approach the limit quickly. These numbers only illustrate the logic.
So before you enable persistent connections, add up the maximum worker count in your process manager, every application that shares the database, and the limit itself. On shared hosting you usually do not control those numbers, so keeping persistent connections off is the safer choice there.
How do slow queries eat up connections?
A connection stays busy until its query finishes. If a query takes several seconds instead of a few milliseconds, the same traffic needs many more concurrent connections. As a result, one missing index can trigger the mysql too many connections error without anyone touching the limit.
- Turn on the slow query log and choose a threshold.
- Rank the queries that appear most often and that consume the most total time.
- Inspect them with
EXPLAINand find steps that scan the full table. - Add the missing index, narrow queries that pull unneeded columns, and fix pagination.
- After each change, compare the connections graph for the same time window.
Also, do not forget locks. A long transaction that holds a row lock makes other connections wait, and they burn a connection while they wait. To separate CPU, disk and RAM causes of general slowness, follow the sequence in our guide server is slow: what is causing it.
Can bot traffic or a sudden spike trigger the error?
Yes, especially on dynamic pages without caching. If every visit hits the database, an aggressive crawler can open hundreds of concurrent requests within minutes, even without bad intent. The same thing happens with real visitors after a newsletter, a viral social post or a TV spot.
To tell them apart, look at your access logs. During the error minute, which IP ranges, which user agents and which URLs show up? Search, filter and cart URLs, which you cannot cache, are usually the first suspects. To read logs systematically, use the method from our article on server log file analysis.
- Keep anonymous visitors away from the database with a page cache.
- Rate-limit search and filter URLs.
- Block brute-force login attempts with a tool such as Fail2ban.
That way, the database only handles requests that truly need to be dynamic.
Is connection pooling the permanent fix?
Connection pooling means the application opens a fixed set of connections up front and shares them across requests. Set up well, it decouples your connection count from traffic swings: instead of hitting the limit, requests briefly wait for a free connection in the pool.
However, a pool is not magic. In long-running runtimes such as Java, Go and Node.js, the pool lives inside the app, and every app instance opens its own pool. For instance, eight instances with a pool of 20 each ask for 160 connections in total. In this example calculation, adding one more server can push you over the budget again.
In the classic PHP model, every request is short-lived, so pooling usually happens outside the app, in a proxy layer in front of the database. Whatever tool you pick, the rule stays the same: the sum of all pools must stay below max_connections minus room for administrators and scheduled jobs.
Which code mistakes leak connections?
A connection leak happens when code opens a connection and does not close it on every path. The normal path looks fine; the leak appears on errors, timeouts and early returns. In code review, look for these patterns:
- Scripts that open a new connection inside a loop.
- Error handlers that never reach the cleanup step.
- Transactions that start but never commit or roll back.
- Queue workers that reconnect for each job without releasing the old connection.
- Plugins or modules that create a second database connection object in the same request.
Closing these holes for good sometimes takes an architectural change, not a one-line patch. If you do not have your own team, or you inherited the code from a previous vendor, an independent technical audit of the code is a sensible next step at this point. We also explain why these problems grow over time in our article on technical debt in software projects.
What is the per-user connection limit for?
max_user_connections caps how many connections a single account can hold at once, separately from the global max_connections limit. It is useful for stopping one application's bug from locking the whole server.
Example scenario: an online store, a blog and a reporting tool share one MySQL server. A runaway loop in the reporting tool burns every connection, and the store goes down too. If each app has its own database user with its own cap, the bug only takes out the reporting tool.
To get there, stop sharing one user across applications. On shared hosting, the provider may already enforce a per-account cap; in that case you see a similar message about the user limit rather than the global one. If you manage users through a control panel, our guide to creating a MySQL database and user privileges in cPanel makes this easier.
How do you prevent mysql too many connections on WordPress and Laravel?
Both platforms open a connection per request by default and close it when the request ends. Therefore, the problem usually comes from what you add on top, not from the platform itself.
On WordPress, start with plugins. Heavy statistics, search or related-posts plugins can run many queries on every page view. Also, without a page cache, every anonymous visit reaches the database. If you also see the critical error screen, the plugin elimination method in our guide to "There has been a critical error on this website" works here as well.
On Laravel, focus on three points:
- Check how many queue workers you run and how each one handles its connection.
- Replace queries that load relations inside a loop (the N+1 pattern) with eager loading.
- Consider moving session and cache drivers off the database, so each request runs fewer extra queries.
In other words, on both platforms you shrink the query count first and the connection lifetime second. Tuning the limit still comes last.
Is the mysql too many connections error different on MariaDB?
The core logic is the same. MariaDB uses a limit with the same name and returns a similar error when it fills up. That said, the two systems have drifted apart over time, so the admin connection, the thread pool and some variables may behave differently.
Before you apply details from the MySQL manual to a MariaDB server, read the official documentation for your exact version. In particular, check the reserved admin connection and thread pool settings, because they decide whether you can get in during an emergency.
If you are not sure which system you run, query the version string. Some shared hosts and distributions ship MariaDB under the "MySQL" label. We compare the two and the migration decision in MariaDB vs MySQL: differences and which to choose.
What does a step-by-step permanent fix look like?
Once the emergency is over, follow this order. The order matters, because tuning without measuring only postpones the problem.
- Measure: Record connection counts, Max_used_connections and the process list for several days.
- Classify: Use the diagnosis table to find the dominant cause: Sleep, slow queries, locks or traffic.
- Fix the code: Close connection leaks, shorten transactions and tame faulty jobs.
- Speed up queries: Index and simplify the top entries in the slow query log.
- Filter traffic: Cut database load with caching, rate limits and bot filtering.
- Size the pools: Treat the total of all application pools as a budget.
- Tune the limit last: Persist max_connections and timeouts based on the observed peak and your RAM.
- Add alerts: Get notified when connection usage crosses a set share of the limit.
When you follow this plan, the mysql too many connections error often disappears without any change to the limit at all.
A realistic example: what happened on campaign night?
Example scenario: a mid-sized online store sends a discount email in the evening. Half an hour later, checkout starts failing. The team raises the limit first; the site comes back for a few minutes, then locks up again.
The saved process list shows three things. First, most connections sleep, and all of them belong to the same application user. Second, a few queries have locked the stock table and have been running for a long time. Third, a heavy crawler hits the category filter pages in the same minute.
The permanent fix has four parts. The team shortens the stock update transaction and adds the missing index. Next, they switch off persistent connections and lower the idle timeout. Then they put caching and a rate limit on filter pages. Last, they adjust the limit modestly based on the observed peak. This is not a client case; it is an example scenario built from components we see often.
The lesson: raising the limit did not remove the error, it only delayed it by a few minutes. Real progress started the moment the team saved the process list, because that record showed three causes at work at once. In addition, a short load test on the filter pages before the send would likely have exposed the lockup early.
How does the fix differ on shared hosting, a VPS and a managed database?
What you can change depends on your environment, so the order of work changes too.
| Environment | What you can change | First move |
|---|---|---|
| Shared hosting | Usually only application code and plugins | Turn off persistent connections, add caching, ask the host for the account cap |
| VPS or dedicated server | MySQL config, PHP-FPM, web server | Measure, then tune timeouts, pools and the limit together |
| Managed database service | Only the parameters the provider exposes | Read the provider's connection limit, size app pools to match |
| Containers | Database settings and replica counts | Recalculate total pool size whenever replicas grow |
If you are choosing between a VPS and a cloud server, our comparison of VPS vs cloud server vs VDS helps you understand resource limits. For containers, compare your setup with our guide to PostgreSQL and MySQL in Docker.
What are the most common mistakes with this error?
Teams that hit this error repeatedly tend to make the same moves:
- Setting the limit absurdly high: The error vanishes and memory exhaustion takes its place.
- Restarting before saving evidence: The process list and the peak value disappear.
- Giving every app the same user: One faulty job stops everyone.
- Granting admin privileges to the app user: The manual advises reserving the extra connection for administrators; otherwise the app burns it too and you cannot get in.
- Forgetting to multiply pool size by server count: Horizontal scaling silently breaks the budget.
- Running backups and reports at peak hours: Long locks grow the queue.
Your backup method also affects lock time. We cover that separately in our database backup and restore guide.
What should you monitor so the error does not return?
The final piece of a permanent fix is visibility. If you want to see the next peak before your users do, track these signals:
- Current connections and their share of max_connections.
- The daily trend of Max_used_connections.
- The number of queries landing in the slow query log.
- Status counters that show refused connection attempts.
- Pool wait time on the application side.
Knowing how to read server load also helps you separate a database problem from a CPU problem; our article on what load average means explains it. However, if you set the alert threshold too low, the team learns to ignore notifications and misses the real one. So set it based on your normal observed peak.
What if you cannot fix it on your own?
If you measured, reviewed the queries and tuned the settings, yet the mysql too many connections error keeps coming back, the problem most likely lives in the application architecture. At that point, outside help moves faster than trying the same setting with different values.
When Talha Aslan and team take over existing software, we first map the risks through a technical audit, then modernize it module by module. After launch, we run updates, monitoring, backups and bug fixes under a written maintenance plan. We build with OWASP-based security requirements and automated tests, and the repository and cloud accounts stay in your name. If you want connection handling, queues and the integration layer fixed for good, you can review the scope of our software development services.
We do not promise timelines or outcomes up front; we look at the code and the measurements first, then put the scope in writing.



