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
| Option | Where it's set | Default | Clock starts | Clock stops | What fires | What the caller gets |
|---|---|---|---|---|---|---|
connectTimeout | Connection, pool and cluster node config | 10000 ms (0 turns it off) | The connection object is created | Login completes, or the connection fails or closes | A client timer | Fatal ETIMEDOUT error, socket destroyed |
timeout | query() and execute() options only | None | The command is sent to the server | The whole reply has arrived | A client timer | PROTOCOL_SEQUENCE_TIMEOUT, not fatal. The statement keeps running on the server |
idleTimeout with maxIdle | Pool config | 60000 ms, and maxIdle equal to connectionLimit | The connection is released to the pool | The connection is acquired again | A sweep once a second, only when maxIdle is lower than connectionLimit | Nothing. The idle connection is closed quietly |
waitForConnections and queueLimit | Pool config | true and 0 (no limit) | - | - | No timer: waiting for a pool connection has no time limit | No connections available. or Queue limit reached., at once |
restoreNodeTimeout with removeNodeErrorCount | Pool cluster config | 0 (remove the node for good) and 5 | The node is taken offline | restoreNodeTimeout has passed | The node's error count reaching removeNodeErrorCount | 'offline' or 'remove' event, then POOL_NONEONLINE or POOL_NOEXIST if no node is left |
enableKeepAlive and keepAliveInitialDelay | Connection and pool config | true, and the operating system's delay | The socket goes idle | Any traffic | The operating system's TCP stack | A 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:
10000ms.0turns the timer off.
On expiry, MySQL2 destroys the socket and raises a fatal error:
| Property | Value |
|---|---|
message | 'connect ETIMEDOUT' |
code | 'ETIMEDOUT' |
errorno | 'ETIMEDOUT' |
syscall | 'connect' |
fatal | true |
Where the error lands:
createConnection()frommysql2/promiserejects with it.pool.getConnection(),pool.query()andpool.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 whatconnection.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:
- promise.js
- callback.js
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
}
}
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
});
connection.query(
{
sql: 'SELECT * FROM `orders` WHERE `status` = ?',
values: ['pending'],
timeout: 2000,
},
(err, rows) => {
if (err && 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()orexecute().- 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: 300queued behind aSELECT 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.
- 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
- 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:
| Property | Value |
|---|---|
message | 'Query inactivity timeout' |
code | 'PROTOCOL_SEQUENCE_TIMEOUT' |
errorno | 'PROTOCOL_SEQUENCE_TIMEOUT' |
syscall | 'query' |
fatal | not 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
INSERTthat 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()andpool.execute()return the connection to the pool only once the server has finished, so that pool slot stays taken until then. If you usepool.getConnection()and callrelease()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.
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
maxIdleis lower thanconnectionLimit.maxIdledefaults toconnectionLimit, so with the defaults the pool never closes an idle connection, whateveridleTimeoutis. - 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 thanmaxIdle, down to none.
- every free connection beyond
- 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
connectTimeoutagain. - By default the socket is closed without
COM_QUIT, so MySQL counts these connections inAborted_clients. WithgracefulEnd: true, the pool sendsCOM_QUITfirst. - 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:
| Setting | Default | Result |
|---|---|---|
waitForConnections: false | true | Fails at once with Error('No connections available.') |
queueLimit reached (if > 0) | 0 | Fails 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, aconnectTimeout, orNo connections available.. Query errors do not count. Each successfulgetConnection()on the node lowers its count by one, so the errors do not need to be consecutive. - When the count reaches
removeNodeErrorCount(default5, and0also means5):- With
restoreNodeTimeoutabove0, 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'. Onlycluster.add()brings it back.
- With
What the caller sees:
- With
canRetry(defaulttrue), each failed attempt emits'warn'with the error, andgetConnection()tries again on a matching node that is still online, possibly the same one. WithcanRetry: 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, orcode: '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 theORDERselector, onegetConnection()can waitremoveNodeErrorCount×connectTimeoutbefore it reaches the next node. LowerconnectTimeoutin 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.
keepAliveInitialDelayis the idle time, in milliseconds, before the operating system sends the first probe. Node.js rounds it down to whole seconds, and0, unset, or anything below1000keeps 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.
| Setting | Server | What it stops | What the client sees |
|---|---|---|---|
max_execution_time (ms), or the /*+ MAX_EXECUTION_TIME(ms) */ hint | MySQL | Read-only SELECT statements, not those inside stored programs | ER_QUERY_TIMEOUT (errno 3024). Not fatal |
max_statement_time (seconds), or SET STATEMENT max_statement_time = N FOR ... | MariaDB | Any statement, except inside stored procedures | errno 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) | Both | A statement waiting for a row lock | ER_LOCK_WAIT_TIMEOUT (errno 1205). Not fatal. Only that statement is rolled back: the transaction stays open |
wait_timeout (seconds, default 28800) | Both | An idle connection: the server closes it | See below |
net_read_timeout (seconds, default 30) | Both | The server waiting for more data from the client in the middle of a command | The server closes the connection: fatal PROTOCOL_CONNECTION_LOST |
net_write_timeout (seconds, default 60) | Both | The server waiting for the client to accept more of the reply | The 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']
);
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...) andcodeset to the number4031. - MariaDB and older MySQL versions just close the socket, and the connection emits a fatal
'error'withcode: '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_timeoutapplies instead only to clients that connect with theCLIENT_INTERACTIVEflag, 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 to | Use |
|---|---|
| Fail fast when the server cannot be reached | connectTimeout |
| Stop a slow statement on the server | MAX_EXECUTION_TIME or max_statement_time |
| Stop waiting for a reply, and let the statement finish | Per-query timeout |
| Not queue forever when the pool is exhausted | queueLimit, waitForConnections: false, or your own timer |
| Close pooled connections nobody is using | maxIdle lower than connectionLimit, with idleTimeout |
| Survive the server closing idle connections | A pool, or an 'error' listener on standalone connections (see wait_timeout) |
| Notice a dead peer on a long-idle connection | enableKeepAlive with keepAliveInitialDelay |
| Take a failing cluster node out of rotation for a while | removeNodeErrorCount with restoreNodeTimeout |
| Stop waiting for a row lock | innodb_lock_wait_timeout |