MySQL ERROR 1040 Too many connections: cause and fix
Fix MySQL ERROR 1040 "Too many connections": see who is connected, close leaking connections and raise max_connections.
MySQL allows only a set number of connections at once, 151 by default. When they are all in use, new clients get error 1040. Raising the limit helps for a moment, but the usual cause is an app that opens connections and never closes them.
What to do, step by step
- Log in as an administrator. MySQL keeps one extra connection for admin accounts, so you can still get in.
- See who is connected: SHOW PROCESSLIST;. Look for many idle connections from one program or user.
- Raise the limit for now: SET GLOBAL max_connections = 300;. This lasts until MySQL restarts.
- Make it permanent in your config file under [mysqld]. The my.cnf generator on this site writes that line for you.
- Fix the cause in the app: close connections when done, use a connection pool, and avoid persistent connections for many workers.
Commands you can copy
SHOW VARIABLES LIKE 'max_connections';SHOW FULL PROCESSLIST;SET GLOBAL max_connections = 300;SET GLOBAL wait_timeout = 300;KILL 123;Other causes to check
- Many connections in Sleep state
- Clients connect and then do nothing. Lower wait_timeout so MySQL closes idle connections, and fix the app so it closes them.
- It happens only at busy times
- Too many app workers for the limit. Each worker can hold a connection, so workers times servers must stay below max_connections. A pool or a proxy such as ProxySQL helps.
- After raising the limit MySQL runs out of memory
- Every connection uses memory. Raise the limit in small steps and watch RAM, or add a pool instead.
- Cannot log in at all
- The extra admin connection may be taken too. Stop some app servers for a moment, log in, and then kill idle connections.
Questions about MySQL too many connections
- What is the default max_connections?
- 151 in MySQL and MariaDB. Many servers run fine with a few hundred.
- How do I see the current number of connections?
- Run SHOW STATUS LIKE 'Threads_connected'; for now, and Max_used_connections for the peak since the last restart.
- Is a bigger limit always better?
- No. Each connection uses memory and can slow the server. A pool that shares a few connections is better than thousands of idle ones.
Config generators for this
- MySQL my.cnf settingsA small MySQL or MariaDB override file for connections, memory, character set and the slow query log.