Skip to content

[react-server] Don't capture a stack for the render-completed cacheSignal abort reason - #37289

Open
santhoshsathish94 wants to merge 8 commits into
react:mainfrom
santhoshsathish94:rsc-flight-completed-abort-nostack
Open

santhoshsathish94 wants to merge 8 commits into
react:mainfrom
santhoshsathish94:rsc-flight-completed-abort-nostack

Conversation

@santhoshsathish94

@santhoshsathish94 santhoshsathish94 commented Aug 13, 2026 •

Copy link
Copy Markdown

Fixes #37288

Summary

On every successful Flight render, flushCompletedChunks builds an Error and stores it on
request.cacheController.signal.reason:

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);
}

That Error captures a stack. The stack is never read, and it could not help anyone if it were: the
frames are flushCompletedChunks -> startFlowing -> pull, all internal, and the one useful
question -- which render completed -- lives in the async stack, which error.stack does not carry.
Meanwhile the object is retained for the lifetime of the request as signal.reason, and V8's
captured CallSites keep alive whatever the capturing frames reach through their closure scope, which
here is the completed render.

So this is dead weight by construction. This PR aborts with a string instead.

Change

     if (request.status < ABORTING) {
-      const abortReason = new Error(
+      // A string rather than an Error because the only stack worth having here is the
+      // async one that says which render completed, and that is not in error.stack.
+      request.cacheController.abort(
         'This render completed successfully. All cacheSignals are now aborted to allow clean up of any unused resources.',
       );
-      request.cacheController.abort(abortReason);
     }

Two files, +4 -3.

Why nothing is lost

  • A string is a supported shape on this path, not a tolerated one. emitErrorChunk already branches
    on error instanceof Error and, for a plain value, produces String(error) with an empty stack.
  • Nothing touches Error.stackTraceLimit, so no process-wide state is involved.
  • The frames dropped are all inside React. The reason is constructed in React's flush, so its stack
    could never contain an application frame.
  • No public API change.

Test

One existing assertion changed. ReactCache-test.js read renderedCacheSignal.reason.message; with
a string reason it asserts the reason itself. This assertion predates the PR, so it is worth
flagging: it is the only place in the test suite that depended on this reason being an Error.

An earlier revision of this PR added a test asserting the reason carried no stack frames. That test
is removed -- with a string there is no stack to assert, and as @eps1lon pointed out it could only
ever have proven an invariant rather than a reclaim.

Background

#37288 has the original heap analysis and vercel/next.js#84648 collects the reports that led here.
Those numbers move with workload, Next.js version and Node version (Node 24.20 appears to reduce
stack retention on its own), so I would rather this change stand on the code above than on any
particular measurement.

Test plan

  • yarn test react-server and yarn test react-reconciler, lint/prettier/flow -- not run
    locally (toolchain), relying on CI.

…gnal abort reason

On every successful Flight render, ReactFlightServer creates
new Error('This render completed successfully...') and stores it as
cacheController.signal.reason for the request's lifetime. Its synchronous stack
retains the completed render's cache scope (the cache() fetch-dedupe entries
holding fetch Response bodies), leaking RSC responses under client-abort load
until the process OOMs.

Create that internal, never-surfaced cleanup reason with Error.stackTraceLimit = 0
(save/restore) so it carries no stack. Message and behavior are unchanged.

Refs react#37288
@haoku123

Copy link
Copy Markdown

Thanks for the fix — the diagnosis is correct (V8 captures the stack eagerly at new Error() time, and with async stack traces enabled in Node 16+ that retains the completed render's async scope), and keeping the Error type is the right call here: signal.reason is consumed by abortStream / abortIterable / abortBlob (ReactFlightServer.js ~1377, ~1511, ~3565), which pass it to erroredTask for tasks still pending at abort, so a plain string/object would degrade the error shape sent to the client.

Two suggestions before this lands:

  1. Guard the global mutation with try/finally. Error.stackTraceLimit is process-wide shared state. The synchronous block makes interleaving impossible today, but the restore is fragile: if new Error throws for any reason (or someone later adds an await inside the block), the limit stays at 0 and every subsequent stack trace in the process silently loses frames. Something like:
const abortReason = new Error(
  'This render completed successfully. All cacheSignals are now aborted to allow clean up of any unused resources.',
);
if (suppressStackTrace(abortReason)) {
  // stack stripped, nothing else to do
}

or a small createAbortReason(message) helper with try/finally would make the intent and the safety boundary explicit.

  1. This needs a regression test. It's an OOM-class bug, but the behavioral surface is small and assertable: the abort reason created on the success path must have no captured stack. A unit test around the flushCompletedChunks success path asserting abortReason.stack is undefined/empty (with stack traces enabled in the test env) would lock the fix against future refactors that reintroduce the capture.

Minor: the fatalError path (~4400) also creates a stacked abortReason, but that one runs once per request rather than per successful render, so it's not a leak source — worth a one-line comment there to prevent someone from "fixing" the asymmetry later.

…lper + regression test

- Wrap the no-stack Error creation in createErrorWithoutStack() with try/finally, so a throw (or a future await) cannot leave Error.stackTraceLimit pinned at 0 process-wide.

- Add a regression test asserting the completion cacheSignal reason has no captured stack (Flight path via ReactNoopFlightServer in ReactCache-test).

- Note at the fatalError path that its stacked reason runs once per request, not per completed render, so it is not a leak source.
@santhoshsathish94

Copy link
Copy Markdown
Author

Thanks for the thorough review — all three addressed in 49c1936.

1. Guarded the global mutation with try/finally. Extracted a small helper so the safety boundary is explicit and a throw (or a future stray await) can't leave Error.stackTraceLimit pinned at 0:

function createErrorWithoutStack(message: string): Error {
  const previousStackTraceLimit = Error.stackTraceLimit;
  Error.stackTraceLimit = 0;
  try {
    return new Error(message);
  } finally {
    Error.stackTraceLimit = previousStackTraceLimit;
  }
}

The success path now just calls createErrorWithoutStack(...). And good call on keeping the Error type — signal.reason flows into erroredTask via abortStream / abortIterable / abortBlob, so a plain string/object would degrade the client error shape; kept it an Error.

2. Added a regression test. It asserts the completion cacheSignal() reason has no captured stack, right next to the existing cacheSignal() aborts when the render finishes normally test in ReactCache-test.js (which already drives the Flight completion path through ReactNoopFlightServer). It fails against the pre-fix stacked reason and passes now. In the spirit of your "drain luck" point it's a direct assertion rather than a load test — though I couldn't run the full react-server suite locally, so CI is the source of truth here; happy to adjust if it flags anything.

3. fatalError path. Added a one-line comment that it runs at most once per request (not per completed render), so its stacked reason isn't a leak source — to keep someone from "fixing" the asymmetry later.


Independent corroboration since filing: @xabierlameiro reproduced this on Next.js 16.3.1 and 16.2.12 (React 19.2.8, Node 24) using the shared repro — four rounds × ~19.5k client-aborted requests, doubled (vercel/next.js#84648 comment):

  • retained heap without the flag: 407–2264 MB; with --stack-trace-limit=0: 68–157 MB — the two arms never overlap (lowest unpatched is 2.6× the highest patched).
  • the patched arm shows no trend across rounds, i.e. no residual leak on this path once the frames are gone.

@santhoshsathish94

Copy link
Copy Markdown
Author

This is ready for a maintainer review whenever someone has a moment — CI is green, and I've addressed the community review from @haoku123 (a try/finally guard around the stack-limit toggle, plus a regression test asserting the completion cacheSignal() reason carries no stack).

@sebmarkbage / @unstubbable — since this touches the react-server render-completion path you both work on most, would one of you be the right person to review, or point me to who is? No rush, and thanks.

@haoku123

Copy link
Copy Markdown

Thanks for addressing the review — the try/finally guard around the process-wide Error.stackTraceLimit toggle plus the regression test are exactly right. The comment explaining why the stack-limit toggle must be restored even on throw is accurate and will help future readers. Leaving a normal new Error on the fatal path (runs once per request, no leak) also looks correct. LGTM from my side — thanks for driving this.

@dianatofficial dianatofficial left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Looks good. Error handling is solid.

@santhoshsathish94

Copy link
Copy Markdown
Author

@gnoff We’ve been investigating a React/Next.js OOM issue under sustained load, with an independent reproduction in Next.js. We raised this PR with the findings and mitigation. Would appreciate your thoughts on the approach.

Next.js issue: vercel/next.js#84648

Resolves a conflict in ReactFlightServer.js. Upstream moved the completed-render cacheSignal abort earlier in flushCompletedChunks so it runs before the stream bookkeeping can set CLOSED, which read as a delete-vs-modify against this branch. Reapplied createErrorWithoutStack at the new call site and kept upstream's ordering comment intact.
@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

The build for this commit did not complete, so there is no size report. See the workflow run for details.

Generated by sizebot against b158234

@santhoshsathish94

Copy link
Copy Markdown
Author

Resolved the conflict with main. Upstream moved the completed-render cacheSignal abort earlier in flushCompletedChunks — so it runs before the stream bookkeeping can set CLOSED while debug chunks are outstanding — which read as a delete-vs-modify against this branch. The change is reapplied at the new call site with that ordering comment kept intact; the net diff against main is unchanged at +20/-1.

I have the test suite running locally now, so the earlier note about not being able to build/run it no longer applies:

  • The regression test passes, and still fails with the fix reverted at the new call site — so it guards the behaviour at the moved location, not just where the code used to be.
  • packages/react-server produces an identical set of failures to a clean checkout of main in the same environment, so nothing here is a new failure.

I've ticked the regression-test box. Leaving the second one unticked on purpose: my local suite run isn't green (those failures reproduce on unmodified main here, so they appear environmental), and prettier flags ~4.2k files including ones this branch never touched because it's a CRLF working tree. Neither is something I can honestly claim as verified, so CI stays the source of truth for that box.

@haoku123

haoku123 commented Sep 2, 2026

Copy link
Copy Markdown

Following up here — I reviewed this change earlier and it still looks correct to me (the try/finally guard around the Error.stackTraceLimit toggle plus the regression test).

Adding one independent data point on impact, in case it helps with prioritisation: the leak this addresses isn't theoretical. vercel/next.js#84648 ("Memory leak during load tests in dynamic rendering mode", still open) reports the process sitting at ~15 GB after a load test finishes, with no recovery. That matches the retention described here: the abort reason is only ever used for diagnostics, but capturing it keeps the synchronous render stack — and through it the completed response — reachable for as long as the request object is, so a client that disconnects leaves the finished render pinned.

If it would help move this forward I'm happy to:

  • add a stress-style regression test asserting that retained size drops once the client disconnects, if that's valuable at this layer;
  • rebase again if main has moved.

@sebmarkbage @unstubbable @gnoff — is anything else blocking review, or is this just waiting on bandwidth? No pressure, just trying to be useful.

Comment on lines +293 to +304
expect(errors).toEqual([]);
expect(renderedCacheSignal.aborted).toBe(true);
expect(renderedCacheSignal.reason.message).toContain(
'This render completed successfully.',
);
// The completion reason must not capture a stack. A captured stack retains the
// completed render's cache scope for the request's lifetime and leaks RSC
// responses under load. See #37288.
const stackFrames = (renderedCacheSignal.reason.stack || '')
.split('\n')
.filter(line => /^\s*at\s/.test(line));
expect(stackFrames).toEqual([]);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The test makes it impossible to check if the leak is in React because the app code is leaking the signal itself. What is the real-world scenario that reproduces a memory leak? Is that still happening on the latest version on main?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks — this is a fair concern. I think there are two separate things to distinguish here: what the React regression test is proving, and what the end-to-end reproduction is proving.

The test in this PR is intentionally a narrow regression test for the React invariant: the completion cacheSignal() abort reason should not capture a stack. It goes through the Flight completion path and verifies that the actual reason stored on signal.reason has no stack frames. It is not intended to be the leak reproducer by itself.

The real-world reproduction is the one from vercel/next.js#84648. The workload does not retain the cacheSignal from application code; it uses a dynamic server component with a slow upstream and clients disconnecting while the render is in progress. Under sustained high concurrency, retained heap grows after forced GC. The same workload was independently reproduced on Next 16.3.1 / 16.2.12 with React 19.2.8 and Node 24.

The strongest evidence there is the A/B with --stack-trace-limit=0: without the flag, retained heap after the load rounds was 407–2264 MB; with it, 68–157 MB. The two sets did not overlap, and the stackTraceLimit=0 arm showed no accumulating trend across rounds. This is what led me to the React new Error() / captured CallSites retention path rather than application-level retention.

I also agree that suppressing the stack globally does not isolate this exact React call site, since it affects other stack-producing paths as well. That is why I'm treating the A/B as evidence that captured stacks are the dominant retained cost on this client-abort path, rather than as a proof that only this single new Error() is responsible.

For the second question, the issue is still reproducible on currently published React/Next versions; #84648 contains the recent independent reproductions. I can also run the shared repro against current React main to make that comparison explicit.

@haoku123

haoku123 commented Sep 2, 2026

Copy link
Copy Markdown

@eps1lon — your objection is correct, and I want to be precise about why, because I endorsed this test earlier and my wording there was too generous.

What the test can and cannot prove

renderedCacheSignal is a strong reference held in the test's own scope:

let renderedCacheSignal = null;
async function Test() {
  renderedCacheSignal = cacheSignal();

The signal stays reachable across the whole assertion window, so it cannot be collected no matter what the abort reason holds. expect(stackFrames).toEqual([]) therefore verifies an invariant — that the completion reason carries no captured frames — not a reclaim. It can't distinguish "React released the render" from "React is still retaining it and we just can't observe that from here." Your read is right.

When I said the test looked "exactly right," I meant it in that narrow invariant sense. That was imprecise of me, and I should have separated the two claims myself.

Does it still reproduce on main?

At the code level, yes. On current main, flushCompletedChunks still builds the reason with a plain new Error (packages/react-server/src/ReactFlightServer.js:6692), and createErrorWithoutStack does not exist on main at all — it is introduced by this PR. Nothing has landed that would change this path.

On strengthening the test — my suggestion is not to

I previously offered to add a stress-style test asserting retained size drops after a disconnect. Having looked at it properly, I would withdraw that: it needs --expose-gc, and this file has no GC-assertion precedent (WeakRef / global.gc appear nowhere in ReactCache-test.js). It would be the first, and inherently timing-sensitive — the kind of flake that costs more than it proves.

A WeakRef variant has the same problem in a different shape: it only becomes meaningful once React's own strong path to the signal (controller -> request) is dropped, so it would assert on React's internal retention graph rather than on the public contract.

So: keep this as the cheap, deterministic invariant test it is — it locks the mechanism. Establish the effect (heap returning to baseline) from the end-to-end reproduction in vercel/next.js#84648, where @santhoshsathish94 already has A/B numbers and has offered to re-run it against current main. Happy to lend a hand there if a second pair of hands helps.

Tell me if I have got the tradeoff wrong.

@haoku123

haoku123 commented Sep 3, 2026

Copy link
Copy Markdown

Following up with the evidence I offered to gather. I ran this locally against current main (React @ 6c3bd60). Summary first, then the reproducible bits.

1. main is still affected (code level)

  • packages/react-server/src/ReactFlightServer.js:6692 still builds the reason with a plain new Error(...).
  • createErrorWithoutStack does not exist anywhere on main — it is introduced by this PR.

Nothing has landed that changes this path.

2. What V8 actually retains — the dividing line is argument vs. closure

I built a small harness (node --expose-gc) that does 60 iterations with a ~1.6 MB payload each and measures retained heap with stackTraceLimit = 10 vs 0:

how the payload is reachable from the frame that throws retained (capture=10) retained (capture=0)
passed as an argument (f(request)) 4.2 MB 4.1 MB → not retained
the receiver (this.x(), payload on the object) 95.7 MB 4.1 MB → retained
captured by closure 95.8 MB 4.2 MB → retained
arrow fn invoked as a method + closure (React's shape) 95.8 MB 4.2 MB → retained

So the stack does not retain values merely passed as arguments — but it does retain what the throwing frames reach via closure context or receiver. That distinction is the whole ballgame here.

3. React's real path sits on the retained side of that line

I captured the actual synchronous stack of the completion reason on the real ReadableStream renderer (server.edge), not the noop renderer:

at flushCompletedChunks  (react-server/src/ReactFlightServer.js:6692)
at startFlowing          (react-server/src/ReactFlightServer.js:6802)
at Object.pull           (react-server-dom-webpack/src/server/ReactFlightDOMServerEdge.js:169)  <-- method call
at Object.pullAlgorithm  (node:internal/webstreams/util:174)

ReactFlightDOMServerEdge.js:169 is the pull of the ReadableStream underlying source; request is captured by that closure, not passed down as an argument. Per the table above that is the retained shape. (The noop renderer's stack is a poor proxy — it bottoms out in processTicksAndRejections via plain function calls, which is why I checked the real one.)

4. The PR's fix closes it

Swapping new Error(m) for the PR's createErrorWithoutStack(m) in that same harness: 95.7 MB → 4.1 MB (~23x). The try/finally also holds stackTraceLimit steady, so later stacks are unaffected.

What this does and does not establish

Established: the mechanism is real, main still has it, React's own completion path is on the retained side, and this PR's change removes the retention in a controlled harness.

Not established: the magnitude in a real Next.js process. My harness uses a synthetic payload; the real cost is the render's cache scope and RSC payload hanging off that same frame. That gap is what the reproduction in vercel/next.js#84648 measures, and I'd rather that number stay the one we quote for impact.

I'm still not proposing any of this as a merged test — it needs --expose-gc, and ReactCache-test.js has no GC-assertion precedent, so it would be flaky by construction. This is review evidence, offered for what it's worth. Harness below if you want to poke at it.

v8-retention.js
const COUNT = 60, SIZE = 200_000;
const makePayload = s => new Array(SIZE).fill(s);

// React's real shape: ReadableStream({ pull: (controller) => {...} })
function makeStreamLike(seed) {
  const payload = makePayload(seed);
  return {
    type: 'bytes',
    pull: () => {
      const err = new Error('This render completed successfully.');
      err.__touch = payload.length;   // keep a real dependency on the capture
      return err;
    },
  };
}

function measure(label, captureStack, fn) {
  const prev = Error.stackTraceLimit;
  Error.stackTraceLimit = captureStack ? 10 : 0;
  const errors = [];
  for (let i = 0; i < COUNT; i++) errors.push(fn(i));
  Error.stackTraceLimit = prev;
  global.gc(); global.gc();
  const after = process.memoryUsage().heapUsed;
  if (errors.length !== COUNT) throw new Error('unexpected');
  return after / 1024 / 1024;
}

function scenario(name, build) {
  measure(name + ' warmup', true, build);
  const withStack = measure(name, true, build);
  const without = measure(name, false, build);
  console.log(`${name}: capture=${withStack.toFixed(1)}MB nocapture=${without.toFixed(1)}MB ` +
    `${withStack > without * 1.1 ? 'LEAK OBSERVED' : 'no difference'}`);
}

scenario('closure capture', i => {
  const payload = makePayload(i);
  function inner() { const e = new Error('x'); e.__touch = payload.length; return e; }
  return inner();
});
scenario('stream pull() method', i => makeStreamLike(i).pull());

Run with node --expose-gc v8-retention.js.

@haoku123

haoku123 commented Sep 6, 2026

Copy link
Copy Markdown

Bumping this with a concrete offer, since the open question from review was "does it still happen on main?"

I can run the end-to-end reproduction from vercel/next.js#84648 against current main and report the before/after heap numbers — that's the one piece of impact evidence still missing from the chain (my harness proves the mechanism and the fix locally, but uses a synthetic payload, so the real-world magnitude belongs to that repro).

@eps1lon — is the evidence I posted enough to unblock review, or would you like the main reproduction numbers first? Happy to do either. No rush, just want to keep this moving.

@xabierlameiro

Copy link
Copy Markdown

@santhoshsathish94 thanks for asking. Two corrections on my numbers:

  • They're not production data. They come from your repro on my laptop, so please move them out of "Independent production validation".
  • "The arms never overlap" held for that session. Later runs on the same machine and Node sometimes came back flat without the flag (vercel/next.js#84648). The A/B shows what the stack costs when retention builds up, not how often it does.

Also relevant for measuring this PR: Node 24.20.0 removes the stack part on another path. On vercel/next.js#84884's repro, the same build retains +17.02 MB per 1000 requests on 24.18 and +4.62 on 24.21 (details). I haven't measured this call site on 24.20+, but an A/B of this change should state the Node version.

@haoku123 if you run the e2e repro against main, I'd abort at 200 ms instead of 60, count what reaches the upstream, and do three runs per arm.

@santhoshsathish94

Copy link
Copy Markdown
Author

I have rewritten the description. The PR now stands on the code rather than on heap numbers, and
I have removed the impact tables and the "independent production validation" section entirely.

@eps1lon, on your two questions:

The test. You are right, and I should have said so plainly the first time instead of arguing
around it. It holds a strong reference to the signal in the test scope, so the most it can prove is
an invariant -- that the completion reason carries no captured frames -- not that anything is
reclaimed. The description now says exactly that. If an invariant test is not worth its keep here I
am happy to drop it and land the change alone.

Still on main? Yes at the code level. flushCompletedChunks still builds the reason with a
plain new Error and createErrorWithoutStack does not exist on main; @haoku123 checked this
against 6c3bd60. Nothing has landed on that path.

How much it costs in practice, I have stopped claiming. Two things changed my mind: run-to-run
variance on the shared repro is larger than the effect I was attributing to it (@xabierlameiro got
602 / 826 / 875 MB and then a flat run under 136 MB from identical inputs), and Node 24.20 appears
to remove much of the stack cost by itself (+17.02 MB per 1000 requests on 24.18 vs +4.62 on 24.21,
on vercel/next.js#84884's repro). I would rather not put a number on this than put a shaky one on it.

What is left after all of that is the narrow thing, and I think it stands on its own: the reason is
internal, never surfaced, and its stack is never read, yet the object is retained for the request
lifetime and the frames reach the completed render. The frames removed are all inside React, so no
application frame can ever appear in them. #34864 and #37086 accepted this shape on paths where the
stack is surfaced and merely capped it; this one is never surfaced, so it needs zero frames.

The alternatives remain open if the global toggle is the sticking point: a module-level singleton
reason, or a non-Error reason.

@xabierlameiro -- thank you for the correction, the section is gone. Labelling laptop runs as
production data was my error, not yours. @haoku123 -- the closure-versus-argument distinction in
your harness is the clearest statement of the mechanism in this thread; thank you for digging it out.

Comment on lines 6709 to 6714
// Internal cleanup signal, never surfaced to the user. It must not capture a
// stack — see createErrorWithoutStack (#37288).
const abortReason = createErrorWithoutStack(
'This render completed successfully. All cacheSignals are now aborted to allow clean up of any unused resources.',
);
request.cacheController.abort(abortReason);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

We can just abort with a string here and comment that we omit a stack because the stack isn't useful. The only useful part is the async stack ("which render completed?") which isn't available in this error.stack.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in 0f283ae -- both changes as you described them.

The completion site now aborts with the string, and the comment gives your reason rather than mine:
the only stack worth having here is the async one that says which render completed, and that is not
in error.stack. The stackTraceLimit helper is gone with it, so nothing touches process-wide state
any more. I also removed the leak-framed comment on the fatalError path -- you are right that a
stack is the default and only its absence needs explaining.

Two things worth flagging rather than leaving for CI to find.

An existing assertion had to change. ReactCache-test.js on main asserts
renderedCacheSignal.reason.message, which is undefined once the reason is a string. It now
asserts the reason itself. That assertion predates this PR and is the only place in the suite that
depended on this reason being an Error.

Why a string is safe on the consuming path, since an earlier review here argued for keeping the
Error type: the reason reaches erroredTask through abortStream, abortIterable and
abortBlob, and from there emitErrorChunk, which already branches on error instanceof Error and
for a plain value produces String(error) with an empty stack. So this is a shape that path already
supports.

I also dropped the stack-invariant test this PR had added. With a string there is no stack to assert,
and your earlier point about it stands regardless.

The description is updated to match.

Comment on lines +4476 to +4477
// Unlike the success path (#37288), this runs at most once per request (not per
// completed render), so capturing a stack here is fine and not a leak source.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This can be removed. It's not about leaking but whether we want a stack and we want one by default. Only omitting the stack needs a reason.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

done.

Per review: the stack on this reason is not useful, so use a string and drop the stackTraceLimit helper. Also removes the leak-framed comment on the fatalError path, and updates the existing cacheSignal assertion, which read reason.message.

@santhoshsathish94 santhoshsathish94 left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The suggested changes are done, thanks for rightly pointing out, hope this is how the actual learning happens

@ManagrNo

Copy link
Copy Markdown

+1 from production; the fix is right. One detail worth adding to the description: the pinned scope isn't only the render closure — the processImmediate frame's receiver is the Immediate, which carries the ALS store and queue links, so one retained reason chains to other requests' Request objects (retainer path in #37288 comment).

@wverri

wverri commented Oct 5, 2026

Copy link
Copy Markdown

Independent confirmation from a production-like setup, in case it helps the review.

Setup: Next 16.3.8 (bundled React 19.3.0-canary-cbb046ab-20260731), Node 22, output: "standalone" in Docker, Postgres via pg + Prisma adapter. Load: 50 concurrent connections against App Router pages that query the DB during render.

Before: with --max-old-space-size=384 the server crashed with "Ineffective mark-compacts near heap limit" after ~3,500 requests. Sequential requests didn't leak; it only shows up when renders overlap. Heap snapshots showed the same chain described here: long-lived object (the pg pool connection socket and its connect listeners) → that request's AsyncLocalStorage store → cacheController.signal.reason → CallSiteInfo → the Immediate the flush ran in → _idleNext → every later Immediate, each holding another request's store and its own abort Error.

After creating that abort reason without a stack (same idea as this PR; we patch Error.stackTraceLimit = 0 around it in next/dist/compiled/next-server/app-page*.runtime.prod.js as a postinstall workaround):

50 connections before after
requests before OOM (384 MB heap) ~3,500 none, 37k+ stable
throughput 282 req/s 535 req/s
p95 latency 502 ms 241 ms
peak RSS (1 GB heap) 1.35 GB 369 MB

Disabling OpenTelemetry, response compression or resizing the DB pool did not change the outcome; only removing the stack did. Happy to share more detail.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

7 participants