Repository navigation
[react-server] Don't capture a stack for the render-completed cacheSignal abort reason - #37289
santhoshsathish94 wants to merge 8 commits into
Conversation
…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
|
Thanks for the fix — the diagnosis is correct (V8 captures the stack eagerly at Two suggestions before this lands:
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
Minor: the |
…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.
|
Thanks for the thorough review — all three addressed in 1. Guarded the global mutation with 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 2. Added a regression test. It asserts the completion 3. 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):
|
|
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 @sebmarkbage / @unstubbable — since this touches the |
|
Thanks for addressing the review — the |
dianatofficial
left a comment
There was a problem hiding this comment.
Looks good. Error handling is solid.
|
@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.
|
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 |
|
Resolved the conflict with main. Upstream moved the completed-render I have the test suite running locally now, so the earlier note about not being able to build/run it no longer applies:
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. |
|
Following up here — I reviewed this change earlier and it still looks correct to me (the 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:
@sebmarkbage @unstubbable @gnoff — is anything else blocking review, or is this just waiting on bandwidth? No pressure, just trying to be useful. |
| 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([]); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
|
@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
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. 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 At the code level, yes. On current 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 A 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 Tell me if I have got the tradeoff wrong. |
|
Following up with the evidence I offered to gather. I ran this locally against current 1.
|
| 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.
|
Bumping this with a concrete offer, since the open question from review was "does it still happen on I can run the end-to-end reproduction from vercel/next.js#84648 against current @eps1lon — is the evidence I posted enough to unblock review, or would you like the |
|
@santhoshsathish94 thanks for asking. Two corrections on my numbers:
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 |
|
I have rewritten the description. The PR now stands on the code rather than on heap numbers, and @eps1lon, on your two questions: The test. You are right, and I should have said so plainly the first time instead of arguing Still on How much it costs in practice, I have stopped claiming. Two things changed my mind: run-to-run What is left after all of that is the narrow thing, and I think it stands on its own: the reason is The alternatives remain open if the global toggle is the sticking point: a module-level singleton @xabierlameiro -- thank you for the correction, the section is gone. Labelling laptop runs as |
| // 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| // 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. |
There was a problem hiding this comment.
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.
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
left a comment
There was a problem hiding this comment.
The suggested changes are done, thanks for rightly pointing out, hope this is how the actual learning happens
|
+1 from production; the fix is right. One detail worth adding to the description: the pinned scope isn't only the render closure — the |
|
Independent confirmation from a production-like setup, in case it helps the review. Setup: Next 16.3.8 (bundled React Before: with After creating that abort reason without a stack (same idea as this PR; we patch
Disabling OpenTelemetry, response compression or resizing the DB pool did not change the outcome; only removing the stack did. Happy to share more detail. |
Fixes #37288
Summary
On every successful Flight render,
flushCompletedChunksbuilds anErrorand stores it onrequest.cacheController.signal.reason:That
Errorcaptures a stack. The stack is never read, and it could not help anyone if it were: theframes are
flushCompletedChunks->startFlowing->pull, all internal, and the one usefulquestion -- which render completed -- lives in the async stack, which
error.stackdoes not carry.Meanwhile the object is retained for the lifetime of the request as
signal.reason, and V8'scaptured 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
emitErrorChunkalready brancheson
error instanceof Errorand, for a plain value, producesString(error)with an empty stack.Error.stackTraceLimit, so no process-wide state is involved.could never contain an application frame.
Test
One existing assertion changed.
ReactCache-test.jsreadrenderedCacheSignal.reason.message; witha 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-serverandyarn test react-reconciler, lint/prettier/flow -- not runlocally (toolchain), relying on CI.