How to fix ERROR 1040: Too many connections in MySQL

MySQLINTERMEDIATEHIGHUpdated May 20, 2026· 348 views

MySQL Error 1040 occurs when the number of concurrent client connections exceeds the server's max_connections limit. This happens due to insufficient connection limits, poor connection management, slow queries, or traffic spikes. Fix by increasing max_connections, implementing connection pooling, adjusting timeout values, and optimizing queries.

Quick fix

Fixes 1040

-- Show current connection limit
SHOW VARIABLES LIKE 'max_connections';

-- Show maximum connections used since server startup
SHOW STATUS LIKE 'Max_used_connections';

-- Show current active connections
SHOW PROCESSLIST;

-- Get a count of connections by state
SHOW PROCESSLIST;
SELECT state, COUNT(*) FROM information_schema.processlist GROUP BY state;
  1. Check current connection usage and limits
  2. Increase max_connections temporarily to restore service
  3. Make max_connections increase permanent
  4. Reduce timeout values to close idle connections faster
mysql — error
-- Show current connection limit
SHOW VARIABLES LIKE 'max_connections';
-- Show maximum connections used since server startup
SHOW STATUS LIKE 'Max_used_connections';
-- Show current active connections
SHOW PROCESSLIST;
-- Get a count of connections by state
SHOW PROCESSLIST;
SELECT state, COUNT(*) FROM information_schema.processlist GROUP BY state;
ERROR 1040: Too many connections

What this error means

MySQL Error 1040 (SQLSTATE 08004) is triggered when a client attempts to establish a new connection to the MySQL server but the current number of active connections has already reached the max_connections limit. The server refuses the connection to protect itself from resource exhaustion. The MySQL server pre-allocates memory (1-10 MB per connection depending on buffer settings) for each active connection. When the max_connections threshold is breached, no new connections are accepted until existing connections close. This error is a safety mechanism—allowing unlimited connections would eventually exhaust server memory and crash the database. Unlike transient network errors, Error 1040 indicates a capacity problem that requires either increasing server resources, optimizing connection usage, or implementing connection pooling. The error manifests immediately on connection attempts and cannot be retried successfully until underlying conditions improve.

Typical symptoms

  • Applications fail to connect with "ERROR 1040 (HY000): Too many connections"
  • Connection timeouts in application connection pools or ORM frameworks
  • Intermittent connection failures during traffic spikes, with success resuming once traffic drops
  • Web server or application logs show increasing numbers of failed database connection attempts
  • SHOW PROCESSLIST shows a large number of "Sleep" state connections, suggesting connections are not being closed properly
  • Database becomes unresponsive or extremely slow even though CPU and memory appear adequate
  • Replication lag on database replicas due to master connection exhaustion

Common causes

  1. The max_connections parameter is set too low for the application workload (default is 151, often insufficient for production)
  2. Application or connection pool not closing connections properly, leading to accumulated open connections
  3. Connection timeout values (wait_timeout, interactive_timeout) are too long, keeping idle connections alive for hours
  4. Slow or long-running queries hold connections open longer than necessary, reducing available slots for new connections
  5. Sudden traffic spike or DDoS attack causing an abnormal surge in connection requests
  6. Database replicas consuming connections without proper management or connection limits
  7. Multiple application instances or services competing for a limited connection pool
  8. Memory constraints preventing the server from handling the configured max_connections value

How to fix "ERROR 1040: Too many connections"

1Check current connection usage and limits

First, determine how many connections are currently active and what the limit is.

sql
-- Show current connection limit
SHOW VARIABLES LIKE 'max_connections';

-- Show maximum connections used since server startup
SHOW STATUS LIKE 'Max_used_connections';

-- Show current active connections
SHOW PROCESSLIST;

-- Get a count of connections by state
SHOW PROCESSLIST;
SELECT state, COUNT(*) FROM information_schema.processlist GROUP BY state;

If Max_used_connections is close to max_connections, you are running near capacity. If you see many "Sleep" connections, check the wait_timeout setting.

2Increase max_connections temporarily to restore service

For immediate relief, increase the limit at runtime (changes persist until next restart).

sql
-- Check current limit
SHOW VARIABLES LIKE 'max_connections';

-- Increase temporarily (no restart required)
SET GLOBAL max_connections = 500;

-- Verify the change
SHOW VARIABLES LIKE 'max_connections';

This allows new connections immediately. However, verify that your server has enough memory. As a rough estimate, each connection uses 1-10 MB. For 500 connections, budget 5-50 GB of RAM.

3Make max_connections increase permanent

Locate and edit the MySQL configuration file to persist the change across restarts.

bash
# On Linux/Unix, find the config file:
# /etc/mysql/mysql.conf.d/mysqld.cnf (Debian/Ubuntu)
# /etc/my.cnf (CentOS/RHEL, generic)
# /usr/local/mysql/etc/my.cnf (macOS with Homebrew)

# Edit the config file:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

# Find the [mysqld] section and add or modify:
[mysqld]
max_connections = 500

# Save and exit (Ctrl+X, Y, Enter in nano)

# Restart MySQL to apply:
sudo systemctl restart mysql
# or on macOS:
brew services restart mysql

