Skip to content

[react-server] Flight leaks completed-render fetch responses under client-abort load #37288

Open

Description

@santhoshsathish94

Repo: facebook/react · Area: react-server (Flight) · Type: Bug / memory leak

Summary

Under load where HTTP clients disconnect mid-render, an RSC (React Flight) server retains the
completed render's fetch responses (and their parsed data) indefinitely. Memory grows without
bound until the process OOMs. The retention is caused by the stack trace of the internal
Error('This render completed successfully. All cacheSignals are now aborted ...') that Flight
creates on every successful render to abort its cacheController.

Environment

  • react / react-dom 19.2.8 (also reproduces on current canary)
  • Next.js 16.2.12 (App Router, force-dynamic, production build) as the host — but this is a
    react-server issue, not Next-specific.
  • Node.js 22.x / 25.x.

Reproduction

Minimal repro: a force-dynamic async Server Component that await fetch(slowUpstream) (400ms) and
renders a large list; a load generator sends requests and disconnects the client at ~60ms
(before the upstream responds). Full repro + scripts: https://github.com/santhoshsathish94/react-flight-oom-repro

Measure retained heap (post-global.gc()) after each of several 20k-request rounds.

Observed vs expected

Controlled, fixed request-count, 4 rounds × 20k requests, retained heap after forced GC:

round current expected (fixed)
1 ~540 MB ~50 MB
2 ~1150 MB ~40 MB
3 ~1250 MB ~55 MB
4 ~1600 MB ~70 MB (flat)

The render completes normally on disconnect (the fetch is not cancelled) — so this is not an
abort/error path; the responses are retained after successful completion.

Root cause

packages/react-server/src/ReactFlightServer.js (the render-complete path):

if (request.status < ABORTING) {
  const abortReason = new Error(
    'This render completed successfully. All cacheSignals are now aborted to allow clean up of any unused resources.',
  );
  request.cacheController.abort(abortReason);
}

abortReason becomes cacheController.signal.reason and is held for the request's lifetime. The
synchronous stack captured at new Error() retains, via its CallSites' closures, the completed
render's async/cache scope — including the cache() fetch-dedupe entries that hold the fetch
Response bodies. Because that reason is retained, the whole per-request cache scope (and every
Response in it) is never released.

Evidence it is stack-mediated: only --stack-trace-limit=0 eliminates the growth;
--no-async-stack-traces does not (so it is synchronous-frame capture, not async linking).
A heap snapshot shows the retained objects are _Response / InternalReadableByteStream /
ReadableByteStreamController reachable through the dedupe cache() map.

Proposed fix

This reason is an internal cleanup signal that is never surfaced to users, so it does not need a
stack trace. Create it with zero frames (or use a module-level singleton, or a non-Error reason):

if (request.status < ABORTING) {
  const previousStackTraceLimit = Error.stackTraceLimit;
  Error.stackTraceLimit = 0;
  const abortReason = new Error('This render completed successfully. All cacheSignals are now aborted to allow clean up of any unused resources.');
  Error.stackTraceLimit = previousStackTraceLimit;
  request.cacheController.abort(abortReason);
}

Validated: the fix keeps retained heap flat (~68 MB) across 8 sustained rounds (160k requests) with
no change to rendered output (normal request still returns the full response). PR attached.

Workaround for app authors

Run the server with NODE_OPTIONS=--stack-trace-limit=0 (drops all error stacks globally).

Activity

  1. santhoshsathish94 commented on Aug 13, 2026

    @santhoshsathish94
    Author

    Downstream context: this is being hit in production Next.js App Router apps.

    Fix PR: #37289.

  2. ManagrNo commented on Sep 19, 2026

    @ManagrNo

    We hit exactly this in production yesterday (self-hosted Next.js 16.3.5 / React 19.2.8 / Node 24.19, ~1.15 M pages, ~18 renders/s of mostly uncached pages) and can add two things: a heap-snapshot retainer path that shows the retention is cross-request, and a production-verified workaround.

    Retainer path (two v8.writeHeapSnapshot of the same process at 2 and 8 minutes, diffed by node id, shortest strong path to a GC root):

    Flight Request(A) —cacheController→ AbortController —#signal→ AbortSignal —kReason→ Error
      —<error_stack_symbol>→ FixedArray —[i]→ CallSiteInfo —[receiver]→ Immediate
      —_idleNext→ Immediate —_idleNext→ … (every Immediate that ran in the same processImmediate batch)
      —kAsyncContextFrame→ AsyncContextFrame —table→ Flight Request(B)
      —cacheController→ … → Error → CallSiteInfo → Immediate → … → Request(C) → …
    

    So the stack of A's abort reason doesn't only pin A's closure scope: the frame immediate._onImmediate() has the Immediate as receiver, the Immediate carries the AsyncLocalStorage frame of the request it was scheduled in (requestStorage), and executed Immediates keep their queue links — which chains every completed render to the next ones. Numbers at 8 minutes: 3 627 live IncomingMessage, 9 462 live Flight Request objects, +7 per second (= our render rate), +484 MB of ArrayBuffers (flightData, segmentData) and +443 MB of zlib state per 6 minutes, OOM at the 4 GB heap limit every 20–55 minutes. --no-async-context-frame does not help (the async_hooks store lives on the Immediate as well).

    Workaround, verified in production: read reason.stack when an AbortController is aborted with an object. V8 formats the stack and drops the CallSiteInfo array, which breaks the chain at the first link. Installed as a hot-patch through the inspector, live heap after forced full GC went from +145–250 MB/min to flat within one minute; deployed as a wrapper around AbortController.prototype.abort in instrumentation.ts, the process has been flat for 12 h.

    const orig = AbortController.prototype.abort
    AbortController.prototype.abort = function (reason) {
      if (reason !== null && typeof reason === 'object') { try { void reason.stack } catch {} }
      return orig.call(this, reason)
    }

    A string reason as in #37289 fixes it at the source; a frozen module-level singleton Error would too. Standalone Node-only repro of the Immediate/ALS part (10 errors pin 1 000 stores, 1 GiB): nodejs/node#66129.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions