VPS Tutorials
Fix MySQL 1040 Too Many Connections on a VPS: Pools and Limits (2026)
Recover administrative access, identify connection owners, budget every application pool and adjust MySQL limits only with memory and workload evidence.

When a site reports ERROR 1040 (HY000): Too many connections, APIs cannot reach MySQL and even administration tools fail to connect, ordinary client slots may be exhausted. The VPS is not necessarily too small: extra application processes, multiplied connection pools, unreturned connections and slow queries can all create the same failure.
This guide uses MySQL 8.4 as its main reference. Restore administrative access, identify who holds the connections, then adjust application pools and database capacity. For MySQL 8.0, consult that version's documentation. MariaDB differs in privileges, system tables and persistent configuration; do not copy MySQL-specific statements unchanged.
| Error or symptom | Investigate |
|---|---|
MySQL 1040 Too many connections | Ordinary server connection capacity exhausted |
Too many user connections or account resource-limit errors | Per-account capacity, not necessarily global max_connections |
Access denied or 1045 | Account, password and authentication matching |
2003, Connection refused or timeout | Service, address, listener and network |
Application errors such as QueuePool limit ... timeout | Pool wait timeout; server connections may still be available |
Do not increase max_connections simply because the application cannot connect. For network/login failures use the MySQL/MariaDB connection guide; for 1040 see MySQL's Too many connections documentation.
Pause confirmed nonessential imports, reports, queue consumers or a faulty application instance. Bound retries and use backoff; immediate retries from every request can create a connection storm.
Keep an existing administration session open. Avoid opening several more. Connect locally with an established administrator account and enter the password at the prompt:
mysql --connect-timeout=5 -u db_admin -p
Replace the example db_admin account and use the correct socket, host and authentication method. sudo mysql does not provide passwordless access on every installation. For an existing Compose deployment:
docker compose exec mysql mysql --connect-timeout=5 -u root -p
Replace mysql with the actual service. Running the client inside the container avoids unrelated network issues; it does not bypass the connection limit.
MySQL normally reserves one connection beyond the ordinary limit for an account with CONNECTION_ADMIN. This is one shared reserved slot, not one per administrator. If occupied, another window may still fail. Arrange restricted administration privileges and any dedicated management interface in advance; do not grant application accounts a way around limits or expose port 3306 publicly.
If access remains unavailable, reduce confirmed application traffic/processes so connections can close. Consider restarting MySQL only after assessing impact, preserving evidence and planning recovery. It disconnects all clients, loses some evidence and may trigger simultaneous reconnects that reproduce the failure.
First confirm the instance:
SELECT VERSION(), @@hostname, @@port, CURRENT_USER(), CONNECTION_ID();
SHOW GLOBAL VARIABLES
WHERE Variable_name IN (
'max_connections', 'max_user_connections',
'wait_timeout', 'interactive_timeout'
);
SHOW GLOBAL STATUS
WHERE Variable_name IN (
'Threads_connected', 'Threads_running',
'Max_used_connections', 'Connection_errors_max_connections',
'Connections', 'Uptime'
);
Sample through the same management connection rather than opening one for each measurement:
Threads_connected: current open connections.Threads_running: non-sleeping threads, not a CPU percentage.Max_used_connections: connection high-water mark, not the current count.Connection_errors_max_connections: connections refused at the limit; watch its increase during the observation interval.Connections: cumulative connection attempts; use time differences to derive a rate.
Record time and Uptime, since restarts/statistics resets change the baseline. A normal snapshot after traffic subsides cannot disprove an earlier 1040. See status variable definitions.
In MySQL 8.4, query Performance Schema, grouping by account/state before inspecting longer sessions:
SELECT USER, COMMAND, COUNT(*) AS connection_count,
MAX(TIME) AS longest_state_seconds
FROM performance_schema.processlist
GROUP BY USER, COMMAND
ORDER BY connection_count DESC;
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE
FROM performance_schema.processlist
ORDER BY TIME DESC
LIMIT 50;
Correlate account, source address, application logs and deployment time. HOST often includes a client port; different ports can belong to the same application. Sorting by TIME alone does not identify the root cause.
Seeing other accounts normally requires appropriate privileges. Unavailable tables or incomplete monitoring can produce an incomplete list. See processlist visibility and structure.
Sleep means the session is not executing a statement. Pools intentionally keep idle sessions. Check:
- Whether counts match replicas, processes and pool capacity.
- Whether requests return connections for reuse or planned retirement.
- Whether each request/task creates a new pool.
- Whether exceptions or cancellation leave connections borrowed or transactions open.
An idle session can still hold a transaction. Inspect InnoDB transactions:
SELECT trx_mysql_thread_id, trx_started, trx_state
FROM information_schema.innodb_trx
ORDER BY trx_started;
Match trx_mysql_thread_id to the connection ID. An open transaction is not automatic permission to terminate it: investigate business activity and lock waits. Long transactions can occupy slots and block other requests, amplifying both latency and connection pressure.
First control the application producing them. These IDs are examples; replace them with freshly verified targets:
KILL CONNECTION 12345;
KILL CONNECTION closes the connection and affects its work; uncommitted transactions may roll back, potentially slowly. KILL QUERY stops only the statement and retains the connection, so it may not free a slot. See KILL behavior and privileges.
Do not kill every session older than an arbitrary Sleep threshold, or interrupt replication, backups, administrators and legitimate pools. If the application reconnects immediately, KILL merely clears the list briefly.
A setting of pool_size=10 does not mean the whole service uses at most ten connections. Each replica may run multiple processes with separate pools and optional overflow.
For independent per-process pools, budget replicas × processes per replica × maximum pool capacity, then add queues, scheduled tasks, administration and other services. For bounded SQLAlchemy QueuePool, concurrent checkouts depend on pool_size + max_overflow; see the pooling documentation. This is a hypothetical budget, not a measured site:
| Source | Potential connections |
|---|---|
| API: 2 replicas × 4 processes × (10 pooled + 10 overflow) | 160 |
| Background jobs | 20 |
| Other sites and scheduled jobs | 10 |
| Administration and monitoring reserve | 10 |
| Total | 200 |
An ordinary limit of 151 could be exceeded. This is potential capacity: pools need not open every connection at startup. Compare it with observations.
Reduce unnecessary pool capacity, overflow and worker concurrency according to demand and database throughput. Preserve administration headroom. Ensure release on success, exceptions and cancellation, timely commit/rollback, and pool initialization at the correct process lifecycle. Recalculate when adding replicas/workers: rolling deployments temporarily run old and new instances together; coordinated warmups or restarts create bursts.
If application use is reasonable and the database has memory/processing headroom, a moderate increase may be appropriate. In MySQL 8.4, max_connections is a dynamic global variable; system resources can affect the effective value. See the system variable reference.
Check host memory and, where applicable, container limits:
free -h
vmstat 1 5
docker stats --no-stream
Run the final command only for Docker. Host free memory can exceed a container's allowance. Per-connection memory varies with query buffers, temporary tables and workload. Setting 1000 blindly can turn 1040 into OOM; see MySQL Docker OOM troubleshooting.
Here, 200 is a syntax example, not a recommendation. Record the original value and select a limit from your actual budget:
SET @incident_old_max_connections = @@GLOBAL.max_connections;
SELECT @incident_old_max_connections;
SET GLOBAL max_connections = 200;
SELECT @@GLOBAL.max_connections;
Appropriate administration privileges are required. SET GLOBAL changes the running value without a restart but usually does not persist it. Change one key limit at a time rather than simultaneously retuning memory.
To roll back within the same session:
SET GLOBAL max_connections = @incident_old_max_connections;
The session variable @incident_old_max_connections disappears on disconnect, so record the original number outside that session too. On reconnect, restore the recorded number explicitly. Lowering the limit does not clean up existing sessions; assess room for subsequent connections.
After pools, metrics and business traffic are stable, choose a clear configuration-management method. SET PERSIST changes the runtime value and persists it:
SET PERSIST max_connections = 200;
Replace the example value; see SET semantics and privileges. To remove that persisted setting:
RESET PERSIST max_connections;
RESET PERSIST removes persistence without restoring the running value. Restore that separately from your change record. See RESET PERSIST. If maintaining configuration files instead, confirm the loaded source so my.cnf, persisted values and deployment arguments do not conflict.
Recreating a container need not remove persisted settings in its data directory. Keep the database volume. See the MySQL 8.4 Docker deployment guide for configuration, data and backups.
wait_timeout governs idle sessions, not actively running slow queries. An excessively short value can leave a pool reusing server-closed connections. Distinguish global changes from existing session values, and coordinate server timeouts with pool recycling, health checks and long transactions. Fix leaks and pool lifecycle first; neither 30 nor 60 seconds is universally optimal.
Use the original application account and connection route to test login, reads, writes and important transactions. Gradually resume paused work and observe an interval covering normal traffic and scheduled jobs:
Threads_connectedstays within budget instead of rising continuously.- 1040 errors and
Connection_errors_max_connectionsstop increasing. - Query latency, pool waits, errors and memory remain acceptable.
- Deployments and overlapping queue/scheduled peaks retain headroom.
A single successful login or zero connections after a restart does not prove the cause is fixed. Save before/after snapshots, limits, pool settings and rollback details so future application scaling includes the database budget.