Skip to content

Fix ERROR 1040 Too many connections on cPanel MySQL/MariaDB

When WordPress or a PHP app on your cPanel server fails with error 1040 too many connections, you can still log in as root through a slot the database keeps for administrators. From there, find the account that used up the connections, close its idle ones and cap it so one site cannot take every site down again.

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.cnf holds the database root password, so mysql runs 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 mysql command is missing, use mariadb with 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 = 151 and wait_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 mysql command line shows ERROR 1040 (HY000): Too many connections or ERROR 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.

The max_connections pool full of mostly Sleep connections, the 152nd WordPress connection refused with ERROR 1040, and root entering through the one reserved slot

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

  1. Confirm the error in the site logs. cPanel’s PHP writes errors to an error_log file in the site folder, and WordPress debug logging writes to wp-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/null

    Example output:

    /home/bakery/public_html/error_log
    /home/tlshop/public_html/error_log

    Several accounts listed at once is the classic picture of 1040: the whole server is refusing. If nothing matches and you see Access denied or Can't connect to local MySQL server through socket instead, this is a different problem. A wrong password or a stopped service needs a different fix.

  2. Log in through the reserved slot. Run this as root on 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.

  3. 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_connected counts open sessions. Threads_running counts the ones executing a query right now, including yours. Max_used_connections at max_connections + 1 shows that your root session 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. If Threads_running came back at 60 or more, read “When this is the wrong approach” before going further.

  4. 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_s is 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.PROCESSLIST is deprecated but still works, and performance_schema.processlist gives the same columns. A single row with event_scheduler and Daemon is a built-in MySQL thread, so leave it alone.

  5. Match the database user to a site. cPanel prefixes database users with the account name, so bakery_wp1 almost certainly belongs to the bakery account. Confirm it from the site’s own configuration:

    grep -l "bakery_wp1" /home/*/public_html/wp-config.php

    Example output:

    /home/bakery/public_html/wp-config.php

    If 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/ with grep -rl.

  6. Close that user’s idle connections. Write the list of KILL statements to a file first. Doing it in two separate commands matters: a pipe would run two root clients 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.sql

    Example output:

    127
    KILL 88214;
    KILL 88219;
    KILL 88307;

    The count should be close to the Sleep total from step 4. If it is 0, the sessions are younger than two minutes, so lower TIME > 120 to TIME > 30. When the list looks right, run it:

    mysql --force < /root/kill-1040.sql

    No output means every listed session was closed. The --force option tells the client to keep going after an error. You may see a line such as ERROR 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 remaining KILL lines still run. Only target Sleep sessions 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.

  7. 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 is localhost for 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.conf

    Example output:

    /opt/cpanel/ea-php82/root/etc/php-fpm.d/bakery.example.conf:pm.max_children = 20

    Add 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' resource while the others keep working. MySQL 8 rejects the older GRANT ... WITH MAX_USER_CONNECTIONS form, so stick with ALTER USER.

  8. Shorten how long idle sessions can linger. Eight hours of wait_timeout lets 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.

  9. Make the changes survive a restart. SET GLOBAL lasts 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.cnf

    Example output:

    1:[mysqld]
    9:max_connections=151

    Add wait_timeout=300 below [mysqld], and edit any existing wait_timeout line instead of adding a second one. An !includedir line 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_mysql during a quiet hour.

  10. Raise max_connections only if step 3 showed real load. If Threads_running was 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 SUPER session holds the reserved slot: a monitoring agent, a backup, or a shell someone left open. Recent MariaDB clients may print this inside an ERROR 2002 message that ends in 1040 - Too many connections. Find that client from the shell with ps aux | grep -E 'mysql|mysqldump' and end it, which frees the slot for you. As a last resort, /scripts/restartsrv_mysql drops every connection and brings the sites back, but you lose the evidence for steps 3 and 4.
  • SET GLOBAL max_user_connections fails on MariaDB with ERROR 1290. MariaDB refuses to change that server-wide setting at runtime if it started at 0. The per-account ALTER USER cap from step 7 is not affected. For a server-wide default, add max_user_connections=50 under [mysqld] in /etc/my.cnf and 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 your max_connections is 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.php and admin-ajax.php hits. 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_connections is lower than what you set (MySQL). The server could not get enough open-file handles from the system. Find the error log with mysql -e "SELECT @@log_error;" and search it for Changed limits. A line like Changed limits: max_connections: 214 (requested 400) confirms it. Run systemctl edit mysqld, which opens an override file that survives updates. Add a [Service] line with LimitNOFILE=65535 below it, save, then restart during a quiet window.
  • The site now shows ERROR 1226 or ERROR 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.