Your Node.js app runs fine for days. Then a busy hour arrives, like an event registration opening or a newsletter going out, and the logs fill with Error: Too many connections. The MySQL too many connections error is rarely a database problem. It is almost always the app opening connections faster than it gives them back.
This bug-log entry covers why it happens, the pattern I use in every Node.js project now, and how to watch connections live so you know the fix worked.
Why MySQL says "too many connections"
MySQL has a hard ceiling, max_connections. The default on a fresh install is usually 151, but check your own server. When every slot is taken, new clients get refused, and your API returns 500s even though the database is not busy at all.
In Node.js projects, three causes cover nearly every case I have seen:
- A new connection per request. The handler calls
createConnection(), runs a query and moves on. Under light traffic you never notice. Under load you open hundreds. - Leaks. A connection taken from a pool is never released, usually because an error was thrown before
release()ran. The pool slowly drains until every request waits forever. - Long transactions. A transaction holds its connection until commit or rollback. If you call a payment gateway or send an email in the middle of one, that connection is locked for seconds.
A fourth cause shows up in development: hot reload. Every time nodemon or a framework dev server reloads your module, it can create a fresh pool while the old one stays open.
The anti-pattern to look for
Search your codebase for createConnection. If you find it inside a route handler, you have found the bug:
// Do not do this const mysql = require('mysql2/promise'); app.get('/api/events', async (req, res) => { const conn = await mysql.createConnection({ host: '127.0.0.1', user: 'your-user', password: process.env.DB_PASSWORD, database: 'app_db', }); const [rows] = await conn.query('SELECT id, title FROM events'); res.json(rows); // conn.end() is never called, so the connection stays open }); Even with conn.end() added, opening a TCP connection and authenticating on every request is slow. The fix is not to close connections more carefully. The fix is to stop opening them per request.
One shared mysql2 pool for the whole Node app
A connection pool keeps a fixed number of connections open and lends them out. Create it once, in its own module, and import it everywhere:
// db.js const mysql = require('mysql2/promise'); const pool = mysql.createPool({ host: process.env.DB_HOST || '127.0.0.1', port: Number(process.env.DB_PORT || 3306), user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, waitForConnections: true, connectionLimit: 10, queueLimit: 0, maxIdle: 10, idleTimeout: 60000, enableKeepAlive: true, keepAliveInitialDelay: 0, }); module.exports = pool; Node caches modules, so every require('./db') returns the same pool. A few options worth understanding:
-
connectionLimitis the maximum number of open connections this pool will ever hold. -
waitForConnections: truemeans extra requests queue up and wait instead of failing immediately. -
queueLimit: 0means the queue has no limit. Set a number if you prefer fast failure over long waits. -
maxIdleandidleTimeoutclose idle connections so a quiet app does not hold slots it does not need.
For the hot reload problem in development, store the pool on globalThis so a reload reuses it:
const pool = globalThis.__dbPool || mysql.createPool({ /* same options */ }); if (process.env.NODE_ENV !== 'production') globalThis.__dbPool = pool; module.exports = pool; Releasing connections: pool.query vs getConnection
For single queries, use pool.query() or pool.execute(). They borrow a connection, run the query and return it automatically. You cannot leak with them:
const pool = require('./db'); app.get('/api/events', async (req, res, next) => { try { const [rows] = await pool.query('SELECT id, title FROM events'); res.json(rows); } catch (err) { next(err); } }); You only need pool.getConnection() when several queries must run on the same connection, which mostly means transactions. Then release() goes in finally, always:
async function createBooking(userId, ticketId) { const conn = await pool.getConnection(); try { await conn.beginTransaction(); const [result] = await conn.execute( 'UPDATE tickets SET stock = stock - 1 WHERE id = ? AND stock > 0', [ticketId] ); if (result.affectedRows === 0) throw new Error('Sold out'); await conn.execute( 'INSERT INTO bookings (user_id, ticket_id) VALUES (?, ?)', [userId, ticketId] ); await conn.commit(); } catch (err) { await conn.rollback(); throw err; } finally { conn.release(); } } Notice what is not inside that transaction: no HTTP call to a payment provider, no email. Do the slow external work before or after, and keep the transaction to the database writes only. Short transactions keep connections moving and reduce lock waits too.
Finally, close the pool on shutdown so PM2 restarts do not leave connections hanging:
process.on('SIGINT', async () => { await pool.end(); process.exit(0); }); Choosing connectionLimit (and why PM2 matters)
The number that matters is the total across every process, not the number in one file. If PM2 runs your app in cluster mode with 4 instances and each pool has connectionLimit: 10, the app can open 40 connections. Add cron workers, a queue consumer and your admin tool, and that total grows.
My rule of thumb: add up every pool's limit across every process, add a few for yourself to connect during an incident, and keep that under max_connections with clear headroom. A bigger pool is not automatically faster. If queries are slow, more connections just means more slow queries competing for the same CPU and disk. Fix the slow query first.
If you deploy with PM2 the way I describe in deploying a Node.js app on a VPS with PM2 and Nginx, check pm2 ls to see how many instances you really run before picking a number.
Watching connections live with SHOW PROCESSLIST
On my own VPS, MySQL runs in Docker, so I connect like this:
docker exec -it your-mysql-container mysql -u root -p Then three queries tell you most of the story:
SHOW VARIABLES LIKE 'max_connections'; SHOW GLOBAL STATUS LIKE 'Threads_connected'; SHOW GLOBAL STATUS LIKE 'Max_used_connections'; Threads_connected is how many are open now. Max_used_connections is the peak since MySQL started, which shows how close you got during the last busy period.
To see who holds them:
SHOW FULL PROCESSLIST; Many rows with Command = Sleep and a growing Time value point to leaks or per-request connections nobody closed. Rows stuck in Query with long times point to slow queries or lock waits. For a summary grouped by user and client:
SELECT user, SUBSTRING_INDEX(host, ':', 1) AS client, command, COUNT(*) AS total FROM information_schema.processlist GROUP BY user, client, command ORDER BY total DESC; In an emergency, KILL <id>; ends a single connection, and you can raise the limit temporarily with SET GLOBAL max_connections = 300;. That setting is lost on restart, and each connection uses memory, so treat it as a bandage while you fix the app, not as the fix.
FAQ
Should I just increase max_connections?
Only as a short-term measure. If the app leaks, it will eventually fill any limit you set. Fix the pool and the releases first, then size max_connections to fit the real total.
What is the default connectionLimit in mysql2?
The mysql2 pool defaults to 10 connections. That is a reasonable start for a single process. Multiply by your PM2 instances before you change it.
Is pool.query safe without calling release?
Yes. pool.query() and pool.execute() release the connection themselves. You only call release() on connections you took with getConnection().
Why does the error appear only in production?
Production has real concurrency and more processes. A leak of one connection per error is invisible locally and fatal under load.
Fighting a database error in production and want a second pair of eyes? Talk to the editor at ahmed-adil.com.
Originally published on The Supplement, Ahmed Adil's blog.