# Verify the change persisted:
mysql -u root -p -e "SHOW VARIABLES LIKE 'max_connections';"

Choose a value appropriate for your workload. Start with 500-1000 for typical applications, or 2000+ for high-concurrency systems.

4Reduce timeout values to close idle connections faster

Idle connections waste capacity. Reduce wait_timeout and interactive_timeout to close connections that are no longer in use.

sql
-- Check current timeouts (default is 28800 seconds = 8 hours)
SHOW VARIABLES LIKE 'wait_timeout';
SHOW VARIABLES LIKE 'interactive_timeout';

-- Set shorter timeouts at runtime (300 seconds = 5 minutes)
SET GLOBAL wait_timeout = 300;
SET GLOBAL interactive_timeout = 300;

-- Verify:
SHOW VARIABLES LIKE '%timeout%';

Make the change permanent in your config file:

ini
[mysqld]
wait_timeout = 300
interactive_timeout = 300

Then restart MySQL. This aggressively closes idle connections, freeing capacity for new ones.

5Implement connection pooling in your application

Connection pooling reuses connections instead of creating new ones, dramatically reducing the connection count.

For Node.js (MySQL2):

javascript
const pool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'mydb'
});

For Python (SQLAlchemy):

python
engine = create_engine(
  'mysql+pymysql://root:password@localhost/mydb',
  pool_size=10,
  max_overflow=20,
  pool_pre_ping=True
)

For Java (HikariCP):

java
HikariConfig config = new HikariConfig();
config.setMaximumPoolSize(10);
config.setMinimumIdle(5);
DataSource ds = new HikariDataSource(config);

Start with a pool size of 10-20 and monitor connection usage. Always close connections explicitly after queries complete.

6Identify and optimize slow queries

Long-running queries hold connections open, reducing available slots. Enable and monitor the slow query log.

sql
-- Enable slow query logging at runtime
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2; -- Log queries taking >2 seconds
SET GLOBAL log_queries_not_using_indexes = 'ON';

-- Make permanent in config file:
[mysqld]
slow_query_log = 1
long_query_time = 2
log_queries_not_using_indexes = 1
slower_log_file = /var/log/mysql/slow.log

After running for a few hours, analyze the slow query log:

bash
# Install mysqldumpslow if needed
sudo apt-get install mysql-server

# Analyze slow queries
mysqldumpslow /var/log/mysql/slow.log | head -20

Add indexes to frequently run slow queries, or refactor queries to use existing indexes.

7Kill long-running connections to free capacity

As an emergency measure, terminate sleeping or long-running connections to free capacity.

sql
-- Show all connections
SHOW PROCESSLIST;

-- Kill a specific connection by ID
KILL CONNECTION 12345;

-- Kill all connections except the one executing this command
SELECT GROUP_CONCAT(CONCAT("KILL ", id)) FROM information_schema.processlist WHERE id != CONNECTION_ID() AND command != "Sleep";

-- Run the output of the above, or use a script:
KILL 101;
KILL 102;
KILL 103;

Warning: Only use this for troubleshooting. Killing connections can disrupt transactions. A better long-term fix is connection pooling.

Advanced notes

In MySQL 8.0.14+, enable the admin connection feature which reserves one extra connection for users with CONNECTION_ADMIN privilege. This allows DBAs to connect and investigate even when all regular connections are exhausted: SET GLOBAL admin_address = '127.0.0.1'; SET GLOBAL admin_port = 33062;

For connection pool exhaustion in application frameworks, ensure connections are returned to the pool after use. Common mistakes include not closing result sets, exceptions breaking the return path, or queries that wait for locks. Use tools like pgBouncer or ProxySQL as a middleware multiplexer to convert many application connections into fewer database connections.

On shared hosting or cloud databases, check platform-imposed limits. AWS RDS has limits based on instance size, and some managed services cap connections lower than the server's configured max_connections.

Monitor connections using this query for long-term capacity planning:

sql
SELECT COUNT(*) as active_connections FROM information_schema.processlist WHERE command != 'Sleep';

If you consistently approach 80% of max_connections, increase the limit further or investigate architectural changes (read replicas, connection pooling, microservices).

Frequently asked questions

What does "1040" mean?
MySQL Error 1040 (SQLSTATE 08004) is triggered when a client attempts to establish a new connection to the MySQL server but the current number of active connections has already reached the max_connections limit. The server refuses the connection to protect itself from resource exhaustion. The MySQL server pre-allocates memory (1-10 MB per connection depending on buffer settings) for each active connection.
How do I fix "1040"?
MySQL Error 1040 occurs when the number of concurrent client connections exceeds the server's max_connections limit. This happens due to insufficient connection limits, poor connection management, slow queries, or traffic spikes. Fix by increasing max_connections, implementing connection pooling, adjusting timeout values, and optimizing queries.
What causes "1040"?
The max_connections parameter is set too low for the application workload (default is 151, often insufficient for production) Application or connection pool not closing connections properly, leading to accumulated open connections Connection timeout values (wait_timeout, interactive_timeout) are too long, keeping idle connections alive for hours
Is the "1040" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading