Repository navigation
Conversation
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Workflows to automatically generate PRs for you. |
WalkthroughAdds per-origin HTTP concurrency limits to Bun's fetch layer. ChangesPer-origin HTTP concurrency
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 11:13 AM PT - Jul 23rd, 2026
✅ @robobun, your commit 4a803f47311f9e69450ec7d69c3f2a3e4198f1f8 passed in 🧪 To try this PR locally: bunx bun-pr 33007That installs a local version of the PR into your bun-33007 --bun |
There was a problem hiding this comment.
I didn't find any bugs, but this changes the user-visible semantics of BUN_CONFIG_MAX_HTTP_REQUESTS (per-origin instead of global, with a hardcoded 4× total ceiling) and reworks the HTTP thread's request-scheduling/deferral logic, so it's worth a human sign-off on the design choices.
Extended reasoning...
Overview
This PR changes fetch()'s in-flight request cap from a single process-global limit to a per-origin limit (scheme + hostname + effective port + unix socket path), with a process-wide ceiling fixed at 4× the per-origin value. It touches the HTTP thread's core scheduling loop (src/http/HTTPThread.rs — drain_events, start_queued_task, new active_per_origin map and deferred_may_start gate), the AsyncHTTP request struct (new origin_hash field, new setter that keeps the two atomics in sync), the bun install callers that write the cap, two docs pages, and adds/extends two test files.
Security risks
None apparent. The change is purely about local request scheduling and socket-count bounding; it does not touch auth, TLS validation, input parsing, or anything that crosses a trust boundary. The only externally observable effect is that the process may now hold up to 4× as many sockets as before, which is a resource-usage consideration rather than a security one.
Level of scrutiny
This deserves careful human review. It is a semantic change to a documented configuration knob — users who previously set BUN_CONFIG_MAX_HTTP_REQUESTS to bound total sockets will now get up to 4× that, and the multiplier is a hardcoded constant with no independent override. It also reworks concurrency-sensitive scheduling state on the HTTP thread (the deferred_may_start optimization, the per-origin slot reserve/release pairing, and the changed wakeup condition in on_async_http_callback_raw). The invariants look right and are well-commented, but this is exactly the kind of code where subtle ordering or missed-wakeup bugs hide.
Other factors
The PR is thorough: the description explains the rationale and tradeoffs clearly, the slot reserve/release is paired on the same path ACTIVE_REQUESTS_COUNT already uses, and there is solid new test coverage for isolation between origins, the per-origin cap, the total ceiling, and abort-while-queued at the new ceiling. Still, the combination of a user-visible behavior change plus a hardcoded 4× design choice plus core event-loop scheduling edits puts this outside what I'd auto-approve.
There was a problem hiding this comment.
Actionable comments posted: 7
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/runtime/networking/fetch.mdx`:
- Around line 439-446: Clarify the fetch concurrency bucket definition in the
networking docs: the current description of the per-origin cap as only scheme +
hostname + port is incomplete. Update the text around the fetch request limits
to match the implementation used by the fetch origin key, including effective
port normalization and unix socket path handling where applicable, so the
documented grouping matches how requests are actually queued.
In `@src/http/AsyncHTTP.rs`:
- Around line 340-345: The set_max_simultaneous_requests setter in AsyncHTTP is
allowing 0 to be stored, which breaks the nonzero cap invariant and can stall
queued requests. Update this setter to clamp or reject zero before writing
MAX_SIMULTANEOUS_REQUESTS and MAX_TOTAL_SIMULTANEOUS_REQUESTS, keeping the same
behavior as load_env so the active/max_total fast path in the HTTP thread never
sees a zero limit.
In `@test/js/web/fetch/fetch-abort-queued.test.ts`:
- Around line 94-98: Condense the explanatory comment in the queued fetch abort
test so it fits the repo’s 3-line limit. Keep only the key invariant being
verified in fetch-abort-queued.test.ts, and remove the extended rationale about
origin ceilings and stalled requests from the inline comment; if needed,
preserve the extra context in the PR description instead.
- Around line 159-163: The stderr assertion in fetch-abort-queued.test.ts still
special-cases the ASAN startup warning, but that filter is no longer needed for
these Bun subprocess tests. Update the expectation near stderrLines in the fetch
abort queued test to assert directly on the raw stderr result with no WARNING:
ASAN interferes filtering, and keep the plain empty-stderr check on the spawned
test output.
- Around line 115-143: The fetch abort test does not verify the intended
precondition that the fifth origin never acquires a socket before aborting.
Update the test around the queued fetch in fetch-abort-queued.test.ts to assert
or log the fifth-origin connection count before calling controller.abort(),
using the existing sockets/sockets.length setup and the queued fetch path so the
test fails if the connection limit regresses and the fifth request starts early.
In `@test/js/web/fetch/fetch-max-http-requests.test.ts`:
- Around line 1-9: The header comment in the fetch max HTTP requests test
exceeds the repo’s 3-line comment limit. Shorten the explanatory block in the
test file so it stays within three lines, keeping only the essential summary
about BUN_CONFIG_MAX_HTTP_REQUESTS and child-process isolation, and move the
longer rationale into the PR description or test name if needed. Use the
existing comment block at the top of fetch-max-http-requests.test.ts as the
target for this cleanup.
- Around line 25-30: Remove the stale stderr normalization in the
fetch-max-http-requests test: the ASAN startup-warning filter is no longer
needed in the bunEnv subprocess assertions. Update the test logic around the
stderr handling in fetch-max-http-requests.test.ts to assert the normalized
stderr directly, using the existing subprocess/test assertions in this suite
instead of filtering out lines that start with the ASAN warning prefix.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: d844aa58-3546-4f99-99ba-a6af1266a06f
📒 Files selected for processing (8)
docs/runtime/environment-variables.mdxdocs/runtime/networking/fetch.mdxsrc/http/AsyncHTTP.rssrc/http/HTTPThread.rssrc/install/PackageManager.rssrc/install/PackageManager/runTasks.rstest/js/web/fetch/fetch-abort-queued.test.tstest/js/web/fetch/fetch-max-http-requests.test.ts
There was a problem hiding this comment.
I didn't find any correctness bugs, but this changes core HTTP-thread scheduling semantics (per-origin slot accounting, a new 4× process-wide ceiling, and the deferred_may_start rescan gate) in a way that affects every fetch() and bun install, so it's worth a human look — particularly the slot reserve/release pairing and the proxy-concurrency edge case noted inline.
Extended reasoning...
Overview
This PR converts BUN_CONFIG_MAX_HTTP_REQUESTS from a process-global in-flight cap to a per-origin cap, adds a derived process-wide ceiling at 4× that value, and threads per-origin slot accounting through the HTTP thread. Touched files: src/http/AsyncHTTP.rs (new origin_hash field, request_origin_hash helper, MAX_TOTAL_SIMULTANEOUS_REQUESTS static, setter API, slot release in the completion callback), src/http/HTTPThread.rs (active_per_origin map, deferred_may_start gate, drain_events rewrite, start_queued_task becomes a method that reserves the slot), src/install/PackageManager.rs and runTasks.rs (rewired to the new setter), two test files, and two docs pages.
Security risks
None identified. The change is internal request scheduling; no auth, crypto, or untrusted-input parsing is involved. The origin hash is derived from URL components the caller already controls, and hash collisions only affect which bucket a request is counted against (worst case: slightly tighter or looser queueing for the colliding origins), not memory safety or data exposure.
Level of scrutiny
This warrants careful human review. It is a behavioral and policy change to a hot path that every fetch() and bun install traverses:
- New 1:1 invariant between
start_queued_task(reserve slot, pushin_flight) andon_async_http_callback_raw(release slot, removein_flight). The PR description argues redirects can't unbalance it because the key is fixed at admission, but the streaming-response path and any other completion path that doesn't go through the modified branch should be checked by someone who knows that code. - The
deferred_may_startoptimization changes whendeferred_tasksis rescanned; the argument that slots are only freed by completions is sound on its face, but it's the kind of liveness invariant that's easy to break later. - The 4× multiplier and the decision to key on destination origin (not proxy) are product/design choices — default total socket count goes from 256 to 1024, and a single proxy can now receive up to 1024 connections (noted in my inline comment).
Other factors
The PR has solid test coverage for the three new behaviors (origin isolation, per-origin queueing, process-wide ceiling) plus the abort-while-queued edge case at the new ceiling. All CodeRabbit comments were addressed in 8bc3ace. The earlier CI failures on commit 3602480 appear to be infra (musl build agents, Windows agent creation) rather than related to the diff. No human reviewer has weighed in yet.
|
CI status on build 70801 (current head,
Across six builds of this branch the fetch suites and the new tests have passed on every lane that ran them. I already used my one CI retrigger. |
8bc3ace to
660191c
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/runtime/networking/fetch.mdx`:
- Around line 438-440: The fetch docs currently describe queuing only when an
origin hits its limit, but the HTTP scheduler in HTTPThread also queues requests
when the process-wide ceiling is reached even if the origin still has capacity.
Update the wording in the fetch networking docs to explicitly mention both
queueing cases, using the relevant fetch concurrency section near the per-origin
limit explanation, so readers understand requests can wait on either the origin
cap or the global cap.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 3f29be7d-a785-4b6b-a90a-c0e5769fd269
📒 Files selected for processing (2)
docs/runtime/environment-variables.mdxdocs/runtime/networking/fetch.mdx
There was a problem hiding this comment.
No issues found on re-review, but this changes core HTTP-thread scheduling and the documented semantics of BUN_CONFIG_MAX_HTTP_REQUESTS (per-origin cap + 4× process ceiling), so it's worth a human sign-off on the design and the deferred_may_start/slot-accounting invariants.
Extended reasoning...
Overview
This PR converts BUN_CONFIG_MAX_HTTP_REQUESTS from a process-global in-flight fetch() cap into a per-origin cap, adds a derived process-wide ceiling at 4× that value, and reworks HTTPThread::drain_events / start_queued_task to track per-origin slot counts in a new active_per_origin map with a deferred_may_start flag gating the deferred-list rescan. AsyncHTTP gains an origin_hash field computed once in init, the cap atomics are now written only via set_max_simultaneous_requests (clamped to ≥1), and PackageManager callers are updated to use the new accessor/setter. Two docs pages, one new test file, and one extended test cover the new semantics. All prior CodeRabbit and my own inline comments are resolved; the most recent commit (660191c) applied the setter clamp and tightened test preconditions.
Security risks
None identified. The origin hash is derived from the request URL's scheme/host/effective port (plus unix socket path) via wyhash and is used only as a scheduling key on the HTTP thread — it is not exposed, not used for auth or routing, and collisions would only mildly under-count one origin's available slots. There is no new attacker-controlled input path; the env var was already user-controlled and remains range-validated in load_env.
Level of scrutiny
This is a runtime-critical, production-facing change rather than a mechanical fix. It alters the user-visible meaning of a documented env var, picks a hard-coded 4× multiplier for the new ceiling, deliberately keys on destination origin rather than proxy (a tradeoff I previously flagged and the author has called out in the PR description), and introduces a new wakeup-gating invariant (deferred_may_start) whose correctness depends on every slot-freeing path setting it before the next drain_events. A miss there would manifest as queued fetches stalling indefinitely, which is exactly the class of bug this PR is fixing. The reserve/release pairing rides on the existing ACTIVE_REQUESTS_COUNT 1:1 path, which looks sound, but a human familiar with the HTTP thread's completion paths (streaming vs. non-streaming, redirects, synchronous abort-before-connect) should confirm there's no path that decrements ACTIVE_REQUESTS_COUNT without also calling release_origin_slot.
Other factors
Test coverage is solid and targeted: the three new fetch-max-http-requests tests assert origin isolation, per-origin queueing, and the exact ceiling high-water mark, and the new fetch-abort-queued case covers abort at the ceiling with a precondition assertion that the fifth origin never connected. The author reports neighboring fetch suites pass identically before/after. The bug-hunting pass found nothing. Given the scope — core HTTP client scheduling affecting every fetch() and bun install — and the design choices baked in (4× multiplier, proxy semantics), I'm deferring to a human reviewer rather than auto-approving.
660191c to
c34307b
Compare
There was a problem hiding this comment.
No issues found in the implementation, but this changes the documented semantics of BUN_CONFIG_MAX_HTTP_REQUESTS (global → per-origin with a 4× process-wide ceiling) and reworks the HTTP thread's admission/deferral logic, so a maintainer should sign off on the policy choice and the scheduler changes.
Extended reasoning...
Overview
This PR reworks the fetch concurrency limiter in the HTTP client. src/http/AsyncHTTP.rs gains an origin_hash field, a request_origin_hash helper, a new MAX_TOTAL_SIMULTANEOUS_REQUESTS atomic (4× the per-origin cap), and a value-based set_max_simultaneous_requests setter that keeps both atomics coherent. src/http/HTTPThread.rs adds active_per_origin: ArrayHashMap<u64, u32> and a deferred_may_start flag, converts the free start_queued_task function into a method that reserves the origin slot before on_start, and rewrites the deferred/queued drain loop to check both the per-origin and process-wide caps while still fast-failing already-aborted tasks. PackageManager.rs / runTasks.rs are updated to use the new setter/getter. Docs and two test files are updated/added.
Security risks
None identified. The change is internal scheduling policy; no new user-controlled input reaches parsing, allocation sizing, or trust boundaries. The origin hash is derived from already-parsed URL fields via bun_wyhash and is only used as a map key on the HTTP thread. The setter clamps to ≥1 so a zero cap can't wedge the queue.
Level of scrutiny
High. HTTPThread::drain_events and on_async_http_callback_raw are the core admission/completion path for every fetch() and bun install network request, and the change alters user-visible behavior of a documented env var. The reserve/release pairing (slot reserved in start_queued_task, released in on_async_http_callback_raw) mirrors the existing ACTIVE_REQUESTS_COUNT/in_flight pairing and looks balanced on all paths I traced (including the synchronous-abort path, where the slot is reserved before on_start so the immediate callback finds it). The deferred_may_start gating argument is sound: slots only free on completion, which sets the flag; the flag is cleared before the rescan and any re-entrant completion during the rescan re-sets it. But this is exactly the kind of scheduler change where a subtle miss (a completion path that doesn't set the flag, or an origin-slot leak on an error branch) would manifest as a slow hang under load rather than a test failure.
Other factors
- This is a semantic/policy change, not just a bugfix: the 4× multiplier, keying on destination origin rather than proxy, and silently raising the effective process-wide socket ceiling from 256 to 1024 are design decisions a maintainer should ratify.
- All prior review feedback (CodeRabbit and my earlier proxy note) has been addressed and resolved; the most recent commit is a docs-only clarification.
- Test coverage is good: three new tests exercise per-origin isolation, same-origin queuing, and the process-wide ceiling, plus a new abort-at-ceiling test. The author reports the relevant new tests fail without the
src/change. - CI on the rebased branch passed on all fetch-related lanes; the three failures reported are unrelated (
node:netGC test on musl, NAPI lifetime on Windows). - The bug-hunting pass found nothing on this revision.
6f16ceb to
56ddccd
Compare
There was a problem hiding this comment.
I didn't find any bugs, but this changes the user-facing semantics of BUN_CONFIG_MAX_HTTP_REQUESTS and reworks the HTTP thread's request-admission loop, so it's worth a human sign-off on the design (per-origin cap, 4× ceiling, proxy exception).
Extended reasoning...
Overview
This PR redefines BUN_CONFIG_MAX_HTTP_REQUESTS from a process-global in-flight cap to a per-origin cap, and introduces a derived process-wide ceiling at 4× the per-origin value. It touches src/http/AsyncHTTP.rs (new origin_hash field, MAX_TOTAL_SIMULTANEOUS_REQUESTS atomic, value-based setter that clamps to ≥1), src/http/HTTPThread.rs (new active_per_origin map and deferred_may_start gate; start_queued_task moved from a free function to a method that reserves a per-origin slot; drain_events now checks both caps and lets tasks to unsaturated origins skip past deferred tasks for saturated ones), two PackageManager call sites migrated to the new setter, two doc pages, one new test file, and one extended test file. All prior review comments (CodeRabbit and my earlier proxy note) are resolved.
Security risks
None identified. The change is scheduling/accounting only — no parsing of untrusted input, no auth/crypto/permissions surface. The origin hash is derived from an already-parsed URL and used only as a HashMap key. The setter clamps to ≥1 so a zero cap can't wedge the queue. The reserve/release pairing is 1:1 (start_queued_task ↔ on_async_http_callback_raw), and both run on the HTTP thread so active_per_origin needs no synchronization.
Level of scrutiny
High. drain_events and start_queued_task are the hot path for every fetch(); a bookkeeping imbalance here would leak slots (permanently reducing an origin's effective concurrency) or over-admit. More importantly, this is a user-visible semantic change to a documented env var, with several design choices a maintainer should ratify: the 4× multiplier for the ceiling, keying on destination origin rather than proxy (deliberately allowing up to 4× more connections to a shared HTTP proxy — now called out in the PR description), and the deferred_may_start optimization that skips rescanning the deferred list until a completion. The PR description also notes a rebase where the moved start_queued_task had to be manually re-aligned with a provenance fix that landed on main.
Other factors
Test coverage is solid and targeted (per-origin isolation, same-origin queueing, process-wide-ceiling high-water mark, abort at the ceiling), and the author verified the neighboring fetch suites. The bug-hunting pass found nothing. CI is green except for two unrelated macOS flakes. This is well-executed, but the combination of critical-path scheduling changes and a documented-behavior redefinition puts it outside what I'd auto-approve.
56ddccd to
418db02
Compare
BUN_CONFIG_MAX_HTTP_REQUESTS (default 256) was a single process-global cap on in-flight requests. An origin that accepted connections but never responded could hold every slot, so a fetch to a completely different, healthy origin never even connected. The cap is now per origin (scheme + hostname + effective port, plus the unix socket path when set), with a process-wide ceiling of 4x the per-origin value above it. No single server ever sees more concurrency than before, one stalled origin can no longer starve the rest, and the deferred-task rescan is gated on a completion having actually freed a slot so the at-capacity path stays O(1) per event loop tick.
darwin 26 aarch64 test-bun failed provisioning the VM (rsync of the checkout was refused with a publickey auth error) before any test ran.
- set_max_simultaneous_requests clamps to 1 so a zero per-origin cap can never zero the total ceiling and wedge the queue. - The ceiling abort test asserts the fifth origin held no socket before the abort, so it fails if the ceiling regresses and the request starts. - Drop the stale ASAN startup-warning stderr filter from the new tests and condense comments.
418db02 to
4a803f4
Compare
|
Rebased onto current After the rebase:
This also addresses the black-hole face of that report: 260 fetches to an unroutable host now only saturate that one origin's 256 slots, so a fetch to a healthy origin starts immediately instead of waiting ~134 s for a kernel SYN timeout to free a global slot. The per-attempt connect timer (#32949) is the separate fix for the 135 s stall on the unroutable fetch itself. |
There was a problem hiding this comment.
I didn't find any bugs, but this changes the semantics of a user-facing default (BUN_CONFIG_MAX_HTTP_REQUESTS from process-global to per-origin with a 4× process ceiling) and reworks the HTTP thread's request-admission path, so it's worth a human sign-off on the design choices.
What was reviewed:
- Slot accounting: the per-origin increment in
start_queued_taskis placed beforeon_startand paired 1:1 withrelease_origin_slotinon_async_http_callback_raw, so synchronous abort/connect-fail re-entry doesn't underflow;origin_hashis fixed at admission so redirects can't unbalance it. deferred_may_startgating: cleared before the rescan and re-set by any completion (including synchronous re-entry fromstart_queued_task), so no wakeup is lost.set_max_simultaneous_requestsclamps to 1 and re-derives the total ceiling; both callers (load_env,bun installinit/backoff) go through it.- The proxy-keying tradeoff I raised earlier is now called out in the PR description;
active_per_originentries are removed at zero so the map doesn't grow unbounded.
Extended reasoning...
Overview
This PR converts BUN_CONFIG_MAX_HTTP_REQUESTS from a single process-global cap on in-flight fetch() requests into a per-origin cap, with a new process-wide ceiling at 4× the per-origin value. It touches src/http/AsyncHTTP.rs (new origin_hash field, MAX_TOTAL_SIMULTANEOUS_REQUESTS atomic, set_max_simultaneous_requests setter, request_origin_hash helper), src/http/HTTPThread.rs (new active_per_origin map and deferred_may_start flag on HttpThread, reworked drain_events, and start_queued_task moved from a free function to a method that reserves the per-origin slot), src/install/PackageManager.rs / runTasks.rs (mechanical rename to the new setter/getter), two docs pages, and two test files (one new, one extended).
Security risks
None identified. The origin hash is derived from the request's own URL/unix-socket-path and used only as a scheduling key on the HTTP thread; it is not exposed to user code and hash collisions would only over-count an origin's slots (making the cap conservative). No auth, TLS, or validation paths are touched. The one externally observable effect is that a single HTTP proxy may now see up to 4× the previous connection count from one process — this was raised in an earlier round, acknowledged as a deliberate tradeoff, and is now documented in the PR description.
Level of scrutiny
High. This is core HTTP-client scheduling logic that every fetch() and every bun install network task passes through, with intricate ownership invariants around the ptr::read/heap::into_raw clone in start_queued_task and synchronous re-entry into on_async_http_callback_raw. The mechanics look correct and the tests exercise the per-origin cap, the process ceiling, and the abort-while-queued path at both caps (verified to fail on main and pass with the fix under both ASAN and release). But the change also encodes several design decisions a maintainer should ratify: repurposing an existing env var's meaning, the fixed 4× multiplier, and keying on destination origin rather than proxy endpoint.
Other factors
All earlier review threads (CodeRabbit and my own inline note about the proxy-concurrency exception) are resolved. CI on the current head is green except for pre-existing flakes unrelated to fetch. The rebase note explains a provenance-fix conflict in start_queued_task that was carried over correctly. Given the scope and the user-visible semantic shift, I'm deferring rather than approving.
|
Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-23, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main. |
Problem
BUN_CONFIG_MAX_HTTP_REQUESTS(default 256) was a single process-global cap on in-flightfetch()requests. Once one origin held every slot, a fetch to a completely different origin could not even connect:In a service that fans out to several upstreams, one degraded dependency saturates the whole pool and stalls requests to healthy upstreams, which is very hard to diagnose from the outside (origin B looks slow, and nothing about origin A appears in B's traces). Node's
http.AgentmaxSocketsand undici's pools are per-origin, so they contain the damage to the broken upstream.What changed
MAX_SIMULTANEOUS_REQUESTS(=BUN_CONFIG_MAX_HTTP_REQUESTS, =bun install --network-concurrency) is now a per-origin cap. The env var, its default (256), and its range are unchanged. An origin is scheme + hostname + effective port, plus the unix socket path when one is set.MAX_TOTAL_SIMULTANEOUS_REQUESTS, sits 4x above the per-origin cap (1,024 by default) and is re-derived from it on every write, so the total socket count stays bounded.HTTPThreadkeeps anactive_per_origincount keyed by a hash computed once inAsyncHTTP::init. The slot is reserved instart_queued_taskand released inon_async_http_callback_raw, the same 1:1 pairingACTIVE_REQUESTS_COUNTalready relies on. The key is fixed at admission, so redirects cannot unbalance it.drain_eventsonly rescansdeferred_tasksafter a completion has freed a slot (the newdeferred_may_startflag). Slots are only ever freed by a completion, so nothing is missed, and the at-capacity path stays O(1) per socket event instead of walking the whole deferred list.Why these semantics
The 256 limit exists for two documented reasons (laid out in #12221, which declined to simply raise it): OS socket limits, and encouraging keep-alive reuse. Keep-alive reuse only ever happens within an origin, so a per-origin cap preserves it exactly, and the single-origin benchmark in that PR behaves identically under this change. The ceiling keeps the socket count bounded.
The property that makes this safe: no destination server ever sees more concurrency than before, because the per-origin cap equals the old global cap. Only the local process may hold more sockets, up to 4x, and the runtime already raises
RLIMIT_NOFILEat startup.One deliberate exception to that property: the key is the destination origin, not the HTTP proxy, so a process reaching four or more destination origins through one proxy can hold up to the process-wide ceiling of connections to that proxy (4x what it could before). Keying on the proxy instead would reintroduce exactly the head-of-line blocking this fixes for everything behind that proxy, so the ceiling is the bound there.
bun installis unaffected: it writes the same value through the new setter and separately paces itself to at most 64 outstanding network tasks, which is below either cap.Tests
test/js/web/fetch/fetch-max-http-requests.test.ts(new):test/js/web/fetch/fetch-abort-queued.test.ts:Without the
src/change the first and third new tests fail by timing out and the others pass; all pass with it. The neighboring suites (fetch-abort-queued,fetch-keepalive,fetch.unix,client-fetch,proxy-stress-concurrent,fetch-leak,fetch.test.ts) were run before and after, and the only failures are ones that reproduce identically without this diff.Docs updated in
docs/runtime/networking/fetch.mdxanddocs/runtime/environment-variables.mdx.Rebase note
While rebasing onto 3f5d816, main had landed a provenance fix in
start_queued_task(keep theheap::into_rawpointer forin_flightrather thanNonNull::from(&*cloned)). This PR had moved that free function into anHttpThreadmethod carrying its pre-fix body, so the method was updated to match the new pattern.[review] gate passed · iteration 18 · 8 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 2 passed · 0 rejected · iteration 18
evidence per changed file