If your sites on a cPanel server suddenly show “Error establishing a database connection” and the logs say ERROR 1040 (HY000): Too many connections, this page walks you through getting them back, step by step. The database server (MySQL or MariaDB) has reached its max_connections limit, the number of client sessions it will hold at once, and it is turning every new visitor away. The fix is to log in as root through the one slot the server keeps for administrators, then close the idle connections of the account that used up the slots and cap it. Raising max_connections comes last, and only if the numbers say you are short of real capacity.
What you’ll accomplish
- Confirm that the outage really is error 1040, and not a wrong password or a stopped service.
- Get a working database session while every site is locked out.
- Tell a connection leak apart from genuine load with one status query.
- Free the pool and bring the sites back without restarting the database.
- Cap the account that caused it, so next time only that site gets an error.
Prerequisites
- Root SSH access to the cPanel/WHM server. On a standard cPanel install,
/root/.my.cnfholds the database root password, somysqlruns without prompting. - MySQL 8.0 or 8.4, or MariaDB 10.6, 10.11 or 11.4, the versions you are likely to find on a current cPanel server. The commands work on both engines, and the few differences are called out where they matter. On MariaDB 11.x, if the
mysqlcommand is missing, usemariadbwith the same options. - Permission to end sessions. Step 6 disconnects clients. On a shared server, that can interrupt another customer’s request, so tell whoever needs to know.
- The defaults, for reference. Both engines ship with
max_connections = 151andwait_timeout = 28800, which is eight hours of idle time before the server closes a forgotten connection.
How it works
Every page view in WordPress or another PHP app opens a connection to the database and is supposed to close it when the page is done. Each open connection uses one slot. max_connections is the number of slots, and when all of them are taken, the next client is refused with error 1040 instead of a login. Together the slots form one pool, shared by every account on the server. That is why all your WordPress sites fail at the same moment, even when only one of them caused it.
The error text changes a little depending on who reports it:
- The
mysqlcommand line showsERROR 1040 (HY000): Too many connectionsorERROR 1040 (08004), depending on the client and server versions. - PHP’s mysqli extension, which WordPress uses, logs
mysqli_real_connect(): (HY000/1040): Too many connections, and WordPress shows visitors “Error establishing a database connection”. - Apps built on PDO, PHP’s other database layer, log
SQLSTATE[HY000] [1040] Too many connections. Some apps wrap it in their own fatal message, such as “can’t connect to database defined in setup_db.php”, ending in(1040).
Both engines keep one extra slot beyond max_connections. Only an account with the administrator-level SUPER privilege can use it, or CONNECTION_ADMIN on MySQL (CONNECTION ADMIN on MariaDB 10.5.2 and later). root has those privileges, which is why root can still log in while every site is refused.
Once you are in, the key question is what the connections are doing. A session in the Sleep state is open but idle: it finished its work and never hung up. A full pool of sleepers with only a few running queries is a leak or a pile-up from one application. A full pool where many sessions are busy is real load. The two need opposite fixes, and raising max_connections only helps the second.
Step-by-step
-
Confirm the error in the site logs. cPanel’s PHP writes errors to an
error_logfile in the site folder, and WordPress debug logging writes towp-content/debug.log. This search lists the files that mention it:grep -l 'Too many connections' /home/*/public_html/error_log /home/*/public_html/wp-content/debug.log 2>/dev/nullExample output:
/home/bakery/public_html/error_log /home/tlshop/public_html/error_logSeveral accounts listed at once is the classic picture of 1040: the whole server is refusing. If nothing matches and you see
Access deniedorCan't connect to local MySQL server through socketinstead, this is a different problem. A wrong password or a stopped service needs a different fix. -
Log in through the reserved slot. Run this as
rooton the server itself. On localhost the client uses the local socket, so no network setting gets in the way.mysql -e "SELECT 1;"Example output:
+---+ | 1 | +---+ | 1 | +---+If this also returns 1040, someone else already holds the reserved slot. Go to the first entry under Troubleshooting before you continue.
-
Read the three numbers that classify the incident.
mysql -e "SHOW GLOBAL STATUS WHERE Variable_name IN ('Threads_connected','Threads_running','Max_used_connections'); SHOW GLOBAL VARIABLES LIKE 'max_connections';"Example output:
+----------------------+-------+ | Variable_name | Value | +----------------------+-------+ | Max_used_connections | 152 | | Threads_connected | 152 | | Threads_running | 4 | +----------------------+-------+ +-----------------+-------+ | Variable_name | Value | +-----------------+-------+ | max_connections | 151 | +-----------------+-------+Threads_connectedcounts open sessions.Threads_runningcounts the ones executing a query right now, including yours.Max_used_connectionsatmax_connections + 1shows that yourrootsession took the reserved slot. Here 152 are connected but only 4 are working, so the pool is full of idle sessions: a leak or pile-up. IfThreads_runningcame back at 60 or more, read “When this is the wrong approach” before going further. -
Find which database user holds the pool.
mysql -e "SELECT USER, COMMAND, COUNT(*) AS conns, MAX(TIME) AS oldest_s FROM information_schema.PROCESSLIST GROUP BY USER, COMMAND ORDER BY conns DESC;"Example output:
+------------+---------+-------+----------+ | USER | COMMAND | conns | oldest_s | +------------+---------+-------+----------+ | bakery_wp1 | Sleep | 131 | 3417 | | tlshop_app | Sleep | 12 | 95 | | tlshop_app | Query | 3 | 2 | | jfcafe_wp | Sleep | 5 | 640 | | root | Query | 1 | 0 | +------------+---------+-------+----------+oldest_sis the age in seconds of the oldest session in each group. One user with well over half the pool, sleeping for nearly an hour, is your culprit. On MySQL 8.4,information_schema.PROCESSLISTis deprecated but still works, andperformance_schema.processlistgives the same columns. A single row withevent_schedulerandDaemonis a built-in MySQL thread, so leave it alone. -
Match the database user to a site. cPanel prefixes database users with the account name, so
bakery_wp1almost certainly belongs to thebakeryaccount. Confirm it from the site’s own configuration:grep -l "bakery_wp1" /home/*/public_html/wp-config.phpExample output:
/home/bakery/public_html/wp-config.phpIf nothing matches, the site may be an addon domain, which is a second site kept in its own folder under the same account. Widen the search to
/home/bakery/withgrep -rl. -
Close that user’s idle connections. Write the list of
KILLstatements to a file first. Doing it in two separate commands matters: a pipe would run tworootclients at once, and the second one finds the reserved slot taken.mysql -N -e "SELECT CONCAT('KILL ',ID,';') FROM information_schema.PROCESSLIST WHERE USER='bakery_wp1' AND COMMAND='Sleep' AND TIME > 120;" > /root/kill-1040.sql wc -l < /root/kill-1040.sql head -3 /root/kill-1040.sqlExample output:
127 KILL 88214; KILL 88219; KILL 88307;The count should be close to the
Sleeptotal from step 4. If it is 0, the sessions are younger than two minutes, so lowerTIME > 120toTIME > 30. When the list looks right, run it:mysql --force < /root/kill-1040.sqlNo output means every listed session was closed. The
--forceoption tells the client to keep going after an error. You may see a line such asERROR 1094 (HY000) at line 12: Unknown thread id: 88412. It means that session closed on its own in the meantime, which is harmless, and the remainingKILLlines still run. Only targetSleepsessions here. Killing a session in the middle of a large write makes the server undo that write, and the slot stays busy until the undo finishes. -
Cap the account so it cannot fill the pool again. A per-account limit means this user gets an error of its own instead of taking every site down. This syntax works on MySQL 8.x and MariaDB 10.6 and later. Use the exact
'user'@'host'pair, which islocalhostfor a normal cPanel database user:mysql -e "ALTER USER 'bakery_wp1'@'localhost' WITH MAX_USER_CONNECTIONS 25; SELECT User, Host, max_user_connections FROM mysql.user WHERE User='bakery_wp1';"Example output:
+------------+-----------+----------------------+ | User | Host | max_user_connections | +------------+-----------+----------------------+ | bakery_wp1 | localhost | 25 | +------------+-----------+----------------------+For the number, start from the site’s PHP-FPM limit. PHP-FPM is the service that runs a fixed number of PHP worker processes per site, and each worker normally holds one connection. Read the limit from the site’s pool file, named after its domain:
grep -H 'pm.max_children' /opt/cpanel/ea-php*/root/etc/php-fpm.d/bakery.example.confExample output:
/opt/cpanel/ea-php82/root/etc/php-fpm.d/bakery.example.conf:pm.max_children = 20Add 5 for cron jobs and admin work, so 20 workers become a cap of 25. If no file matches, the site does not run PHP-FPM, so start at 25. The cap applies to new logins. Once it is reached, that site sees
ERROR 1226 (42000): User 'bakery_wp1' has exceeded the 'max_user_connections' resourcewhile the others keep working. MySQL 8 rejects the olderGRANT ... WITH MAX_USER_CONNECTIONSform, so stick withALTER USER. -
Shorten how long idle sessions can linger. Eight hours of
wait_timeoutlets a leaked connection keep its slot all day. Five minutes is plenty for PHP pages and cron jobs:mysql -e "SET GLOBAL wait_timeout = 300; SHOW GLOBAL VARIABLES LIKE 'wait_timeout';"Example output:
+---------------+-------+ | Variable_name | Value | +---------------+-------+ | wait_timeout | 300 | +---------------+-------+Sessions that are already open keep their old timeout, so this protects you from now on but does not clear today’s pile-up (step 6 did that). If an app later logs “MySQL server has gone away” after long pauses, raise the value to 600.
-
Make the changes survive a restart.
SET GLOBALlasts until the next restart. cPanel keeps the server settings in/etc/my.cnf, so back it up and add the lines under the[mysqld]section:cp -a /etc/my.cnf /etc/my.cnf.bak-$(date +%F) grep -nE '^\s*(\[mysqld\]|wait_timeout|max_connections|!include)' /etc/my.cnfExample output:
1:[mysqld] 9:max_connections=151Add
wait_timeout=300below[mysqld], and edit any existingwait_timeoutline instead of adding a second one. An!includedirline means another file may override yours, so check it too. The per-account cap from step 7 is stored in the user table and already survives restarts. You do not need to restart now. The file is read at the next planned restart, which you can run with/scripts/restartsrv_mysqlduring a quiet hour. -
Raise
max_connectionsonly if step 3 showed real load. IfThreads_runningwas high and no single account dominated, the pool really is too small. For relief, raise it at runtime to about double the current value, then size it properly once things are calm:mysql -e "SET GLOBAL max_connections = 300; SHOW GLOBAL VARIABLES LIKE 'max_connections';"Example output:
+-----------------+-------+ | Variable_name | Value | +-----------------+-------+ | max_connections | 300 | +-----------------+-------+Every connection uses memory, so a higher limit is a memory bet. Working out the safe number from RAM and PHP-FPM workers is covered in tuning max_connections on a cPanel host.
Validate it works
Check that the pool has room again and the busiest account sits under its cap:
mysql -e "SHOW GLOBAL STATUS WHERE Variable_name IN ('Threads_connected','Threads_running'); SELECT USER, COUNT(*) AS conns FROM information_schema.PROCESSLIST GROUP BY USER ORDER BY conns DESC LIMIT 3;"
Example output:
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_connected | 41 |
| Threads_running | 3 |
+-------------------+-------+
+------------+-------+
| USER | conns |
+------------+-------+
| bakery_wp1 | 19 |
| tlshop_app | 14 |
| jfcafe_wp | 5 |
+------------+-------+
Then load a page on each affected site from outside the server. A 200 means WordPress reached its database:
curl -sS -o /dev/null -w '%{http_code}\n' https://bakery.example/
Example output:
200
A 500 with “Error establishing a database connection” means that site is still refused. Run step 4 again. Finally, run step 3 again an hour later. Threads_connected should stay well below max_connections at your busiest time.
Troubleshooting
- Root gets 1040 too. Another
SUPERsession holds the reserved slot: a monitoring agent, a backup, or a shell someone left open. Recent MariaDB clients may print this inside anERROR 2002message that ends in1040 - Too many connections. Find that client from the shell withps aux | grep -E 'mysql|mysqldump'and end it, which frees the slot for you. As a last resort,/scripts/restartsrv_mysqldrops every connection and brings the sites back, but you lose the evidence for steps 3 and 4. SET GLOBAL max_user_connectionsfails on MariaDB withERROR 1290. MariaDB refuses to change that server-wide setting at runtime if it started at 0. The per-accountALTER USERcap from step 7 is not affected. For a server-wide default, addmax_user_connections=50under[mysqld]in/etc/my.cnfand apply it at the next restart. That is about a third of the default 151, so no single account can take more than a third of the pool. Scale it the same way if yourmax_connectionsis different.- The pool fills up again within minutes. Something is still opening connections faster than they close. Look at the site’s access log for a crawler or a burst of
wp-cron.phpandadmin-ajax.phphits. Also look for a plugin using persistent connections, which keep a connection open per PHP worker. The cap from step 7 keeps the other sites up while you dig. - After a restart,
max_connectionsis lower than what you set (MySQL). The server could not get enough open-file handles from the system. Find the error log withmysql -e "SELECT @@log_error;"and search it forChanged limits. A line likeChanged limits: max_connections: 214 (requested 400)confirms it. Runsystemctl edit mysqld, which opens an override file that survives updates. Add a[Service]line withLimitNOFILE=65535below it, save, then restart during a quiet window. - The site now shows
ERROR 1226orERROR 1203. That is the cap doing its job: 1226 comes from a per-account limit, 1203 from a server-wide one. If normal traffic hits it, the cap is too low for that site’s PHP workers. Raise it by five and watch again.
When this is the wrong approach
If step 3 showed many sessions running (dozens in Query with climbing TIME values), the full pool is a side effect of slow queries. Every new visitor queues behind the same slow statement. Killing idle sessions will not help, and raising max_connections only adds memory pressure. Find and fix the slow query instead, starting with detecting and killing long-running queries.
This page also does not apply to managed databases such as Amazon RDS, where you do not get the SUPER privilege or the reserved slot. If you keep raising max_connections on the same server, the workload has probably outgrown it. The MySQL reference on too many connections and the MariaDB system variables list document every setting used here.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.