Repository navigation
perf(client): replace per-command AbortSignal timeouts with deadline lists - #3618
Conversation
…lists Every command with a timeout (the default since [email protected]) created its own AbortSignal.timeout() and listener, which costs up to half the throughput under load and hundreds of MB of memory. The queue now keeps deadlines in CommandDeadlines: one list per timeout value with one timer per list. Adding a deadline is a push, ending one is a field write, and the timer only takes ended and expired entries from the head of its list. Behavior and errors are unchanged.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4663f6aa1e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
The deadline lists were singly linked, so an ended timeout stayed in its list as a dead entry until it reached the head. After an abort in the middle of a list, every later entry stayed too, and so did the old entries left by a maintenance re-add or a move to another queue. They lasted up to one timeout. The lists are now doubly linked, and ending, replacing or detaching a timeout unlinks its entry at once. Every entry in a list is live, so trim() and the liveness checks in the timer go away. The closed-loop benchmark shows no measurable cost.
prependCommandsToWrite() adopted moved commands one at a time, newest first, and each insert walked the deadline list from its head. When the destination already held M commands with older deadlines, moving N commands took M x N steps in one synchronous run: 20k into 20k blocked the event loop for about 2.7 s, 50k into 50k for about 17 s. adoptAll() now takes all moved commands oldest first and resumes each insert where the previous one stopped, so each list is merged in one walk (about 4 ms and 12 ms for the cases above). It runs no callback, so the queue rejects expired and aborted commands only after the merge.
A list's timer stays armed after the timeouts in it end. Only flushAll() stopped the timers, and close() and QUIT never call it. The armed timer kept the queue, and the client that owns it, from being collected until it fired, which can be hours with a long command timeout. Every shutdown path ends in the socket's 'end' event, so the client now stops the timers there when no command is left.
The deadline code replaced AbortSignal.timeout(), and with it the errors that Node threw for an invalid timeout. Its own errors had no `code` (ERR_OUT_OF_RANGE, ERR_INVALID_ARG_TYPE) and different messages. On an invalid timeout it now calls AbortSignal.timeout(), so the command rejects with the same error as before. Valid timeouts never take this path.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b147a3db60
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| list.timer = setTimeout( | ||
| this.#onTimer, |
There was a problem hiding this comment.
Detach shared deadline timers from request async contexts
When commands are issued under AsyncLocalStorage and the write queue remains nonempty at timer firings, this timer captures the first command's request store, and #onTimer propagates that same store whenever it rearms. Consequently, a completed request, including any buffered payload, can remain reachable for the lifetime of a busy client rather than just its command timeout. In a Node 24 queue-only forced-GC reproduction with 60 ms timeouts and commands drained and resolved every 5 ms, the first store remained reachable after 350 ms, while it was collected on the parent. Arm shared timers outside caller async contexts so completed requests can release their stores.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6b0bc70. Every timer is now created through setDetachedTimeout, a setTimeout wrapper bound with AsyncResource.bind when the module loads. A timer no longer takes the context of whoever armed it, so a rearm from the handler no longer passes the first caller's stores on. A spec checks that the callback sees no store, both on the first fire and after a rearm. Benchmarks before and after are the same within noise; the wrapper costs about 45 ns per arm.
A timer keeps the AsyncLocalStorage stores of the code that creates it. A list's timer serves the commands of many callers, and the handler arms the next timer from inside the last one, so the first caller's stores stayed reachable for as long as the list stayed busy. Create every timer through a function bound at module load instead.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6b0bc70d8d
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const setDetachedTimeout = AsyncResource.bind( | ||
| <T>(callback: (list: DeadlineList<T>) => void, ms: number, list: DeadlineList<T>) => | ||
| setTimeout(callback, ms, list) | ||
| ); |
There was a problem hiding this comment.
Avoid retaining the context of a lazy module load
If the package is first require()d inside an AsyncLocalStorage.run() request, this binding captures that request's stores rather than an empty context. The module-global function then keeps the request and its payload reachable while the module remains cached; clearing deadlines or closing every client cannot release it. Unlike the earlier per-command timer leak, a Node 24 forced-GC reproduction retains an 8 MB store merely by loading client/index.ts, before creating any client or deadline, whereas the pre-binding implementation releases it. Avoid retaining an arbitrary module-loading request in a permanent binding.
Useful? React with 👍 / 👎.
…lists (backport #3618) (#3629) Every command with a timeout created its own AbortSignal.timeout() and listener, which costs up to half the throughput under load and hundreds of MB of memory. The queue now keeps deadlines in CommandDeadlines: one list per timeout value with one timer per list. The client stops the timers when the socket ends and no command is left. Behavior and errors are unchanged. The cherry-pick conflicts in commands-queue.ts, so the queue changes are applied by hand to the 5.x queue: - A command moved to another queue (cluster slot migration) takes its deadline with it, so it times out in its new queue. - An abort ends the command's deadline, and a timeout removes its abort listener, so the second one no longer removes the node again. commands-queue.spec.ts holds only the tests that #3618 added. (cherry picked from commit 2f1e7d9)
This pull request improves the performance of command timeouts. Since
[email protected]every command has a 5 s timeout by default (#3292). Until now each one created its ownAbortSignal.timeout()with a listener, and that is expensive under load. Against the same client withtimeout: 0, throughput drops by 22% at 10 commands in flight and 54% at 1000. p99 at 100 in flight goes from 0.18 to 1.76 ms, and peak memory at 10 in flight grows from 144 to 648 MB.The queue now keeps command deadlines in a new internal module,
CommandDeadlines(client/command-deadlines.ts):Closed-loop benchmark, default timeout, change against
timeout: 0:p99 and peak memory are back at the no-timeout level (0.186 ms at 100 in flight; 148 MB at 10 in flight).
Behavior is unchanged: a timeout still covers only the wait to be sent, and the same errors are thrown (
TimeoutError,CommandTimeoutDuringMaintenanceError). Invalidtimeoutvalues are still rejected withTypeError/RangeError, but the error no longer carries Node'scodeproperty. Timeouts never fire early, and can fire up to about 1 ms late from timer rounding. No public API changes.Note
Medium Risk
Touches core queue timeout and cluster command migration paths; behavior is heavily tested but is timing-sensitive infrastructure on every command send.
Overview
Replaces per-command
AbortSignal.timeout()listeners in the Redis write queue with a new internalCommandDeadlinesscheduler: one sorted deadline list and one sharedsetTimeoutper timeout value, with detached timers viaAsyncResource.bindso callbacks don’t retain caller async context.RedisCommandsQueuenow tracks timeouts viatimerEntry/effectiveTimeout/wasInMaintenanceinstead of abort-signal timeout objects. Deadlines end when a command is sent, are detached/adopted on cluster queue moves (prependCommandsToWrite), andclear/clearDeadlinesIfEmptywhen the queue is empty (including on socketendin the client). Semantics stay the same—timeout only while waiting to write, sameTimeoutError/CommandTimeoutDuringMaintenanceError—with large benchmark wins under many in-flight commands.Adds
command-deadlines.ts(+ unit tests) and expandscommands-queue.spec.tsfor timeout, maintenance, and migration behavior.Reviewed by Cursor Bugbot for commit 6b0bc70. Bugbot is set up for automated code reviews on this repo. Configure here.