What ERROR 1040 means
MySQL and MariaDB accept only a fixed number of client connections at the same time. That number is the max_connections system variable, and its default is 151 in the MySQL 8.0 manual and in the MariaDB documentation. When every slot is taken, the next client is refused:
ERROR 1040 (HY000): Too many connections
The MySQL error reference lists this as error 1040, ER_CON_COUNT_ERROR, with SQLSTATE 08004. The mysql client prints HY000 in front of it, and PHP drivers show the same message with code 1040. A website on top of the database may show a different message: WordPress reports "Error establishing a database connection" (see that guide for the WordPress side).
The error says the slots are full. It does not say why. A connection that sits idle takes a slot exactly like one that runs a query, so the cause is one of these: the limit is too low for real traffic, an application holds connections it no longer needs, or slow queries keep slots busy for too long. Work through the steps below in order, because raising the limit before you know the cause only moves the failure later and costs memory.
The fix in five steps
- Get in. Log in with an admin account. The server keeps one extra slot for it.
- Measure. Compare
Threads_connectedandMax_used_connectionswithmax_connections. - Look. Run
SHOW FULL PROCESSLISTand group the connections by user and client. - Free slots. Kill the sleeping connections of the guilty account, or stop the application for a minute.
- Fix the cause. Close connections in code, stop persistent connections from multiplying, size the pool, set
wait_timeout, and only then raisemax_connectionsafter checking RAM.
Step 1: get a shell when the server is full
The MySQL manual says mysqld permits max_connections + 1 client connections. The extra connection is reserved for accounts with the CONNECTION_ADMIN privilege (or the deprecated SUPER privilege), so an administrator can run SHOW PROCESSLIST even when every ordinary slot is taken. MariaDB reserves one connection in the same way for SUPER or CONNECTION ADMIN users.
On Ubuntu, root logs in over the local socket, so this works from an SSH session:
sudo mysql
If that fails with an access error instead of error 1040, read Access denied for user 'root'@'localhost' first. If it fails with Too many connections even for root, the one reserved slot is already in use. Something is connecting with an admin account, which is the reason application users should not hold SUPER or CONNECTION_ADMIN. In that case stop the application so its connections close, then log in:
systemctl list-units 'php*-fpm*' --no-pager
sudo systemctl stop php8.3-fpm
sudo mysql
Replace php8.3-fpm with the unit name from the first command (Ubuntu 24.04 ships PHP 8.3, Ubuntu 22.04 ships PHP 8.1). For Apache with mod_php stop apache2; for a Node or Python app stop its own service. Start it again when you have found the cause.
Step 2: see how close you are to the limit
SHOW VARIABLES LIKE 'max_connections';
SHOW GLOBAL STATUS WHERE Variable_name IN
('Threads_connected', 'Threads_running', 'Max_used_connections',
'Max_used_connections_time', 'Connection_errors_max_connections');
What each value tells you, using the definitions in the MySQL manual:
Threads_connectedis the number of currently open connections, idle ones included.Threads_runningis the number of threads that are not sleeping.Max_used_connectionsis the highest number of simultaneous connections since the server started, andMax_used_connections_timesays when that peak was reached.Connection_errors_max_connectionscounts connections refused because the limit was reached. If it is above zero, real clients were turned away.
The two thread counts point to different problems. A high Threads_connected with a low Threads_running means most connections are idle: look for leaks, persistent connections and long timeouts. A high Threads_running means connections are busy: look for slow queries and locks, and read how to find and fix slow MySQL queries.
Step 3: see who is using the connections
Without the PROCESS privilege you see only your own threads, so run these as root or another admin. SHOW FULL PROCESSLIST; lists every connection (without FULL the Info column is cut at 100 characters). On a busy server a summary is easier to read:
SELECT user,
SUBSTRING_INDEX(host, ':', 1) AS client,
COUNT(*) AS connections,
SUM(command = 'Sleep') AS sleeping,
MAX(time) AS longest_seconds
FROM information_schema.processlist
GROUP BY user, client
ORDER BY connections DESC;
The Command value is Sleep when a session is idle. The user column is the database account, which maps to one application or one website when you create a user per app, and client is the address it connects from (localhost for the local socket). On MySQL 8.0.22 and later the manual recommends the Performance Schema processlist table over the INFORMATION_SCHEMA one because it needs no mutex, but the query above works on both MySQL and MariaDB.
To see the oldest idle sessions:
SELECT id, user, host, db, time
FROM information_schema.processlist
WHERE command = 'Sleep'
ORDER BY time DESC
LIMIT 20;
Sessions that have slept for thousands of seconds point to code that forgot to close them, or to persistent connections.
Find the process on the server that owns the connections
If the application runs on the same VPS and connects over TCP (127.0.0.1), the operating system can name it. First count the TCP clients by address, then list the client sockets with their process names:
sudo ss -Htn state established '( sport = :3306 )' | awk '{print $4}' | sed 's/:[0-9]*$//' | sort | uniq -c | sort -rn | head
sudo ss -tnp state established '( dport = :3306 )'
The second command prints entries such as users:(("php-fpm8.3",pid=1234,fd=12)). Connections over the local socket file do not appear as TCP sockets; for those, rely on the user and db columns in the process list.
Step 4: free slots right now
With the guilty account identified, generate kill statements for its idle sessions only. Leave system accounts alone, such as event_scheduler or replication users.
SELECT CONCAT('KILL ', id, ';') AS run_this
FROM information_schema.processlist
WHERE command = 'Sleep' AND time > 300 AND user = 'shopapp';
Copy the lines it prints and run them. KILL CONNECTION (the same as plain KILL) ends the session after stopping any statement it is running; KILL QUERY stops only the statement and leaves the session. Killing another user's session needs CONNECTION_ADMIN or SUPER. The MySQL manual also warns that killing a statement that changes non-transactional tables does not roll the changes back, and that killing a REPAIR TABLE or OPTIMIZE TABLE on a MyISAM table leaves the table corrupted. A session that was only sleeping has no running statement, but any uncommitted transaction on it is lost, and the application has to reconnect. This clears the symptom. The leak will refill the slots until you fix it.
Step 5: find the app that leaks connections
Match what you saw in steps 2 and 3 to one of these patterns:
| What the process list shows | Likely cause | Fix |
|---|---|---|
Many Sleep sessions from one user, each with a large Time | Code opens connections and does not close them, or persistent connections are held by idle workers | Close in a finally block or use a pool; turn off persistent connections; set wait_timeout |
| The count grows steadily and drops only after an application restart | Leak in a long-running process (Node, Python, Java service, queue worker) | Use one shared pool with a fixed maximum, and release connections after each use |
| Connections spread across many app instances, each fine on its own | Instances × pool size is larger than max_connections | Cut the pool size per instance or raise the limit to match, with RAM checked |
High Threads_running, statements with long Time and a State such as locked or sending data | Slow queries or lock waits keep slots busy | Slow query log, EXPLAIN, indexes (see the slow queries guide) |
| Many short connections from the web server at the same moment | Traffic or bots hitting uncached pages, each needing a database connection | Page caching, rate limits, and a cap on PHP workers |
| Dozens of identical statements started at the same minute | Cron jobs or scheduled tasks overlapping because the previous run has not finished | Guard the job with flock -n /var/lock/job.lock command |
PHP persistent connections
A normal PHP connection closes when the script ends. A persistent connection does not: PHP keeps it open and hands it to the next request served by the same worker process. The PHP manual gives the consequence. Every child process that opens a persistent connection holds its own connection, so 20 workers mean 20 connections to the server. Idle workers keep their connections, and a spike in traffic that starts many workers leaves many connections open until a worker exits or the database closes the connection. The manual's advice is to make the database's maximum connections greater than the maximum number of web request workers, plus cron jobs and administrative connections.
Persistent connections are opt-in. In mysqli you add p: in front of the host name (new mysqli("p:localhost", ...)), and in PDO you set PDO::ATTR_PERSISTENT. Search your code and your CMS settings for those, and turn them off if the connection count tracks the number of PHP workers. To see the worker ceiling on a server using PHP-FPM:
grep -R "^pm.max_children" /etc/php/*/fpm/pool.d/
Each pool has its own pm.max_children, so add them up across pools. On Apache the equivalent limit is MaxRequestWorkers. If PHP-FPM can start more workers than the database has slots, a traffic spike can produce error 1040 even when every script closes its connection. Lowering the worker cap protects both the database and the server's RAM. Our PHP guide explains PHP-FPM workers.
Connection pooling
A pool opens a fixed number of connections once and lends them to requests, so the application cannot exceed its share. The arithmetic to check is: application instances × pool maximum, plus cron jobs and admin sessions, must stay below max_connections. Two examples with a ceiling set:
// Node.js, mysql2: at most 10 connections for this process
const pool = mysql.createPool({
host: '127.0.0.1', user: 'shopapp', password: process.env.DB_PASS,
database: 'shopdb', connectionLimit: 10
});
const [rows] = await pool.query('SELECT 1');
# Python, SQLAlchemy: at most 5 + 5 connections, recycled before wait_timeout
engine = create_engine(url, pool_size=5, max_overflow=5,
pool_recycle=1800, pool_pre_ping=True)
Set the pool's recycle or lifetime value below wait_timeout. Otherwise the server closes an idle pooled connection first and the application hits "MySQL server has gone away" on its next query. When many separate application processes cannot share a pool, a proxy such as ProxySQL can multiplex many client connections onto fewer server connections, as Percona describes in its guide to error 1040.
Close idle connections with wait_timeout
MySQL's wait_timeout is the number of seconds the server waits for activity on a non-interactive connection before closing it. Its default is 28800 seconds, which is 8 hours, so a forgotten connection holds a slot for a whole working day. Interactive clients such as the mysql command line use interactive_timeout instead. Check and change both:
SHOW VARIABLES WHERE Variable_name IN ('wait_timeout', 'interactive_timeout');
SET GLOBAL wait_timeout = 300;
A SET GLOBAL applies to connections opened after the change. Sessions that are already open keep their old value, so existing sleepers still need the KILL step. The value of 300 seconds is an example. Choose a number longer than any quiet gap that a pool or persistent connection relies on, then test the site. To keep it after a restart, put wait_timeout = 300 in the [mysqld] section of the config file (shown below).
Raise max_connections the right way
Raise the limit when you have measured a real need: Max_used_connections reaches max_connections during normal busy hours and the connections are doing work. max_connections is dynamic, so you can change it without a restart:
SET GLOBAL max_connections = 300;
That change is lost when the server restarts. To keep it, choose one method:
- MySQL 8.0:
SET PERSIST max_connections = 300;writes it tomysqld-auto.cnfin the data directory. The server reads that file after all other option files, so it overrides them. If you later edit the config file and nothing changes, runRESET PERSIST max_connections;. - Config file, MySQL or MariaDB: add the setting under
[mysqld].
Then restart the service (# MySQL on Ubuntu: /etc/mysql/mysql.conf.d/mysqld.cnf # MariaDB on Ubuntu: /etc/mysql/mariadb.conf.d/50-server.cnf [mysqld] max_connections = 300sudo systemctl restart mysqlorsudo systemctl restart mariadb). MariaDB 10.6 and 10.11 do not useSET PERSIST, so the file is the way to keep it there. On Windows the file ismy.ini.
Verify the running value, not the file:
SELECT @@max_connections;
SHOW VARIABLES LIKE 'open_files_limit';
The second line matters because every connection needs file descriptors. The MySQL 8.0 manual says the effective maximum is the lesser of open_files_limit - 810 and the value you set. The server asks the operating system for the largest of 10 + max_connections + (table_open_cache * 2) and max_connections * 5, but it cannot get more than ulimit -n, or LimitNOFILE under systemd. If open_files_limit comes back small, raise the service limit with a systemd drop-in, then restart:
sudo systemctl edit mysql
# in the editor that opens, add:
[Service]
LimitNOFILE=65535
Use mariadb in place of mysql for MariaDB. The manual says Linux should routinely support at least 500 to 1000 simultaneous connections, and as many as 10,000 with many gigabytes of RAM and a light workload per connection. Pick the number from your measured peak plus headroom, not from that ceiling.
What a higher limit costs in memory
Each connection is served by a thread with its own memory. The MySQL manual lists a thread stack (thread_stack), a connection buffer and a result buffer (both start at net_buffer_length and grow up to max_allowed_packet as needed), and statement-digest memory per session. On top of that, a query that scans a table allocates a read buffer, and most queries that sort allocate a sort buffer. Those buffers are allocated when a query needs them, so the real peak depends on the queries that run at the same time, not on the connection count alone.
The worst case is a useful upper bound: global buffers (the InnoDB buffer pool above all) plus max_connections times the per-connection buffers. Look at the values on your server:
SELECT @@innodb_buffer_pool_size, @@thread_stack, @@net_buffer_length,
@@sort_buffer_size, @@join_buffer_size, @@read_buffer_size;
Then measure instead of guessing. Note the memory use of the server while it is busy, raise the limit in steps, and compare:
free -h
ps -o rss=,comm= -C mysqld # MariaDB: -C mariadbd
Leave room for the operating system, PHP and the web server on the same machine. If the server runs out of RAM, Linux swaps first and then the out-of-memory killer ends a large process, which can be mysqld. Check with sudo journalctl -k | grep -i -E 'out of memory|oom'. Our VPS RAM sizing guide shows how to budget memory between the database, PHP and the web server. The thread cache (thread_cache_size) also keeps the memory of idle threads allocated while they wait for reuse.
Stop one account from taking every slot
A single misbehaving site should not be able to lock out the others. max_user_connections limits simultaneous connections per account. Its global default is 0, which means no limit, and you can set a limit on one account instead:
ALTER USER 'shopapp'@'localhost' WITH MAX_USER_CONNECTIONS 40;
When an account exceeds its limit, the error is 1203 ("User ... already has more than 'max_user_connections' active connections"), not 1040. That is useful in itself: you now know which application to look at. In MariaDB, max_user_connections does not apply to users with SUPER or CONNECTION ADMIN. Keep the sum of the per-account limits within max_connections so the accounts cannot together fill the server.
MariaDB differences
- Default and range.
max_connectionsdefaults to 151, with a range of 10 to 100000, and is dynamic like in MySQL. - Reserved slot. One connection is reserved for a
SUPERorCONNECTION ADMINaccount. Check the privilege names your MariaDB version supports in its GRANT documentation. Root oversudo mysqlalready has them. - Separate admin port. MariaDB can listen on
extra_portand cap that port withextra_max_connections, so administrators and tools can connect when all ordinary threads are busy. The MariaDB thread pool page notes that this port uses the old one-thread-per-connection handling. - Thread pool. On Unix,
thread_handling=pool-of-threadsenables MariaDB's thread pool, which replaces one thread per connection. It is a tuning step for servers with many active clients, and it does not remove the need to find the leak. - No SET PERSIST. Put permanent settings in the config file, as shown above.
- Binary and service names. The server binary is
mariadbdand the service ismariadb.
MySQL 8.0.14 and later can also listen on a dedicated administrative network interface (an IP address and port), which the Connection Interfaces chapter of the manual describes, and which does not depend on the shared connection slots.
Similar errors, side by side
| Error | Meaning | Where to go |
|---|---|---|
1040 Too many connections | Server-wide limit max_connections reached | This guide |
1203 User ... already has more than 'max_user_connections' active connections | One account hit its own limit | Raise or fix that account's connections; check max_user_connections |
1129 Host ... is blocked because of many connection errors | The host exceeded max_connect_errors interrupted attempts | Flush the host cache (mysqladmin flush-hosts), then find why connections were interrupted |
1045 Access denied for user | The server was reached but rejected the login | Access denied for user root |
2002 or 2003 cannot connect | The client could not reach the server (stopped service, wrong socket or port, firewall) | Check the service and the port, not the limits |
2006 MySQL server has gone away | The server closed a connection the client still thought was open, for example after wait_timeout | Recycle pooled connections before wait_timeout |
Common mistakes
- Setting
max_connectionsto 5000 as the first move. Memory is allocated as connections and queries use it, so a very high limit can look fine until a busy period uses it, and then the out-of-memory killer endsmysqld. - Editing the config file and not restarting, or editing a file that
SET PERSISToverrides. Always read the running value withSELECT @@max_connections;. - Giving the application the root account. It takes the reserved admin slot, so you cannot log in when you need to.
- Setting
wait_timeoutvery low with a pool. The pool then hands out dead connections and the app reports "server has gone away". - Using
SET GLOBAL wait_timeoutand expecting sleepers to disappear. It affects new connections only. - Pool size multiplied across instances. Ten containers with a pool of 50 want 500 connections.
- Killing everything that sleeps. Filter by user and age, so you do not cut a connection that a replication or backup job is using.
- Treating a raised limit as the fix. If the count climbs back to the new limit, a leak remains.
On Bigdomainhost servers
On a Bigdomainhost KVM VPS you have full root access, so every command above works as written on an Ubuntu server: you can read the process list, set max_connections and wait_timeout, and add a LimitNOFILE drop-in. VPS plans can be resized up with a reboot if the memory check shows you need more RAM. On Web & cPanel hosting you do not have MySQL root access and cannot change server settings such as max_connections. Web & cPanel plans allow 25 concurrent MySQL connections (see the fair-use limits in our docs), so a "too many connections" error there points to slow queries, plugins or uncached traffic on your own site. Fix those, or move to a VPS if the site has outgrown shared limits. Free migration is included on every plan.
Stuck on a connection error? Message us on WhatsApp at +91 75994 50220 at any time, call during IST working hours, or email support@bigdomainhost.com.
This guide was written by the Bigdomainhost team with AI assistance. Commands and behaviour were checked against the MySQL 8.0 Reference Manual, the MariaDB documentation and the PHP manual on 29 November 2026.
Sources (checked )
- MySQL 8.0 Reference Manual: B.3.2.5 Too many connections
- MySQL 8.0 Reference Manual: 7.1.12.1 Connection Interfaces (max_connections + 1, CONNECTION_ADMIN, administrative interface)
- MySQL 8.0 Reference Manual: 7.1.8 Server System Variables (max_connections, max_user_connections, wait_timeout, open_files_limit)
- MySQL 8.0 Reference Manual: 7.1.10 Server Status Variables (Threads_connected, Max_used_connections)
- MySQL 8.0 Reference Manual: KILL Statement
- MySQL 8.0 Reference Manual: SHOW PROCESSLIST Statement
- MySQL 8.0 Reference Manual: How MySQL Uses Memory
- MySQL 8.0 Error Reference: Server error reference (1040, 1203)
- PHP Manual: Persistent Database Connections
- PHP Manual: mysqli persistent connections
- MariaDB Knowledge Base (Wayback Machine snapshot): Server System Variables (max_connections)
- MariaDB Knowledge Base (Wayback Machine snapshot): Thread Pool in MariaDB (extra_port, extra_max_connections)
- MariaDB Knowledge Base (Wayback Machine snapshot): GRANT (CONNECTION ADMIN, MAX_USER_CONNECTIONS)
- Percona Blog: Preventing MySQL Error 1040: Too Many Connections