Pular para o conteúdo principal

Timeouts

MySQL2 has several options that limit how long something may take. Each one measures something different: connecting, one statement, an idle pooled connection, a failing cluster node. None of the client-side options stops a statement that is already running on the server. For that, use a server-side limit.

Summary​

OptionWhere it's setDefaultClock startsClock stopsWhat firesWhat the caller gets
connectTimeoutConnection, pool and cluster node config10000 ms (0 turns it off)The connection object is createdLogin completes, or the connection fails or closesA client timerFatal ETIMEDOUT error, socket destroyed
timeoutquery() and execute() options onlyNoneThe command is sent to the serverThe whole reply has arrivedA client timerPROTOCOL_SEQUENCE_TIMEOUT, not fatal. The statement keeps running on the server
idleTimeout with maxIdlePool config60000 ms, and maxIdle equal to connectionLimitThe connection is released to the poolThe connection is acquired againA sweep once a second, only when maxIdle is lower than connectionLimitNothing. The idle connection is closed quietly
waitForConnections and queueLimitPool configtrue and 0 (no limit)--No timer: waiting for a pool connection has no time limitNo connections available. or Queue limit reached., at once
restoreNodeTimeout with removeNodeErrorCountPool cluster config0 (remove the node for good) and 5The node is taken offlinerestoreNodeTimeout has passedThe node's error count reaching removeNodeErrorCount'offline' or 'remove' event, then POOL_NONEONLINE or POOL_NOEXIST if no node is left
enableKeepAlive and keepAliveInitialDelayConnection and pool configtrue, and the operating system's delayThe socket goes idleAny trafficThe operating system's TCP stackA fatal network error once the operating system gives up on the peer

connectTimeout​

The time allowed to open a connection and log in: the DNS lookup, the TCP connect, the TLS upgrade when ssl is set, the MySQL handshake and authentication, including any authentication switch.

  • Clock starts: when the connection object is created. For a pool, that is when the pool opens a new connection, so time spent waiting for a free pool connection is not counted.
  • Clock stops: when the handshake finishes, successfully or not, when a network error occurs, or when the connection is closed. It does not apply to anything sent after login.
  • Default: 10000 ms. 0 turns the timer off.

On expiry, MySQL2 destroys the socket and raises a fatal error:

PropertyValue
message'connect ETIMEDOUT'
code'ETIMEDOUT'
errorno'ETIMEDOUT'
syscall'connect'
fataltrue

Where the error lands:

  • createConnection() from mysql2/promise rejects with it.
  • pool.getConnection(), pool.query() and pool.execute() fail with it.
  • With the callback API, commands queued before the handshake finished receive it in their callbacks. With no command queued, the connection emits it as an 'error' event, which is what connection.connect(callback) listens to.

MySQL2 does not retry. The connection cannot be reused: create a new one.

import mysql from 'mysql2/promise';

try {
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
connectTimeout: 5000,
});
} catch (err) {
if (err.code === 'ETIMEDOUT') {
// The server could not be reached, or did not finish the login, within 5 s
}
}

Per-query timeout​

The time allowed for one query() or execute() call to get its whole reply. It is set per call only:

import mysql from 'mysql2/promise';

const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
});

try {
const [rows] = await connection.query({
sql: 'SELECT * FROM `orders` WHERE `status` = ?',
values: ['pending'],
timeout: 2000,
});
} catch (err) {
if (err.code === 'PROTOCOL_SEQUENCE_TIMEOUT') {
// MySQL2 stopped waiting. The statement is still running on the server
}
}

What it measures​

  • Clock starts: when MySQL2 sends the command to the server, not when you call query() or execute().
    • A connection runs one command at a time, so time spent queued behind other commands on the same connection is not counted. A query with timeout: 300 queued behind a SELECT SLEEP(1) succeeds after about one second.
    • Time spent waiting for a pool connection is not counted either.
    • For execute(), preparing the statement is not counted. The clock starts when the prepared statement is executed.
  • Clock stops: when the last packet of the reply arrives, or when the server returns an error.
  • It is not reset when data arrives, despite the word "inactivity" in the error message: it limits the total time of the reply.
  • With .stream(), MySQL2 stops reading from the socket while your consumer is paused, and that time counts too.

What happens on expiry​

The callback, the promise or the stream receives an error. It is not fatal:

PropertyValue
message'Query inactivity timeout'
code'PROTOCOL_SEQUENCE_TIMEOUT'
errorno'PROTOCOL_SEQUENCE_TIMEOUT'
syscall'query'
fatalnot set

