You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -8,89 +8,146 @@ title: 'ERROR 1040 (HY000): Too Many Connections'
8
8
ERROR 1040 (HY000): Too many connections
9
9
```
10
10
11
-
## Description
11
+
You may also see this from application code as a connection refused or pool exhaustion error, depending on your driver. The MySQL error log will show `Aborted connection` entries alongside it.
12
12
13
-
This error occurs when the MySQL server has reached its maximum allowed number of concurrent client connections. The server is unable to accept any new connections until existing connections are closed or terminated.
13
+
## What Triggers This Error
14
14
15
-
## Causes
15
+
MySQL 1040 means every connection slot is occupied and the server can't accept new ones. The fix depends on why the slots filled up:
16
16
17
-
- Low `max_connections` setting (default is often too low, typically 151)
18
-
- Connection leaks in applications (not properly closing connections)
19
-
- Inefficient connection pooling configuration
20
-
- Long-running queries holding connections open
21
-
- Sleeping connections consuming connection slots
22
-
- Sudden increases in application traffic
23
-
- Unclosed transactions keeping connections active
24
-
- Insufficient server resources to handle more connections
17
+
-**Connection leak in application code** — connections opened but never closed
18
+
-**`max_connections` set too low for the workload** — the default (151) is often insufficient
19
+
-**Long-running queries holding connections** — slots occupied by queries that haven't finished
20
+
-**Connection pooler misconfiguration** — pool max exceeds server max, or idle connections aren't being reaped
The most common cause. Your application opens connections but doesn't close them — usually because error paths skip the cleanup step, or connections are created inside loops without proper release.
33
28
34
-
-- Increase max_connections temporarily
35
-
SET GLOBAL max_connections =500;
29
+
```sql
30
+
-- Check how many connections are sleeping (idle)
31
+
SELECT user, host, command, time, state
32
+
FROMinformation_schema.processlist
33
+
WHERE command ='Sleep'
34
+
ORDER BYtimeDESC;
35
+
```
36
36
37
-
-- For permanent changes, modify my.cnf/my.ini:
38
-
# max_connections = 500
39
-
```
37
+
If you see hundreds of `Sleep` connections from the same application user with high `time` values, that's a leak. Fix the application code — ensure every connection is closed in a `finally` block (Java/Python) or `defer` (Go):
40
38
41
-
2.**Implement connection pooling**:
39
+
```python
40
+
# Python example — always close in finally
41
+
conn = mysql.connector.connect(...)
42
+
try:
43
+
cursor = conn.cursor()
44
+
cursor.execute("SELECT ...")
45
+
finally:
46
+
conn.close()
47
+
```
42
48
43
-
Configure connection pools in your application:
49
+
As an immediate fix to restore access, kill the sleeping connections:
44
50
45
-
```
46
-
# Example pool settings:
47
-
pool_size = 10 # Base connections
48
-
pool_max_size = 20 # Maximum connections
49
-
pool_idle_timeout = 300 # Seconds before idle connection is closed
50
-
```
51
+
```sql
52
+
-- Kill connections sleeping longer than 5 minutes
53
+
SELECT CONCAT('KILL CONNECTION ', id, ';')
54
+
FROMinformation_schema.processlist
55
+
WHERE command ='Sleep'ANDtime>300;
56
+
```
51
57
52
-
3.**Terminate idle connections**:
58
+
### `max_connections` set too low
53
59
54
-
```sql
55
-
-- Show current connections and their state
56
-
SHOW PROCESSLIST;
60
+
The default of 151 is a conservative starting point. Production workloads with multiple application instances, background jobs, and monitoring agents can exceed this quickly.
57
61
58
-
-- Kill long-running or sleeping connections
59
-
KILL CONNECTION connection_id;
60
-
```
62
+
```sql
63
+
-- Check current setting and usage
64
+
SHOW VARIABLES LIKE'max_connections';
65
+
SHOW STATUS LIKE'Threads_connected';
66
+
SHOW STATUS LIKE'Max_used_connections';
67
+
```
61
68
62
-
4.**Configure connection timeouts**:
69
+
If `Max_used_connections` is close to or equal to `max_connections`, you're hitting the ceiling:
63
70
64
-
```sql
65
-
-- Reduce timeout values
66
-
SET GLOBAL wait_timeout =300; -- Close inactive connections after 5 minutes
67
-
SET GLOBAL interactive_timeout =300; -- Close inactive client connections after 5 minutes
68
-
```
71
+
```sql
72
+
-- Increase temporarily (takes effect immediately, lost on restart)
73
+
SET GLOBAL max_connections =500;
74
+
```
69
75
70
-
## Prevention
76
+
For a permanent change, edit `my.cnf`:
77
+
78
+
```ini
79
+
[mysqld]
80
+
max_connections = 500
81
+
```
82
+
83
+
Each connection uses memory (roughly 1-10 MB depending on buffers), so don't set this to 10,000 — increase it in proportion to available RAM.
84
+
85
+
### Long-running queries holding connections
86
+
87
+
A slow query or stuck transaction can hold a connection for hours. If enough of them pile up, you run out of slots.
88
+
89
+
```sql
90
+
-- Find queries running longer than 60 seconds
91
+
SELECT id, user, host, db, time, state, LEFT(info, 100) AS query
92
+
FROMinformation_schema.processlist
93
+
WHERE command !='Sleep'ANDtime>60
94
+
ORDER BYtimeDESC;
95
+
96
+
-- Kill a specific long-running query
97
+
KILL QUERY <id>;
98
+
```
99
+
100
+
Address the root cause: add indexes, optimize the query, or set a query timeout:
71
101
72
-
1.**Use connection pooling** in your applications (HikariCP, DBCP, PDO)
102
+
```sql
103
+
-- Set a 30-second timeout for SELECT statements on NEW connections (MySQL 5.7.8+)
104
+
-- Existing sessions keep their current SESSION max_execution_time value.
105
+
SET GLOBAL max_execution_time =30000;
73
106
74
-
2.**Properly manage connections** in application code:
107
+
-- To apply a 30-second timeout for SELECT statements in the current session only:
108
+
-- SET SESSION max_execution_time = 30000;
109
+
110
+
-- To enforce a 30-second timeout for a single SELECT statement:
111
+
-- SELECT /*+ MAX_EXECUTION_TIME(30000) */ ...
112
+
-- FROM your_table
113
+
-- WHERE ...;
114
+
```
75
115
76
-
- Always close connections after use
77
-
- Use try-finally blocks to ensure connections are released
78
-
- Implement connection reuse
116
+
### Connection pooler misconfiguration
117
+
118
+
If you're using a connection pool (HikariCP, DBCP, SQLAlchemy pool, ProxySQL), the pool's maximum size multiplied by the number of application instances must not exceed `max_connections`.
119
+
120
+
Example: 5 app instances × pool max 50 = 250 connections needed, but `max_connections` is 151.
121
+
122
+
```yaml
123
+
# HikariCP example — keep pool small, set idle timeout
124
+
maximumPoolSize: 20
125
+
minimumIdle: 5
126
+
idleTimeout: 300000# 5 minutes
127
+
maxLifetime: 1800000# 30 minutes
128
+
```
79
129
80
-
3.**Monitor active connections**:
130
+
For ProxySQL, ensure `mysql-max_connections` on the backend server entry matches the actual MySQL setting.
81
131
82
-
```sql
83
-
-- Check current connection count
84
-
SHOW STATUS LIKE'Threads_connected';
85
-
```
132
+
### Sudden traffic spike
86
133
87
-
4.**Optimize slow queries** that hold connections open:
88
-
```sql
89
-
-- Enable slow query log
90
-
SET GLOBAL slow_query_log ='ON';
91
-
SET GLOBAL long_query_time =1;
92
-
```
134
+
Legitimate load exceeding capacity. Short-term: increase `max_connections` and add connection pooling at the application or proxy layer. Long-term: consider read replicas, query caching, or moving to a managed service with auto-scaling.
135
+
136
+
```sql
137
+
-- Monitor connection growth in real time
138
+
SHOW STATUS LIKE 'Threads_connected';
139
+
SHOW STATUS LIKE 'Connections'; -- cumulative since startup
140
+
```
141
+
142
+
## Prevention
143
+
144
+
- Use connection pooling in every application that connects to MySQL — never open raw connections per request
145
+
- Set `wait_timeout` and `interactive_timeout` to close idle connections automatically (300-600 seconds is reasonable)
146
+
- Monitor `Threads_connected` vs `max_connections` and alert at 80% utilization
147
+
- Enable the slow query log (`long_query_time = 1`) to catch queries that hold connections too long
93
148
94
149
<HintBlock type="info">
95
-
Increasing max_connections requires more memory. Each connection consumes server resources, so simply increasing this value without addressing underlying issues can lead to performance problems. Connection pooling is often a better solution.
150
+
151
+
Bytebase's [SQL Review](https://www.bytebase.com/docs/sql-review/review-rules/) can catch problematic queries during change review before they cause connection issues in production. See also [ERROR 53300: Too Many Connections in Postgres](/reference/postgres/error/53300-too-many-connections) for the PostgreSQL equivalent.
0 commit comments