Skip to content

perf(fetch): avoid duplicate makeRequest and defer Request signal linking - #6260

Open
mjackson wants to merge 1 commit into
nodejs:mainfrom
mjackson:mjackson/optimize-fetch-request-webidl
Open

mjackson wants to merge 1 commit into
nodejs:mainfrom
mjackson:mjackson/optimize-fetch-request-webidl

Conversation

@mjackson

@mjackson mjackson commented Nov 26, 2026 •

Copy link
Copy Markdown

Background

While profiling Node.js HTTP servers built on the Web Fetch API (such as @remix-run/node-fetch-server, which constructs a native new Request(url, { method, headers, signal, body }) for every incoming HTTP request), two hot-path allocations stood out in Request construction:

  1. createDependentSignal() runs eagerly in the Request constructor even when request.signal is never read, allocating a second AbortController, WeakRef, WeakMap entries, FinalizationRegistry registration, and addAbortListener / removeEventListener churn on GC.
  2. When input is a string, the Request constructor calls makeRequest() twice — allocating and immediately discarding a 40-property internal request object, a HeadersList, a Map, and a urlList array on every call.

Both optimizations preserve Undici's HTTP client behavior and also speed up client fetch() calls.

Summary of changes

  • Lazy dependent AbortSignal in Request (lib/web/fetch/request.js, lib/web/fetch/index.js):
    • Store #sourceSignal in the Request constructor and defer createDependentSignal() until request.signal is accessed via a private #getSignal() helper (avoiding public getter interception when copying or cloning).
    • If the source signal aborts before request.signal is read, accessing request.signal still materializes an already-aborted signal with the original reason.
    • In fetch(), check hasRequestSignal(requestObject) before registering abort listeners so signal-less client fetch(url) calls skip AbortController and addAbortListener setup as well.
  • Avoid duplicate makeRequest() and HeadersList allocations in Request (lib/web/fetch/request.js):
    • Construct the internal request record once for string inputs instead of calling makeRequest() twice.
    • For Request inputs, skip cloning input.#state.headersList when init.headers replaces it immediately in step 32, and skip materializing input.#getSignal() when init.signal overrides it.

Benchmarks

Measured on Apple M5 Pro, Node.js v24.18.0 (150k iterations per benchmark, with global.gc() between runs):

Benchmark main This PR Speedup
new Request(url) 0.301 µs 0.207 µs 1.45x (-31.2%)
new Request(url, { method, headers }) 0.848 µs 0.691 µs 1.23x (-18.5%)
new Request(url, { method, headers, signal }) 2.227 µs 0.717 µs 3.11x (-67.8%)

@mjackson
mjackson force-pushed the mjackson/optimize-fetch-request-webidl branch from 147f9fe to 9a1cd59 Compare November 26, 2026 02:29
@mjackson mjackson changed the title perf(fetch): optimize Request construction, lazy signal linking, readAllBytes, and WebIDL converters perf(fetch): optimize Request construction, lazy signal linking, and WebIDL converters Nov 26, 2026

@mcollina mcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

I know that probably @KhafraDev would object to some of those. This might take a while to land.

cc @jasnell

@codecov-commenter

codecov-commenter commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.67442% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.78%. Comparing base (245306d) to head (9fa7fab).
⚠️ Report is 11 commits behind head on main.

Files with missing lines Patch % Lines
lib/web/fetch/request.js 97.24% 4 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #6260   +/-   ##
=======================================
  Coverage   91.77%   91.78%           
=======================================
  Files         113      113           
  Lines       44884    44927   +43     
=======================================
+ Hits        41194    41236   +42     
- Misses       3690     3691    +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@KhafraDev

Copy link
Copy Markdown
Member

I object to all of them, actually. If the intent is for Claude to maintain undici in perpetuity...

@mjackson mjackson changed the title perf(fetch): optimize Request construction, lazy signal linking, and WebIDL converters perf(fetch): avoid duplicate makeRequest and defer Request signal linking Nov 26, 2026
@mjackson
mjackson force-pushed the mjackson/optimize-fetch-request-webidl branch from 9a1cd59 to 9fa7fab Compare November 26, 2026 23:15
@tsctx

tsctx commented Nov 28, 2026

Copy link
Copy Markdown
Member

-1.

This PR defers signal registration, but the relationship between the source signal and the child signal needs to be weak in both directions to avoid memory leaks. Once weak references are introduced, the cost appears to be roughly equivalent to the current implementation. If so, it is unclear what practical benefit this PR would provide.

@mcollina

Copy link
Copy Markdown
Member

-1.

This PR defers signal registration, but the relationship between the source signal and the child signal needs to be weak in both directions to avoid memory leaks. Once weak references are introduced, the cost appears to be roughly equivalent to the current implementation. If so, it is unclear what practical benefit this PR would provide.

I might be wrong, but I though our tests cover the leaks, or maybe not with a signal?

This PR does also avoid a few bits of data copying, isn’t that worth doing?

@mcollina

Copy link
Copy Markdown
Member

I checked whether the abort-listener leak protection from #5285 is still covered with this change. Behaviour looks right: listener counts on the caller's signal match main for URL and Request inputs, success, network error, redirect and cancelled bodies.

Coverage is thin, though. Only test/fetch/issue-5285.js fails if removeRequestAbortListener(requestObject) is dropped from fetch()'s cleanup, and it only exercises fetch(url, { signal }) on the success path. Nothing goes through the Request-input path this PR changes (input.#getSignal()) via fetch().

I opened #6269 with tests for:

  • a failed fetch leaving no listener on the signal
  • fetch(request) removing its follower from request.signal
  • fetch(request) still rejecting when the source aborts before request.signal is read

They pass on main and on this branch. Feel free to pull them in here if you prefer.

@tsctx

tsctx commented Nov 29, 2026

Copy link
Copy Markdown
Member

This PR does also avoid a few bits of data copying, isn’t that worth doing?

I do not think that alone justifies the change unless the performance improvement can be achieved in a maintainable way without violating the specification.

I checked whether the abort-listener leak protection from #5285 is still covered with this change. Behaviour looks right: listener counts on the caller's signal match main for URL and Request inputs, success, network error, redirect and cancelled bodies.

Coverage is thin, though. Only test/fetch/issue-5285.js fails if removeRequestAbortListener(requestObject) is dropped from fetch()'s cleanup, and it only exercises fetch(url, { signal }) on the success path. Nothing goes through the Request-input path this PR changes (input.#getSignal()) via fetch().

I opened #6269 with tests for:

* a failed fetch leaving no listener on the signal

* `fetch(request)` removing its follower from `request.signal`

* `fetch(request)` still rejecting when the source aborts before `request.signal` is read

They pass on main and on this branch. Feel free to pull them in here if you prefer.

Sorry, but that is not what I meant. The test added in #6269 does not cover this point. That test is fine as it is, so there is no need to add another one.

What I was referring to is the fact that AbortSignal.any is bidirectional and uses weak references, as well as the design intent behind that. I hope this clarifies the distinction, but please let me know if it is still unclear.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants