Skip to content

fetch: make the in-flight request cap per-origin instead of process-global - #33007

Closed
robobun wants to merge 4 commits into
mainfrom
farm/85560460/fetch-per-origin-cap
Closed

robobun wants to merge 4 commits into
mainfrom
farm/85560460/fetch-per-origin-cap

Conversation

@robobun

@robobun robobun commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

BUN_CONFIG_MAX_HTTP_REQUESTS (default 256) was a single process-global cap on in-flight fetch() requests. Once one origin held every slot, a fetch to a completely different origin could not even connect:

// origin A accepts connections and never responds
for (let i = 0; i < 256; i++) fetch("http://slow-origin-a/");
// origin B is healthy, but this never connects until an origin-A slot frees
await fetch("http://fast-origin-b/");

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.Agent maxSockets and 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.
  • A new process-wide ceiling, 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.
  • HTTPThread keeps an active_per_origin count keyed by a hash computed once in AsyncHTTP::init. The slot is reserved in start_queued_task and released in on_async_http_callback_raw, the same 1:1 pairing ACTIVE_REQUESTS_COUNT already relies on. The key is fixed at admission, so redirects cannot unbalance it.
  • drain_events only rescans deferred_tasks after a completion has freed a slot (the new deferred_may_start flag). 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.
  • Already-aborted queued tasks still start regardless of either cap and fail fast, preserving http: fail-fast aborted fetches queued behind max_simultaneous_requests #29411. There is a new test for an abort at the total ceiling, which is a branch the existing test no longer reaches.

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_NOFILE at 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 install is 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):

  • a stalled origin does not block fetches to other origins
  • requests to the same origin still queue behind the per-origin cap (the server's unanswered-request high-water mark stays at 1)
  • the process-wide ceiling bounds in-flight requests across origins (high-water mark is exactly 4 with six origins and a per-origin cap of 1)

test/js/web/fetch/fetch-abort-queued.test.ts:

  • new: aborting a fetch queued behind the process-wide ceiling (rather than the per-origin cap) still rejects its promise

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.mdx and docs/runtime/environment-variables.mdx.

Rebase note

While rebasing onto 3f5d816, main had landed a provenance fix in start_queued_task (keep the heap::into_raw pointer for in_flight rather than NonNull::from(&*cloned)). This PR had moved that free function into an HttpThread method 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)
ASAN without fix: 3 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/fetch/fetch-abort-queued.test.ts test/js/web/fetch/fetch-max-http-requests.test.ts
bun test v1.4.0 (4a803f473)

test/js/web/fetch/fetch-abort-queued.test.ts:
(pass) aborting a fetch that is queued behind max_simultaneous_requests rejects the promise [1404.58ms]
killed 1 dangling process
(fail) aborting a fetch that is queued behind the process-wide request ceiling rejects the promise [5004.05ms]
  ^ this test timed out after 5000ms.

test/js/web/fetch/fetch-max-http-requests.test.ts:
(pass) requests to the same origin still queue behind the per-origin cap [2179.06ms]
(fail) a stalled origin does not block fetches to other origins [5005.60ms]
  ^ this test timed out after 5000ms.
(fail) the process-wide ceiling bounds in-flight requests across origins [5000.12ms]
  ^ this test timed out after 5000ms.

 2 pass
 3 fail
 6 expect() calls
Ran 5 tests across 2 files. [13.55s]
error: script "bd" exited with code 1
__F:3:S:0

release without fix: 3 FAILED
bun test v1.4.0-canary.1 (1498d7b77)

test/js/web/fetch/fetch-abort-queued.test.ts:
(pass) aborting a fetch that is queued behind max_simultaneous_requests rejects the promise [31.49ms]
killed 1 dangling process
(fail) aborting a fetch that is queued behind the process-wide request ceiling rejects the promise [5000.13ms]
  ^ this test timed out after 5000ms.

test/js/web/fetch/fetch-max-http-requests.test.ts:
(pass) requests to the same origin still queue behind the per-origin cap [43.13ms]
(fail) a stalled origin does not block fetches to other origins [5000.48ms]
  ^ this test timed out after 5000ms.
(fail) the process-wide ceiling bounds in-flight requests across origins [5000.06ms]
  ^ this test timed out after 5000ms.

 2 pass
 3 fail
 6 expect() calls
Ran 5 tests across 2 files. [10.20s]
__F:3:S:0
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/fetch/fetch-abort-queued.test.ts test/js/web/fetch/fetch-max-http-requests.test.ts
bun test v1.4.0 (4a803f473)

