Node.js says the MySQL server closed the connection
Error: Connection lost: The server closed the connection.Short answer
The error means the MySQL server, or something between it and your app, closed a connection your code still held. The usual causes are an idle timeout on the server, a statement larger than max_allowed_packet, and a server restart or kill. A pool that drops dead connections fixes the first; the server settings fix the rest.
Fix it fast
1Find out which cause you have
Ask the server how long it keeps idle connections, and whether it restarted recently. The two numbers separate most cases.
SHOW VARIABLES LIKE 'wait_timeout'; -- and from a shell: mysqladmin version (shows the server uptime)2Match what you see, then jump to its fix
- 1
The error appears on the first query after a quiet period, for example in the morning or after a lunch break.The server closed an idle connectionFix - 2
The error comes with one specific query, often a large INSERT or a row with a big BLOB or JSON value, every time.A statement or row is bigger than max_allowed_packetFix - 3
Every open connection fails at the same moment, and the uptime shown by mysqladmin version is very low.The server restarted, crashed or killed the threadFix
- 1
What does the error look like?
Error: Connection lost: The server closed the connection.code: 'PROTOCOL_CONNECTION_LOST'Error: read ECONNRESET
Cause 1 of 3
The server closed an idle connection
1Check
MySQL closes a connection that has been idle longer than wait_timeout (eight hours by default). A single long-lived connection object created at start-up will hit this.
SHOW VARIABLES LIKE 'wait_timeout';2Fix
Stop keeping one connection for the life of the process. Use a pool, which discards a dead connection and opens a new one on the next getConnection call. In mysql2, let the pool close idle connections itself before the server does, and keep sockets alive.
import mysql from 'mysql2/promise';
export const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: 10,
maxIdle: 10,
idleTimeout: 60000, // ms; keep this below the server's wait_timeout
enableKeepAlive: true,
keepAliveInitialDelay: 0,
});3Verify
Run a query, wait longer than idleTimeout, then run it again through the same pool.
async function ping() {
const conn = await pool.getConnection();
try { await conn.query('SELECT 1'); } finally { conn.release(); }
}
await ping();
await new Promise(r => setTimeout(r, 90_000));
await ping();Confirmed by dev.mysql.com
Cause 2 of 3
A statement or row is bigger than max_allowed_packet
1Check
When a packet is larger than max_allowed_packet, the server closes the connection. Read the current limit.
SHOW VARIABLES LIKE 'max_allowed_packet';2Fix
Send smaller statements: split a large multi-row INSERT into batches. If you really need bigger values, raise max_allowed_packet on the server (and on the client, if it has its own limit).
# my.cnf, [mysqld] section, then restart MySQL
max_allowed_packet = 128M3Verify
Repeat the failing statement and read the variable again.
SHOW VARIABLES LIKE 'max_allowed_packet';Confirmed by dev.mysql.com
Cause 3 of 3
The server restarted, crashed or killed the thread
1Check
Look at how long the server has been up, and read its error log for a crash or a KILL.
-- and from a shell: mysqladmin version (shows the server uptime)
mysqladmin version2Fix
Find out who or what restarted the server (an upgrade, an out-of-memory kill, a managed-database maintenance window). In the app, treat the error as fatal for that connection only: with a pool the dead connection is dropped and the next call opens a new one, so retry the query once.
async function run(sql, params) {
const conn = await pool.getConnection();
try { return await conn.query(sql, params); } finally { conn.release(); }
}
async function queryWithRetry(sql, params) {
try {
return await run(sql, params);
} catch (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'ECONNRESET') {
return await run(sql, params); // one retry on a fresh connection
}
throw err;
}
}3Verify
Restart MySQL in a test environment and call queryWithRetry again.
sudo systemctl restart mysqlConfirmed by github.com
How do I stop it coming back?
- Use a pool, never one global connection.
- Keep the pool's idle timeout below the server's wait_timeout.
- Add an error listener so a lost connection does not crash the process.
- Retry a read query once on a connection error; do not blindly retry writes.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Databases
NestJS connects to MySQL at ::1 and is refused
Error: connect ECONNREFUSED ::1:3306
::1 is the IPv6 loopback address.
2 causes, each with a fixDatabases
Node.js MySQL: Cannot enqueue Query after a fatal error
code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR'
This error is a symptom, not the problem.
2 causes, each with a fixDatabases
Node.js cannot reach MySQL: connect ETIMEDOUT
code: 'ETIMEDOUT'
ETIMEDOUT on connect means packets to the database port got no answer at all.
4 causes, each with a fixDatabases
MySQL says Too many connections to a Node.js app
Too many connections
MySQL refuses new clients once max_connections slots are in use.
3 causes, each with a fixDatabases
SequelizeUniqueConstraintError: Validation error on insert
Unhandled rejection SequelizeUniqueConstraintError: Validation error
Sequelize sends the insert, MySQL rejects it because a unique column or unique index already holds that value, and Sequelize reports it as SequelizeUniqueConstraintError.
3 causes, each with a fixDatabases
Installing the Airflow MySQL provider fails on pkg-config or mysqlclient
Building the mysqlclient wheel fails during the install
The Airflow MySQL provider depends on mysqlclient, which pip compiles against the MySQL C client library.
2 causes, each with a fix