After that:

  • Nothing is cancelled on the server. MySQL2 sends nothing to the server, so the statement runs to completion and its changes are applied: an INSERT that timed out on the client still inserts its rows.
  • MySQL2 keeps reading the rest of the reply and discards it. No further result is delivered for that call.
  • The connection stays usable, but it is busy: the next command on it waits until the server has finished the timed-out statement.
  • pool.query() and pool.execute() return the connection to the pool only once the server has finished, so that pool slot stays taken until then. If you use pool.getConnection() and call release() when the timeout error arrives, the connection goes back to the pool at once, and the next user's first command waits behind the running statement.

To stop the statement itself, use a server-side limit.

aviso

timeout is not a connection or pool option. Passed to createConnection() or createPool(), it is ignored, and MySQL2 prints Ignoring invalid configuration option passed to Connection: timeout.


Pool idleTimeout and maxIdle​

These close pooled connections that nobody is using. They do not limit how long a request waits or how long a query runs.

import mysql from 'mysql2/promise';

const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
connectionLimit: 10,
maxIdle: 2, // must be lower than connectionLimit for idleTimeout to apply
idleTimeout: 30000,
});
  • The sweep only runs when maxIdle is lower than connectionLimit. maxIdle defaults to connectionLimit, so with the defaults the pool never closes an idle connection, whatever idleTimeout is.
  • When it runs, the pool checks its free connections once a second. Each check closes, starting with the connection released longest ago:
    • every free connection beyond maxIdle, however briefly it has been idle;
    • every free connection idle for longer than idleTimeout, even if that leaves fewer than maxIdle, down to none.
  • Idle time is counted from the moment a connection is released back to the pool. A connection in use is never closed by the sweep.
  • The pool hands out the most recently released connection first, so under light load the others stay idle and are the ones closed.
  • Closed connections are removed from the pool without any pool event. The next request opens a new connection, which goes through connectTimeout again.
  • By default the socket is closed without COM_QUIT, so MySQL counts these connections in Aborted_clients. With gracefulEnd: true, the pool sends COM_QUIT first.
  • While the sweep is active, its timer keeps the Node.js process alive until pool.end() is called.

Waiting for a pool connection​

pool.getConnection(), pool.query() and pool.execute() take a free connection, or open a new one while fewer than connectionLimit exist. When neither is possible:

SettingDefaultResult
waitForConnections: falsetrueFails at once with Error('No connections available.')
queueLimit reached (if > 0)0Fails at once with Error('Queue limit reached.')
Otherwise-Waits in the queue until a connection is released, or fails with Pool is closed. when the pool ends

Waiting for a pool connection has no time limit, and the per-query timeout does not count it. Neither error above has a code, so match on message.

To bound the wait yourself, make sure a connection that arrives too late goes back to the pool:

function getConnectionWithin(pool, ms) {
return new Promise((resolve, reject) => {
let late = false;
const timer = setTimeout(() => {
late = true;
reject(new Error('Timed out waiting for a pool connection'));
}, ms);

pool.getConnection().then(
(connection) => {
if (late) {
connection.release();
return;
}
clearTimeout(timer);
resolve(connection);
},
(err) => {
clearTimeout(timer);
reject(err);
}
);
});
}

PoolCluster node removal​

removeNodeErrorCount and restoreNodeTimeout decide when a node leaves the rotation, and whether it comes back.

const mysql = require('mysql2');

const cluster = mysql.createPoolCluster({
removeNodeErrorCount: 3,
restoreNodeTimeout: 30000,
});

cluster.add('primary', { host: 'db1', user: 'root', connectTimeout: 2000 });
cluster.add('replica', { host: 'db2', user: 'root', connectTimeout: 2000 });

cluster.on('offline', (nodeId) => console.log(`${nodeId} is offline`));
cluster.on('online', (nodeId) => console.log(`${nodeId} is back`));
cluster.on('remove', (nodeId) => console.log(`${nodeId} was removed`));
  • What counts as an error: a failed getConnection() on that node's pool, for example a connection error, a connectTimeout, or No connections available.. Query errors do not count. Each successful getConnection() on the node lowers its count by one, so the errors do not need to be consecutive.
  • When the count reaches removeNodeErrorCount (default 5, and 0 also means 5):
    • With restoreNodeTimeout above 0, the node goes offline for that many milliseconds and the cluster emits 'offline' with the node id. Once the time has passed, the node is picked again; no event fires at that moment. Its next successful connection emits 'online'. Going offline does not reset the count, so a single failure after it comes back takes it offline again.
    • With restoreNodeTimeout: 0 (the default), the node is removed for good: its pool is ended and the cluster emits 'remove'. Only cluster.add() brings it back.

What the caller sees:

  • With canRetry (default true), each failed attempt emits 'warn' with the error, and getConnection() tries again on a matching node that is still online, possibly the same one. With canRetry: false, each failure goes straight to the caller.
  • When no matching node is left online, the caller gets the last connection error. Later calls fail at once with code: 'POOL_NONEONLINE' (Pool does Not have online node.) while nodes are offline, or code: 'POOL_NOEXIST' (Pool does Not exist.) once they are all removed.
  • Every attempt against a node that does not answer waits a full connectTimeout. With the ORDER selector, one getConnection() can wait removeNodeErrorCount × connectTimeout before it reaches the next node. Lower connectTimeout in the node config for faster failover.

