Design proposal: queue timeouts for MULTI and pipelines
Description
commandOptions.timeout expires a standalone command while it waits for a connection, but queued commands submitted through multi().exec() and multi().execAsPipeline() remain pending. This issue proposes a timeout design for agreement before implementation. Related context: https://github.com/redis/node-redis/pull/3501.
Measured reproduction:
const assert = require('node:assert/strict');
const net = require('node:net');
const { setTimeout: delay } = require('node:timers/promises');
const { createClient } = require('@redis/client');
(async () => {
const reservation = net.createServer();
await new Promise(resolve => reservation.listen(0, '127.0.0.1', resolve));
const port = reservation.address().port;
await new Promise(resolve => reservation.close(resolve));
const client = createClient({
socket: { host: '127.0.0.1', port, reconnectStrategy: () => 10 },
commandOptions: { timeout: 100 }
});
client.on('error', () => {});
const connecting = client.connect().catch(() => {});
const outcomes = { ping: 'pending', exec: 'pending', pipeline: 'pending' };
function observe(name, promise) {
return promise.then(
() => { outcomes[name] = 'resolved'; },
error => { outcomes[name] = error.constructor.name; }
);
}
const operations = [
observe('ping', client.ping()),
observe('exec', client.multi().ping().exec()),
observe('pipeline', client.multi().ping().execAsPipeline())
];
try {
await delay(500);
console.log(JSON.stringify(outcomes));
assert.equal(outcomes.ping, 'TimeoutError', 'standalone positive control');
assert.equal(outcomes.exec, 'TimeoutError', 'MULTI should respect the timeout');
assert.equal(outcomes.pipeline, 'TimeoutError', 'pipeline should respect the timeout');
} finally {
client.destroy();
await Promise.all([...operations, connecting]);
}
})().catch(error => {
console.error(error.message);
process.exitCode = 1;
});
Observed JSON after 500 ms: {"ping":"TimeoutError","exec":"pending","pipeline":"pending"}. The standalone positive control passes. The assertion that MULTI respects the timeout fails.
Proposed design for discussion:
- Match the existing standalone queue timeout. Resolve timeout options when the batch is admitted, use one shared timer, and stop it before writing the first command.
- If the deadline passes while the whole batch is still queued, remove the complete chain and reject it with TimeoutError. Preserve WATCH state on the same connection so the caller can retry or UNWATCH.
- Once writing starts, do not cancel the batch on this deadline. Finish the chain and consume its replies, including after a partial write. Closing the connection for one timed-out batch would also fail unrelated in-flight commands, so I propose leaving that out of this queue-only timeout.
- Keep WATCH tied to its connection and check that identity again immediately before the first write. A connection loss must not replay a started transaction or allow a transaction to use WATCH from the old connection. Later maintenance timeout updates must adjust an unwritten batch's shared timer, preserve maintenance-specific errors, and never restart the timer after writing begins. Preserve timeout opt-outs. Before submitting an implementation, benchmark warmed PING batches against master with matching batch sizes and timeout settings, including disabled timeouts.
Does this queue-only scope fit, or should batch deadlines also cover commands that have started writing?
Node.js Version
v22.23.3
Redis Server Version
Not applicable. No Redis server accepts connections on the dynamically selected loopback port in this reproduction.
Node Redis Version
6.4.0-beta.0, master commit 255bd33.
Platform
Linux x86_64
Thanks for writing this up. It answers the questions from #3501 well.
Queue-only scope fits. It matches how a single command's timeout works today: the timer stops once the command is written. Cancelling a batch that has started writing would need a way to throw away its replies, or a closed connection, and both are out of scope here.
The shared timer and keeping WATCH state on a queue timeout both sound right. Before you start on code, please cover these points in the design:
- Cluster, sentinel and pool. These call the inner client's
_executeMulti/_executePipelineand do not pass their owncommandOptionsdown. The timeout should apply there too. - Per-call options. Say how
withCommandOptions({ timeout })andabortSignalapply to a batch. - Ordering with #3507. That PR changes the start of
_executeMultitoo. Please build on top of it once it lands. - Benchmark. Include the numbers you described in the PR, with timeouts on and off.
- Behavior change. With the 5 s default, a batch that waits through a reconnect will now reject where it used to resolve. Please note this in the PR description so it goes into the release notes.
Once these are settled, go ahead with the PR.
Thanks, @nkaradzhov. I propose:
-
Forward cluster, Sentinel and pool options to the inner batch executors, merging inner defaults, wrapper defaults, then per-call overrides. Sentinel cancellation would be terminal. Relocation would carry cancellation state and the original deadline, preventing cancelled batches from being re-enqueued. WATCH would survive pre-admission rejection and queue timeout on its original connection and held lease. Watched batches would not relocate. Use the existing
resetIfDirty()cleanup to clear retained WATCH before returning the lease to another borrower. -
withCommandOptions({ timeout, abortSignal }).multi()would govern bothexec()andexecAsPipeline(). Explicittimeout: 0ortimeout: undefinedwould disable normal timeouts. Validate options and pre-abort before admission. One timer and one abort listener, when requested, would start at inner queue admission. Pool acquisition stays separate. Cancellation would remove the whole unwritten batch atomically. Immediately before first write, I would recheck WATCH connection/session identity and generation, then detach cancellation. ASKING would belong to the unit, with its first write starting it. Started batches would finish and consume replies. Maintenance updates would adjust one unwritten batch timer, retain priority and maintenance-specific errors, and never re-arm a started batch. -
Build on #3507 after it lands, with its capacity check inside the traced callback before timer setup and admission, counting ASKING too.
-
Fresh medians in milliseconds for 10,000 PINGs, including construction and replies. Each cell uses a separate process, five warmups and nine samples, on Node v22.23.3 and Redis 8.4.0.
| Revision | Pipeline, 0 ms | Pipeline, 5000 ms | MULTI, 0 ms | MULTI, 5000 ms |
|---|---|---|---|---|
Original base 3b65aff |
24.5 | 30.0 | 26.2 | 24.9 |
Withdrawn PR d277cea |
25.7 | 70.9 | 23.1 | 56.8 |
Current master 1cef9d3 |
24.4 | 23.8 | 26.3 | 22.0 |
Base and current master ignore the normal timeout option in these benchmarks. The withdrawn PR uses per-command timers. The proposed shared-timer implementation has not been measured.
- The PR description and release notes would warn that the 5 s default will reject wholly unwritten batches during reconnect, which currently wait and resolve after reconnection.
timeout: 0ortimeout: undefinedopts out. Started batches would remain outside this deadline.
Thanks — this covers all five points, and the direction looks good.
A few notes before you start:
- Sentinel retries. Please drop the "terminal" cancellation for sentinel. Today, when a command on the master times out while the connection is down, sentinel rediscovers the master and retries it with a new timer. Single commands already behave this way, and we don't want to change that here. Batches should follow the same rule.
- Two PRs. First: the batch timeout for the standalone client (
_executeMulti/_executePipeline), with per-calltimeoutandabortSignal. Second: cluster, sentinel and pool. - Benchmark. Please include the same benchmark for the shared-timer implementation in the first PR.
- Base. #3506 has landed and changes how WATCH is cleared when the connection is lost. Please build on it, and on #3507 once that lands.
No need for another design round — go ahead with the first PR.