workers-sdk icon indicating copy to clipboard operation
workers-sdk copied to clipboard

[miniflare] dispatchFetch forces reset: true — one TCP connection (and one TIME_WAIT port) per request, causing ephemeral-port exhaustion in CI

Open ethan-leonard opened this issue 2 months ago • 4 comments

Summary

Every Miniflare#dispatchFetch() (and getWorker().fetch()) closes its TCP connection after the response: DispatchFetchDispatcher.dispatch unconditionally sets undici's options.reset = true (packages/miniflare/src/http/fetch.ts, "avoid keep-alive race conditions"). There is no opt-out: dispatchFetch builds the dispatcher internally and overwrites any dispatcher passed in the request init.

On macOS each closed connection then sits in TIME_WAIT for 2×MSL (30s by default), holding one ephemeral port from the machine-wide pool of 16,384 (net.inet.ip.portrange 49152–65535). Measured: 200 sequential dispatchFetch calls produce exactly 200 TIME_WAIT sockets; a miniflare-heavy integration suite of ours produces ~7,400 in 26 seconds. With a few such suites running concurrently on one CI host, the pool empties and every loopback connect()/listen(0) on the machine — including workerd's own socket binds and unrelated jobs — fails with EADDRNOTAVAIL for tens of seconds. We root-caused a recurring "fetch failed … EADDRNOTAVAIL" CI flake to exactly this.

Versions

  • [email protected] (also present on main today — the options.reset = true line in packages/miniflare/src/http/fetch.ts)
  • Node v22.23.2, macOS arm64 (Linux has a larger default ephemeral range and shorter TIME_WAIT recycling, so macOS hits this first)

Minimal reproduction

import { execSync } from "node:child_process";
import { Miniflare } from "miniflare";

const tw = () =>
  Number(execSync("netstat -an -p tcp | grep -c TIME_WAIT || true", { encoding: "utf8" }).trim());

const mf = new Miniflare({
  compatibilityDate: "2026-08-08",
  modules: true,
  script: `export default { async fetch() { return new Response("ok"); } };`,
});
await mf.ready;
const before = tw();
for (let i = 0; i < 200; i++) {
  const response = await mf.dispatchFetch("https://example.com/");
  await response.text();
}
console.log("TIME_WAIT delta:", tw() - before); // 200 — one connection per request
await mf.dispose();

Ask

The comment above the flag says it mitigates keep-alive connections "disconnecting unexpectedly", so there may be a real race being avoided — but the mitigation costs one ephemeral port per request, machine-wide, with no escape hatch. Either of these would resolve it:

  1. Reuse connections for runtime dispatches (undici already retries idempotent requests on a stale keep-alive connection, which may cover the original race), or
  2. An option to opt out of reset: true (e.g. honoring a caller-supplied dispatcher, or a Miniflare constructor option), so CI-heavy users can choose connection reuse.

Happy to provide more measurements if useful.

ethan-leonard avatar Sep 18 '26 21:09 ethan-leonard

Automated triage

Issue assessment

  • Actionability: ✅ Actionable.
  • Type: Bug (medium confidence).
  • Reproduction: Automatic attempt requested.
  • Labels:
    • package:miniflare (high)
    • ci-flake (medium)
Actionability and missing information

dispatchFetch unconditionally sets undici reset:true, leaving one TIME_WAIT socket per request; the reporter measured 200 sockets for 200 calls and EADDRNOTAVAIL port exhaustion in CI on macOS, and asks for connection reuse or an opt-out.

Reproduction reason: Report includes a self-contained minimal reproduction measuring TIME_WAIT growth per dispatchFetch call, matching a current-behavior defect.

Reproduction

  • Result: ✅ Reproduced.
  • Summary: Reproduced #15716: miniflare 5.20260811.1-alpha (exact issue version), Linux x86_64, Node v22.23.2. 200 sequential dispatchFetch calls left exactly 200 TIME_WAIT sockets (one connection+ephemeral port per request, as measured in the issue); keep-alive baseline left 0.
Evidence and attempted steps

Steps attempted:

  1. Verified sandbox environment: Linux x86_64 (Ubuntu 22.04, kernel 6.18), Node v22.23.2 (same as report), npm registry reachable; ss/netstat absent so TCP state read from /proc/net/tcp{,6}
    • Command: uname -a; node -v; cat /proc/sys/net/ipv4/ip_local_port_range
  2. Installed the exact version named in the issue (miniflare 5.20260811.1-alpha with workerd 1.20260811.1 binary) via pnpm 10.15.1, preserving pnpm-lock.yaml
  3. Adapted the issue's flat-options snippet to the pinned alpha's v5 options schema by passing the issue's options verbatim through the package's own convertV4MiniflareOptions export; scratch-verified dispatchFetch returns the worker's response
    • Command: node -e "import('miniflare').then(m => new m.Miniflare(m.convertV4MiniflareOptions({compatibilityDate:'2026-08-08',modules:true,script:'...'})))"
  4. Ran the reproduction: started Miniflare with the issue's worker, counted TIME_WAIT sockets (state 06 in /proc/net/tcp{,6}) attributable to the workerd listener before/during/after 200 sequential dispatchFetch calls, then ran a 200-request keep-alive fetch() baseline against a plain node:http server
    • Command: node reproduce.mjs

Expected behavior: Per the report's ask: dispatchFetch should reuse connections for runtime dispatches (or honor an opt-out such as a caller-supplied dispatcher or constructor option), so N sequential dispatchFetch calls do not leave N TIME_WAIT sockets holding one ephemeral loopback port each; a keep-alive client should show a flat TIME_WAIT count.

Observed behavior: 200 sequential dispatchFetch calls left exactly 200 TIME_WAIT sockets attributable to the workerd loopback listener (machine-wide delta also exactly 200), growing one-per-request (50/100/150/200 at checkpoints); every socket was an ephemeral client port (e.g. 127.0.0.1:38994) connected to the workerd port, i.e. the client side closes each connection after the response and it lingers in TIME_WAIT. This matches the issue's 200/200 macOS measurement exactly. Baseline: 200 sequential keep-alive fetch() calls against a plain node:http server produced delta 0, isolating the behavior to dispatchFetch's connection handling.

Artifact: Download reproduction archive (Cloudflare Access required).

Treat archive contents as untrusted. Inspect them before running anything.


This summary was generated by an LLM and may contain errors. Please verify its findings.

Triage bot commands and options

Repository collaborators with write or admin access can trigger actions by commenting on this issue:

  • @workers-devprod reproduce: Attempt to reproduce the issue using its description and recent comments.

workers-devprod avatar Sep 18 '26 21:09 workers-devprod

Hi! I'd like to work on this 😸 I’ll first look into why reset: true was originally added and try to reproduce both scenarios. If that scope sounds good, I’d be happy to take it

Wichtowski avatar Sep 20 '26 15:09 Wichtowski

Another datapoint, from @cloudflare/vite-plugin 1.59.0 / miniflare 5.20260921.1-alpha on macOS (Node 26), where this shows up as [vite] Internal server error: fetch failed bursts during Playwright e2e.

With assets.run_worker_first: true, every dev request (including each Vite module file) goes through dispatchFetch, so one e2e run of ~150 tests made ~20k connections. Two suites running at once filled the 16,384-port ephemeral range (TIME_WAIT peaked at ~16.1k), and connects failed with EADDRNOTAVAIL for 1-2s at a time. Vite then broadcasts each error to every open page as the error overlay, so one burst failed 8-10 unrelated tests. The same thing happened on a macOS CI runner.

What fixed it for us, as a local patch: drop options.reset = true in DispatchFetchDispatcher.dispatch and give the runtime Pool keepAliveTimeout: 1e3, keepAliveMaxTimeout: 1e3, so idle sockets always close on the client side well before workerd's 5s idle close (the race reset was guarding against, #14641). Across 21 patched suites: 4,952 connections for 439,244 requests, TIME_WAIT under ~900, 150/150 passing in every run (4 and 9 workers, load up to 34), and no socket-reset errors. The only undici errors left were AbortErrors from pages closing.

jasonnickel avatar Sep 26 '26 01:09 jasonnickel

Thanks for the issue @ethan-leonard 🙂🙏 and thanks @Wichtowski for looking into it 😄

dario-piotrowicz avatar Sep 29 '26 11:09 dario-piotrowicz