test/js/web/fetch/fetch-abort-queued.test.ts:
(pass) aborting a fetch that is queued behind max_simultaneous_requests rejects the promise [1420.82ms]
(pass) aborting a fetch that is queued behind the process-wide request ceiling rejects the promise [1450.27ms]

test/js/web/fetch/fetch-max-http-requests.test.ts:
(pass) a stalled origin does not block fetches to other origins [1294.16ms]
(pass) the process-wide ceiling bounds in-flight requests across origins [2329.33ms]
(pass) requests to the same origin still queue behind the per-origin cap [2478.36ms]

 5 pass
 0 fail
 9 expect() calls
Ran 5 tests across 2 files. [7.48s]
__F:0:S:0

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     4a803f4731
  features     baseline

22 deps, 108 codegen, 1170 objects in 817ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1233] install /workspace/bun
bun install v1.4.0-canary.1 (1498d7b77)

Checked 124 installs across 170 packages (no changes) [4.00ms]
[2/1233] install /workspace/bun/packages/bun-error
bun install v1.4.0-canary.1 (1498d7b77)

Checked 1 install across 2 packages (no changes) [1.00ms]
[3/1233] install /workspace/bun/src/node-fallbacks
bun install v1.4.0-canary.1 (1498d7b77)

Checked 129 installs across 147 packages (no changes) [4.00ms]
[4/1233] gen ErrorCode+*.h
[5/1233] gen bindgenv2
[6/1233] gen .bind.ts → GeneratedBindings.cpp
[7/1233] gen ProcessBindingConstants.lut.h
Generating /workspace/bun/build/release/codegen/ProcessBindingConstants.lut.h from /workspace/bun/src/jsc/bindings/ProcessBindingConstants.cpp
[8/1233] fetch zlib
[zlib] up to date
[9/1233] fetch picohttpparser
[picohttpparser] up to date
[10/1233] fetch libjpeg-turbo
[libjpeg-tur
... (truncated)
diff hotspot
docs/runtime/environment-variables.mdx            |   2 +-
 docs/runtime/networking/fetch.mdx                 |  10 +-
 src/http/AsyncHTTP.rs                             |  83 ++++++++-
 src/http/HTTPThread.rs                            | 207 ++++++++++++++--------
 src/install/PackageManager.rs                     |  23 ++-
 src/install/PackageManager/runTasks.rs            |  10 +-
 test/js/web/fetch/fetch-abort-queued.test.ts      |  75 ++++++++
 test/js/web/fetch/fetch-max-http-requests.test.ts | 139 +++++++++++++++
 8 files changed, 446 insertions(+), 103 deletions(-)

gate history · 2 passed · 0 rejected · iteration 18

evidence per changed file
file                                               reads  edits  tests
docs/runtime/environment-variables.mdx                 3      4      8
docs/runtime/networking/fetch.mdx                      4      6      8
src/http/AsyncHTTP.rs                                  3     12      8
src/http/HTTPThread.rs                                 6      7      8
src/install/PackageManager.rs                          1      2      8
src/install/PackageManager/runTasks.rs                 1      1      8
test/js/web/fetch/fetch-abort-queued.test.ts           3      7      5
test/js/web/fetch/fetch-max-http-requests.test.ts      0      5      5

@mintlify

mintlify Bot commented Jun 28, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
bun 🟢 Ready View Preview Jun 28, 2026, 9:22 AM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Adds per-origin HTTP concurrency limits to Bun's fetch layer. AsyncHTTP gains origin_hash tracking and a new cap API; HTTPThread enforces per-origin and process-wide ceilings; PackageManager uses the new API; tests and docs are updated.

Changes

Per-origin HTTP concurrency

Layer / File(s) Summary
AsyncHTTP caps and origin tracking
src/http/AsyncHTTP.rs
Adds origin_hash: u64, origin hashing, the total concurrency ceiling, and the value-based cap setter/getter API.
AsyncHTTP completion and wakeup gating
src/http/AsyncHTTP.rs
Releases per-origin slots on completion, sets deferred scheduling state, and gates wakeups against the total ceiling.
HTTPThread scheduling and slot accounting
src/http/HTTPThread.rs
Adds per-origin tracking state, updates deferred-task draining for both caps, and replaces the queued-task helper with a method that reserves origin slots.
PackageManager cap wiring
src/install/PackageManager.rs, src/install/PackageManager/runTasks.rs
Switches installer concurrency updates to the new AsyncHTTP cap API.
Fetch concurrency tests
test/js/web/fetch/fetch-max-http-requests.test.ts, test/js/web/fetch/fetch-abort-queued.test.ts
Adds coverage for per-origin isolation, same-origin queueing, total-cap limits, and aborting queued fetches.
Documentation updates
docs/runtime/environment-variables.mdx, docs/runtime/networking/fetch.mdx
Updates the HTTP request limit documentation to describe per-origin limits and the 4× process-wide ceiling.

Possibly related PRs

  • oven-sh/bun#29411: Also changes queued fetch abort behavior around request limits and adds coverage for queued request settlement.
  • oven-sh/bun#31325: Also touches src/http/HTTPThread.rs scheduling and event-drain logic in the HTTP layer.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: making fetch in-flight limits per-origin instead of process-global.
Description check ✅ Passed The description covers the problem, the implementation changes, and testing, though it uses custom headings instead of the template.

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:13 AM PT - Jul 23rd, 2026

✅ @robobun, your commit 4a803f47311f9e69450ec7d69c3f2a3e4198f1f8 passed in Build #78739! 🎉


🧪   To try this PR locally:

bunx bun-pr 33007

That installs a local version of the PR into your bun-33007 executable, so you can run:

bun-33007 --bun

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between a1c39de and 3602480.

📒 Files selected for processing (8)
  • docs/runtime/environment-variables.mdx
  • docs/runtime/networking/fetch.mdx
  • src/http/AsyncHTTP.rs
  • src/http/HTTPThread.rs
  • src/install/PackageManager.rs
  • src/install/PackageManager/runTasks.rs
  • test/js/web/fetch/fetch-abort-queued.test.ts
  • test/js/web/fetch/fetch-max-http-requests.test.ts

Comment thread docs/runtime/networking/fetch.mdx Resolved
Comment thread src/http/AsyncHTTP.rs Resolved
Comment thread src/http/AsyncHTTP.rs Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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, push in_flight) and on_async_http_callback_raw (release slot, remove in_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_start optimization changes when deferred_tasks is 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.

@robobun

robobun commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI status on build 70801 (current head, 418db02938): 281 of 284 completed jobs passed. The failures are:

  • alpine 3.23 x64 and x64-baseline: test/regression/issue/26030.test.ts, a MySQL transaction test run under describeWithContainer("mysql", ...) that times out at 60s. No fetch() in the file. This same test has also appeared on builds 66330 and 70675 of this branch, each time on a different alpine lane.
  • debian 13 x64-asan: test/cli/install/migration/complex-workspace.test.ts, a bun install workspace node_modules layout test. My install-side change is a pure accessor rename (max_simultaneous_requests() returns the value instead of the atomic), and the same test appeared on build 66330 of this branch before any review changes.

test/js/bun/http/proxy-stress-concurrent.test.ts, the one failure I flagged as possibly related on build 70675, passed on every lane of this build, including both darwin 14 lanes. That settles the 1/1200 there as a stress-test tail.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3602480 and 660191c.

📒 Files selected for processing (2)
  • docs/runtime/environment-variables.mdx
  • docs/runtime/networking/fetch.mdx

Comment thread docs/runtime/networking/fetch.mdx Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:net GC test on musl, NAPI lifetime on Windows).
  • The bug-hunting pass found nothing on this revision.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

robobun added 4 commits July 23, 2026 15:20
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.
@robobun
robobun force-pushed the farm/85560460/fetch-per-origin-cap branch from 418db02 to 4a803f4 Compare July 23, 2026 15:28
@robobun

robobun commented Jul 23, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto current main (892b1da). The only conflict was the AtomicState field that #35002 deleted sitting next to the new origin_hash field in AsyncHTTP::init; resolved by keeping origin_hash and dropping the already-removed field.

After the rebase:

  • cargo check -p bun_http / bun_install clean
  • fetch-max-http-requests.test.ts + fetch-abort-queued.test.ts: 3 fail on the system bun (timeout), 5/5 pass on the debug build
  • fetch-keepalive, fetch.unix, proxy-stress-concurrent: 44/44 pass
  • The 300-slow-origin-A / 1-fast-origin-B reproduction from the fuzzer report: origin B answers in 36 ms with the fix vs 3081 ms on main

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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_task is placed before on_start and paired 1:1 with release_origin_slot in on_async_http_callback_raw, so synchronous abort/connect-fail re-entry doesn't underflow; origin_hash is fixed at admission so redirects can't unbalance it.
  • deferred_may_start gating: cleared before the rescan and re-set by any completion (including synchronous re-entry from start_queued_task), so no wakeup is lost.
  • set_max_simultaneous_requests clamps to 1 and re-derives the total ceiling; both callers (load_env, bun install init/backoff) go through it.
  • The proxy-keying tradeoff I raised earlier is now called out in the PR description; active_per_origin entries 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.

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@robobun robobun closed this Sep 13, 2026

This branch was successfully deployed

1 active deployment
staging - docs — 4a803f47 Deployed Jul 23, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants