Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Databases and Redis

Node.js says the MySQL server closed the connection

ErrorError: 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.

  • Applies to Node.js 22, mysql 2.18 (mysqljs), mysql2 3.x, MySQL 8.4
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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)
  2. 2Match what you see, then jump to its fix

    1. 1The 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. 2The 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. 3Every 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

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

Did this fix it?

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 = 128M

3Verify

Repeat the failing statement and read the variable again.

SHOW VARIABLES LIKE 'max_allowed_packet';

Confirmed by dev.mysql.com

Did this fix it?

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 version

2Fix

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 mysql

Confirmed by github.com

Did this fix it?

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:

Related fixes

Databases

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 fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.