ERROR 1040 (HY000): Too many connections
MySQL has a maximum number of simultaneous connections (default: 151). All slots are in use.
Fix 1: Increase max_connections
-- Check current limit
SHOW VARIABLES LIKE 'max_connections';
-- Increase temporarily
SET GLOBAL max_connections = 300;
-- Permanent: add to my.cnf
-- [mysqld]
-- max_connections = 300
Fix 2: Close Idle Connections
-- See all connections
SHOW PROCESSLIST;
-- Kill idle ones
KILL <process_id>;
-- Reduce wait timeout (close idle connections faster)
SET GLOBAL wait_timeout = 300; -- 5 minutes instead of 8 hours
SET GLOBAL interactive_timeout = 300;
Fix 3: Fix Connection Leaks in Code
// ❌ Opening connections without closing
const conn = await mysql.createConnection(config);
const data = await conn.query('SELECT * FROM users');
// Forgot conn.end()
// ✅ Always close connections
try {
const data = await conn.query('SELECT * FROM users');
return data;
} finally {
await conn.end();
}
Fix 4: Use Connection Pooling
// ✅ Pool manages connections automatically
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'mydb',
connectionLimit: 10, // Max connections from this app
waitForConnections: true,
});
const [rows] = await pool.query('SELECT * FROM users');
// Connection automatically returned to pool
Fix 5: Check What’s Using Connections
-- Group by user/host
SELECT user, host, COUNT(*) as connections
FROM information_schema.processlist
GROUP BY user, host
ORDER BY connections DESC;
Related resources
Related: PostgreSQL Cheat Sheet