Talk to the NOC, IST hours — +91 75994 50220 support@bigdomainhost.com
Guide

MySQL 'Too many connections' (ERROR 1040): find the cause and fix it

Your site or app suddenly fails with ERROR 1040 (HY000): Too many connections. The server has run out of connection slots, and raising the number is only sometimes the right answer. This guide shows how to get in, see who holds the slots, free them, find the leak and set the limits so it stays fixed.

Short answer: "Too many connections" (ERROR 1040) means MySQL or MariaDB has reached max_connections (151 by default) and refuses new clients. Log in with an admin account (one extra slot is reserved), check Threads_connected and SHOW FULL PROCESSLIST, kill the idle sessions or stop the app that holds them, fix that app, then set wait_timeout and raise max_connections only after checking RAM.

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

  1. Get in. Log in with an admin account. The server keeps one extra slot for it.
  2. Measure. Compare Threads_connected and Max_used_connections with max_connections.
  3. Look. Run SHOW FULL PROCESSLIST and group the connections by user and client.
  4. Free slots. Kill the sleeping connections of the guilty account, or stop the application for a minute.
  5. Fix the cause. Close connections in code, stop persistent connections from multiplying, size the pool, set wait_timeout, and only then raise max_connections after 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_connected is the number of currently open connections, idle ones included.
  • Threads_running is the number of threads that are not sleeping.
  • Max_used_connections is the highest number of simultaneous connections since the server started, and Max_used_connections_time says when that peak was reached.
  • Connection_errors_max_connections counts 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:

Connection-exhaustion patterns, how they look and what to change
What the process list showsLikely causeFix
Many Sleep sessions from one user, each with a large TimeCode opens connections and does not close them, or persistent connections are held by idle workersClose 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 restartLeak 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 ownInstances × pool size is larger than max_connectionsCut 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 dataSlow queries or lock waits keep slots busySlow query log, EXPLAIN, indexes (see the slow queries guide)
Many short connections from the web server at the same momentTraffic or bots hitting uncached pages, each needing a database connectionPage caching, rate limits, and a cap on PHP workers
Dozens of identical statements started at the same minuteCron jobs or scheduled tasks overlapping because the previous run has not finishedGuard 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 to mysqld-auto.cnf in 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, run RESET PERSIST max_connections;.
  • Config file, MySQL or MariaDB: add the setting under [mysqld].
    # MySQL on Ubuntu: /etc/mysql/mysql.conf.d/mysqld.cnf
    # MariaDB on Ubuntu: /etc/mysql/mariadb.conf.d/50-server.cnf
    [mysqld]
    max_connections = 300
    Then restart the service (sudo systemctl restart mysql or sudo systemctl restart mariadb). MariaDB 10.6 and 10.11 do not use SET PERSIST, so the file is the way to keep it there. On Windows the file is my.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_connections defaults to 151, with a range of 10 to 100000, and is dynamic like in MySQL.
  • Reserved slot. One connection is reserved for a SUPER or CONNECTION ADMIN account. Check the privilege names your MariaDB version supports in its GRANT documentation. Root over sudo mysql already has them.
  • Separate admin port. MariaDB can listen on extra_port and cap that port with extra_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-threads enables 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 mariadbd and the service is mariadb.

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

Connection errors that look alike and what each one means
ErrorMeaningWhere to go
1040 Too many connectionsServer-wide limit max_connections reachedThis guide
1203 User ... already has more than 'max_user_connections' active connectionsOne account hit its own limitRaise or fix that account's connections; check max_user_connections
1129 Host ... is blocked because of many connection errorsThe host exceeded max_connect_errors interrupted attemptsFlush the host cache (mysqladmin flush-hosts), then find why connections were interrupted
1045 Access denied for userThe server was reached but rejected the loginAccess denied for user root
2002 or 2003 cannot connectThe 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 awayThe server closed a connection the client still thought was open, for example after wait_timeoutRecycle pooled connections before wait_timeout

Common mistakes

  • Setting max_connections to 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 ends mysqld.
  • Editing the config file and not restarting, or editing a file that SET PERSIST overrides. Always read the running value with SELECT @@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_timeout very low with a pool. The pool then hands out dead connections and the app reports "server has gone away".
  • Using SET GLOBAL wait_timeout and 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 )

Answers

Frequently asked questions

Still unsure? Call +91 75994 50220 or write to support@bigdomainhost.com — a human replies in IST hours.

What does MySQL error 1040 Too many connections mean?

It means the server already has as many open client connections as its max_connections limit allows, so it refuses the next client. The limit counts idle connections too. The default is 151 in MySQL 8.0 and MariaDB, and an admin account can still use one extra reserved slot.

What is the default max_connections in MySQL and MariaDB?

The default is 151 in the MySQL 8.0 manual and in the MariaDB documentation. MySQL accepts values from 1 to 100000 and MariaDB from 10 to 100000. The value can be changed at runtime with SET GLOBAL, but the effective maximum in MySQL is also capped by open_files_limit minus 810.

How do I log in to MySQL when it says too many connections?

Use an account with the CONNECTION_ADMIN or SUPER privilege, because the server reserves one extra connection for it. On Ubuntu, run sudo mysql as root. If that is refused too, the reserved slot is taken, so stop the application that is connecting, wait a few seconds, and log in again.

How do I increase max_connections permanently?

Run SET GLOBAL max_connections = 300 for an immediate change, then make it permanent. On MySQL 8.0 use SET PERSIST, or add max_connections under [mysqld] in the config file and restart the service. MariaDB has no SET PERSIST, so use the config file. Confirm with SELECT @@max_connections.

Does raising max_connections use more memory?

Yes, each connection runs its own thread with a stack, connection and result buffers, and queries allocate sort, join and read buffers when they need them. The real peak depends on what the queries do. Raise the limit in steps and watch free -h and the mysqld memory use.

What is the difference between max_connections and max_user_connections?

max_connections is the server-wide limit and produces error 1040 when it is reached. max_user_connections limits each account and produces error 1203 instead. Its default is 0, which means no per-account limit, and you can also set a limit for one account with ALTER USER ... WITH MAX_USER_CONNECTIONS.

Will lowering wait_timeout fix too many connections?

It helps when the slots are held by idle connections, because the server closes a sleeping connection after wait_timeout seconds. The default is 28800 seconds. A new value applies to new connections only, and pools must recycle connections sooner than the timeout or they will report that the server has gone away.

Can PHP persistent connections cause too many connections?

Yes. Each PHP worker that opens a persistent connection keeps its own, so 50 workers can hold 50 connections even when idle. The PHP manual says the database limit must be higher than the number of web workers, plus cron jobs and admin sessions. Disable persistent connections or lower the worker count.

Support that picks up the phone.

In IST hours, in Hindi or English, and WhatsApp replies fastest at any time. Sales, migration and emergencies all reach the same engineers. No offshore queue, no 48-hour first reply.

Need cPanel or WHM with the ports already sorted?

Web & cPanel hosting comes with cPanel ready to log in to, reseller hosting adds white-label WHM, and a KVM VPS can have cPanel & WHM pre-installed. Call +91 75994 50220 or email support@bigdomainhost.com.