TCP keep-alive​

enableKeepAlive (default true) and keepAliveInitialDelay are not timeouts: MySQL2 runs no timer for them. Once the TCP connection is open, MySQL2 calls socket.setKeepAlive(true, keepAliveInitialDelay). This applies to host/port connections only, not to socketPath or a custom stream.

  • keepAliveInitialDelay is the idle time, in milliseconds, before the operating system sends the first probe. Node.js rounds it down to whole seconds, and 0, unset, or anything below 1000 keeps the operating system's default (two hours on Linux, macOS and Windows).
  • If the peer stops answering the probes, the operating system reports the socket as broken. MySQL2 treats that as a fatal network error, such as ETIMEDOUT: queued commands receive it, or the connection emits 'error', and a pool drops the connection.
  • Keep-alive does not stop the server from closing an idle connection after wait_timeout, and it does not limit how long a query may run.

Server-side limits​

These are enforced by the server, so they are what actually stop work there. The client sees them as ordinary MySQL errors, or as a closed connection.

SettingServerWhat it stopsWhat the client sees
max_execution_time (ms), or the /*+ MAX_EXECUTION_TIME(ms) */ hintMySQLRead-only SELECT statements, not those inside stored programsER_QUERY_TIMEOUT (errno 3024). Not fatal
max_statement_time (seconds), or SET STATEMENT max_statement_time = N FOR ...MariaDBAny statement, except inside stored procedureserrno 1969 (ER_STATEMENT_TIMEOUT), sqlState '70100'. MySQL2 has no code name for it, so match on errno. Not fatal
innodb_lock_wait_timeout (seconds, default 50)BothA statement waiting for a row lockER_LOCK_WAIT_TIMEOUT (errno 1205). Not fatal. Only that statement is rolled back: the transaction stays open
wait_timeout (seconds, default 28800)BothAn idle connection: the server closes itSee below
net_read_timeout (seconds, default 30)BothThe server waiting for more data from the client in the middle of a commandThe server closes the connection: fatal PROTOCOL_CONNECTION_LOST
net_write_timeout (seconds, default 60)BothThe server waiting for the client to accept more of the replyThe server closes the connection: fatal PROTOCOL_CONNECTION_LOST
// MySQL: stop the SELECT on the server after 2 seconds
await connection.query(
'SELECT /*+ MAX_EXECUTION_TIME(2000) */ * FROM `orders` WHERE `status` = ?',
['pending']
);

// MariaDB: stop the statement on the server after 2 seconds
await connection.query(
'SET STATEMENT max_statement_time = 2 FOR SELECT * FROM `orders` WHERE `status` = ?',
['pending']
);
dica

When testing a statement limit with SLEEP() on MySQL, the interrupted SLEEP() returns 1 instead of failing. Use a statement that does real work to see ER_QUERY_TIMEOUT.

When the server closes a connection for wait_timeout:

  • MySQL 8.0.24 and later first send error 4031 (ER_CLIENT_INTERACTION_TIMEOUT). MySQL2 emits it as a fatal 'error' event on the connection, with the server's message (The client was disconnected by the server because of inactivity...) and code set to the number 4031.
  • MariaDB and older MySQL versions just close the socket, and the connection emits a fatal 'error' with code: 'PROTOCOL_CONNECTION_LOST'.
  • Either way, later commands on that connection fail with Can't add new command when connection is in closed state. Listen for 'error' on standalone connections and create a new one. A pool drops the closed connection and opens a new one for the next request.
  • interactive_timeout applies instead only to clients that connect with the CLIENT_INTERACTIVE flag, which MySQL2 does not send by default.

A .stream() consumer that stays paused for longer than net_write_timeout makes the server give up on the reply and close the connection.


Which one do I use?​

You want toUse
Fail fast when the server cannot be reachedconnectTimeout
Stop a slow statement on the serverMAX_EXECUTION_TIME or max_statement_time
Stop waiting for a reply, and let the statement finishPer-query timeout
Not queue forever when the pool is exhaustedqueueLimit, waitForConnections: false, or your own timer
Close pooled connections nobody is usingmaxIdle lower than connectionLimit, with idleTimeout
Survive the server closing idle connectionsA pool, or an 'error' listener on standalone connections (see wait_timeout)
Notice a dead peer on a long-idle connectionenableKeepAlive with keepAliveInitialDelay
Take a failing cluster node out of rotation for a whileremoveNodeErrorCount with restoreNodeTimeout
Stop waiting for a row lockinnodb_lock_wait_timeout