next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Next.js 16.2.2 standalone + Cache Components: cached internal streamed fetches cause unbounded arrayBuffers growth and OOM

Open mdotk opened this issue 8 months ago • 18 comments

Link to the code that reproduces this issue

https://github.com/mdotk/next-standalone-memory-repro

To Reproduce

  1. Clone the repro repo and install dependencies.
npm install
  1. Build the app.
npm run build
  1. Start the standalone server.
PORT=3025 npm run start:standalone
  1. In another shell, run the reproducing load.
BASE_URL=http://127.0.0.1:3025 \
DURATION_MS=180000 \
CONCURRENCY=64 \
PAGE_WEIGHT_KB=2048 \
API_WEIGHT_KB=2048 \
MIX=page,api,page,page \
MAX_LOGGED_FAILURES=20 \
npm run load
  1. Sample memory during the run.
curl 'http://127.0.0.1:3025/api/health?sample=1'

Current vs. Expected behavior

Current:

On [email protected] with output: "standalone" and cacheComponents: true, the standalone server shows rapid unbounded memory growth under sustained high-cardinality traffic once the app is doing cached internal server-side fetch() calls against a streamed JSON route.

In one local run:

  • baseline was about 95 MB rss
  • after ~28s, memory reached about 1.58 GB rss / 589 MB arrayBuffers
  • after ~38s, memory reached about 2.36 GB rss / 1.04 GB arrayBuffers
  • after ~62s, memory reached about 2.42 GB rss / 1.95 GB arrayBuffers
  • after ~180s, memory reached about 3.43 GB rss / 4.31 GB arrayBuffers

The standalone server then died with:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

While the server is destabilizing, the load generator starts receiving:

  • ECONNRESET
  • UND_ERR_SOCKET
  • ECONNREFUSED

Expected:

Memory should stabilize or at least be reclaimed after responses complete. Large temporary spikes under load are one thing, but the standalone process should not continue retaining arrayBuffers/external memory until it exits with OOM.

Provide environment information

Operating System:
  macOS 15.x arm64
Node.js version:
  25.1.0
Next.js version:
  16.2.2
Output mode:
  standalone
Other config:
  cacheComponents: true
  compress: false

Additional context

A few things make this feel close to the existing response-retention / runtime-retention family:

  • the failing repro requires cached internal server-side fetch()
  • the internal fetched route returns a streamed JSON response
  • the exploding categories are rss, external, and especially arrayBuffers
  • the app is generating many unique request paths over time

I also ran the same repro app locally with next start as a control. I know that is not the supported way to run an app configured with output: "standalone", so I am not presenting it as the main repro. But it is useful signal:

  • with next start, the app still showed large temporary growth under the same load
  • after the shorter control run stopped, memory recovered back down instead of the server dying
  • with the standalone server, the same app kept climbing and eventually exited with OOM

That difference made me file this specifically against the standalone runtime path.

This also overlaps with symptoms in:

  • #90433
  • #90895
  • #90898
  • #75994

mdotk avatar Apr 03 '26 01:04 mdotk

Additional production signal from the same app after filing this issue:

  • We kept the app on [email protected], output: "standalone", and cacheComponents: true.
  • We raised our production restart guard from 5 GiB to 7 GiB to see whether this was mainly a restart-threshold artifact.
  • Result: restart frequency decreased, but the underlying memory trend did not change. The process still climbs steadily until it reaches the new ceiling and is recycled.

Recent production pattern:

  • Around 2026-04-04T12:20Z the process was already at ~6.9 GiB
  • 2026-04-04T12:25Z: ~7.29 GiB
  • 2026-04-04T12:29Z: guard-triggered restart at 7601336320
  • 2026-04-04T12:30Z: second restart at 7593152512
  • after restart it returned to low memory and began the same steady climb again

The runtime artifact growth also continues during these runs. In the same production windows we still see:

  • .next/server/app growth continuing over time
  • fetch-cache file count continuing to increase
  • large server/cache footprint before each restart window

So increasing the restart limit reduces restart frequency, but does not produce stabilization. The process still grows until it reaches whatever ceiling we give it.

This strengthens the runtime/deployment suspicion rather than the “small application leak” theory:

  • our minimal repro still shows standalone OOM behavior on 16.2.2
  • the next start control in that repro behaved materially better after load stopped
  • our production app still shows the same upward-only pattern under standalone, even when the restart threshold is raised

mdotk avatar Apr 04 '26 22:04 mdotk

I'm seeing a very similar issue. Unbounded growth and OOM after going from 15 -> 16 and changing from unstable_cache to "use cache". With no other changes to the app.

stofolus avatar Apr 08 '26 07:04 stofolus

I can confirm this issue as well. This is 16.2.4, standalone and cache components. Here is what I see in our server logs after it starts hitting max memory on a 16gb server. Restarting the server releases the memory and I don't see these for a while until this issue starts to build up again:

failed to forward action response TypeError: fetch failed at ignore-listed frames {
  [cause]: Error [HeadersTimeoutError]: Headers Timeout Error at ignore-listed frames {
    code: 'UND_ERR_HEADERS_TIMEOUT'
  }
}

r0bdiabl0 avatar May 04 '26 13:05 r0bdiabl0

Possibly a distinct regression in the same area — flagging here since this is the active arrayBuffers/standalone thread.

Self-hosted, output: "standalone", containerized Node server. A single dependency bump — next 16.1.6 → 16.2.6 — took steady-state memory from ~6 GB to ~17 GB under an identical workload. Growth is off-heap (rss/external/arrayBuffers), not JS heap; --max-old-space-size has no effect.

This looks separate from the root cause tracked here: in our 16.2.6 build the #90897 fixes are present — dist/server/lib/clone-response.js registers both cloned1 and cloned2 with FinalizationRegistry, and dist/server/lib/lru-cache.js throws on a 0 size — yet 16.2.6 still runs ~3× the memory of 16.1.6 on the same traffic. That points to an additional leak somewhere in the 16.2.x line beyond the clone-response/LRU issue. The May 2026 security release (GHSA-c4j6-fc7j-m34r WS-upgrade SSRF, http-proxy CVE-2026-29057, streaming-fetch-hang fix) is one candidate, but the bump spans all of 16.2.x.

Bisecting within 16.2.x to localize; will follow up with process.memoryUsage() numbers.

Lorenzo45 avatar May 16 '26 07:05 Lorenzo45

We hit this leak hard in production and did a fairly deep forensic pass. Sharing because the evidence suggests the dominant mechanism is different from (and additional to) what #94238 fixes and it reproduces without cacheComponents.

Environment

  • next 16.2.6, react/react-dom 19.2.4, node 22.22.3, output: "standalone", Turbopack build
  • cacheComponents NOT enabled
  • Docker Swarm, 3 replicas, 5.5GiB memory limit each
  • Traffic: sustained high-cardinality crawler-heavy load over a large CMS-backed site (mostly dynamic SSR + ISR)

Symptom

Every replica leaks ~90–150MB/min of RSS from boot. At death (~25–40 minutes): ~3GB V8 heap + 2.5–3.4GB of live arrayBuffers, then cgroup OOM kill (Memory cgroup out of memory: Killed process (next-server), anon-rss: 5.53GB) or health-check kill once event-loop stalls reach 1.5–2.6s. An 8-minute V8 sampling heap profile on one replica showed live arrayBuffers growing 460MB → 1.06GB, with the live allocations attributed to React Flight render/parse.

Finding 1: #94238 does not fix this case (verified in production)

We backported #94238 into 16.2.6 (src/server/lib/{dedupe-fetch,clone-response}.ts are byte-identical between v16.2.6 and that PR's base, so the backport is exact; verified active at runtime via a boot marker). The leak slope was unchanged.

Then the decisive experiment: on a replica at 4.1GB RSS / 2.09GB arrayBuffers, we forced a double full GC via the inspector (HeapProfiler.collectGarbage twice, 5s apart). Result:

BEFORE: rss 4,118,712,320  arrayBuffers 2,090,208,082
AFTER : rss 3,999,309,824  arrayBuffers 2,064,898,972   (~1% freed)

So the retained bytes are strongly reachable. This is not the FinalizationRegistry/GC-lag retention that #94238's deterministic cancellation addresses. (Also worth noting: without cacheComponents, React.cacheSignal() returns null for our renders, so #94238 is largely inert here by design.)

Finding 2: the strong retainer (root-anchored ownership analysis)

We parsed a full production heap snapshot (replica at 5 minutes of age, already 460MB of arrayBuffers) and aggregated ownership paths for all system / JSArrayBufferData nodes, using BFS-from-GC-roots distances so every chain walks strictly root-ward (no cycles). The dominant family, ~137MB across ~16,000 buffers at just 5 minutes:

JSArrayBufferData (chunk)
  ← .buffer of Uint8Array
  ← element of chunk Array captured in a `pull` closure          // streamed-from-buffer queue
  ← pullAlgorithm ← [[kState]] of ReadableStreamDefaultController
  ← [[kState]] of ReadableStream
  ← props.reactServerStream                                      // app-render: reactServerResult.tee() passed as <App reactServerStream={...}/>
  ← props of the App element ← closure contexts
  ← onShellReady of the Fizz request/options object
  ← <symbol kResourceStore> on a LIVE Timeout / pending Promise  // AsyncLocalStorage resource store
  ← active timer list (_idleNext/_idlePrev → TimersList → timerListMap) / see moduleCache variant below

Interpretation: react-dom-server runs each render inside its internal requestStorage AsyncLocalStorage. Any async resource created during a render and still alive after it

A pending long-lived timer, an unsettled promise carries kResourceStore → the Fizz request → its onShellReady closure → the App element props → the teed reactServerStream and every chunk it buffered.

One such lingering resource per render pins the render's entire RSC payload. Under real-world traffic there is almost always something (library timers, fetch timeouts, circuit breakers), so this leaks per-request at scale. We removed one app-level source of long-lived in-render timers entirely (TanStack Query server-side gcTime timers) with no measurable effect. Eliminating pin sources one by one is unwinnable at app level.

A particularly sharp variant from the same aggregation: Turbopack's moduleCache retains module-loading promises permanently, so whichever request first loads a given module is pinned forever:

... ← flightData/segmentData ← closure contexts ← onError of Fizz request
    ← <symbol kResourceStore> on Promise
    ← promise in closure `get` ← get namespaceObject ← moduleCache ← clearChunkCache

Happy to provide the full ownership-signature reports, the sampling profile, or run instrumented builds against this workload: it reproduces within minutes at moderate load.

aadelgrossi avatar Jul 22 '26 16:07 aadelgrossi

I reproduced this on the linked repro and ran a few controls around it. Numbers below in case they are useful.

Setup: the repro as published (next 16.2.2, next build --webpack, standalone output, cacheComponents on, compress off), Node 25.7.0, macOS 15 arm64. I start the standalone server.js directly with --expose-gc --max-old-space-size=6144 so I can sample after a forced full GC, and drive it with the repro's own scripts/load.mjs.

It reproduces, and the memory survives GC.

With the documented load (CONCURRENCY=64 PAGE_WEIGHT_KB=2048 API_WEIGHT_KB=2048 MIX=page,api,page,page, 180s), 4053 requests, none failed:

heap arrayBuffers rss
baseline, post-GC 22 MB 0 MB 93 MB
end of load 3100 MB 3575 MB 3816 MB
3 forced GCs + 30s idle 2916 MB 3430 MB 3121 MB

About 4% comes back. The rest stays. That is in the same range as the ~1% @aadelgrossi measured in production with a double HeapProfiler.collectGarbage, so whatever holds those bytes is already in this minimal repro. No production-scale replica needed to chase it.

With a single cache key it all goes away.

Two lines changed in scripts/load.mjs so every request asks for slug-fixed and variant=0. Same duration, same concurrency, same payload size:

requests heap post-GC arrayBuffers post-GC
unique slugs 4053 2916 MB 3430 MB
one fixed slug 37976 33 MB 3 MB

Nine times the traffic through the same code and memory stays flat, so it follows the number of distinct cache keys rather than the volume. Disk does the same thing: the unique-slug runs left 30 GB in .next/standalone/.next/cache/fetch-cache (~15k requests in total), the fixed-slug run 2.7 MB.

Lighter runs peak just as high and give it all back.

Both with unique slugs, 90s:

requests peak arrayBuffers post-GC
24 connections, kb=2048 3281 818 MB 51 MB
64 connections, kb=512 4017 2022 MB 50 MB

I could not pin down where the boundary sits. A big peak on its own is recoverable; only the heavy run holds on to it. Worth knowing if you try to reproduce this at half the payload weight, because there it looks clean.

The gap between what the process reaches and what it keeps is easy to miss. One command against the same repro, with kb=2048 in next-leak.config.json:

npx [email protected] . --routes '/[slug]' --cycles 3 --requests 700 \
  --connections 24 --idle 20 --max-old-space 6144
✔ /[slug]  stable  (-7.03 MB/1000 req)  heap 49.2 MB → 45.9 MB → 35.6 MB → 36.0 MB
    ▲ peak pressure: peaked at 2059.8 MB rss under load while retaining 36.0 MB

The peak lands anywhere between 2.0 and 3.1 GB depending on the run (it is the highest value sampled, not a hard maximum). The 36 MB it retains does not move.

Client disconnects are not the trigger, at least not here.

#94919 and the kResourceStore chain point at streams that never finish, so I tried that too: raw sockets, cut 120ms in, 200 abandoned requests per cycle, three cycles. Growth after GC was +0.6 MB per cycle. The AbortController#signal ← cacheController ← AsyncContextFrame chain does show up in those snapshots, but it is not what fills the heap in this repro.

Happy to share run.json, the raw snapshots or the exact commands if any of this is worth digging into.

(Measured with next-leak, which I maintain.)

xabierlameiro avatar Jul 25 '26 22:07 xabierlameiro

Additional production confirmation (Next 16.3.0, latest stable, standalone)

We hit this on a production content site: [email protected] (latest stable), output: "standalone", Node 24, in a container with a ~1 GB memcg limit, cacheComponents: true, partialPrefetching: true, self-hosted Redis cache handler (cacheMaxMemorySize: 0).

Symptoms match exactly:

  • Two instances OOM-restart every ~30–50 min (the higher-traffic one faster). Steady RSS climb (~10–15 MB/min on the busy instance), killed at ~1 GB anon-rss by cgroup OOM. Raising the memory limit delays but does not stop it.
  • In-process process.memoryUsage() at ~1 GB RSS: heapUsed ≈ 420 MB, external ≈ 324 MB, arrayBuffers ≈ 313 MB. Both JS heap and off-heap arrayBuffers grow monotonically.

Heap-snapshot diff (two snapshots ~3 min apart, right after a restart):

  • JSArrayBufferData +13 MB (dominant grower).
  • Retained RSC postponed resumable-state strings (nextSegmentId/rootFormatContext, 200–360 KB each) accumulating.
  • Promise / InternalReadableStream / Set object counts growing.
  • zlib_memory did not grow (rules out response-compression as the retainer).

Retaining-path analysis: the RSC payload strings are reachable via [property:postponed] on a render object; one is pinned by a suspended async Generator (render async-iterator), another via renderOpts — consistent with a React Flight render whose resumable state is never released. A forced global.gc() recovers almost nothing (strongly reachable), matching the "per distinct cache key, survives GC" behavior reported above.

Config note: our Redis cache handler stores/fetches normally (not the leak), and growth is not gzip (zlib flat). We had a multi-day stable baseline on the same Next version with partialPrefetching: false; re-enabling partial prefetching restarted the fast OOM cycle. It behaves like an amplifier of the same per-cache-key render retention, not the root cause.

Happy to share sanitized snapshots or run instrumented builds if it helps.

j4tmr avatar Aug 12 '26 07:08 j4tmr

next 16.3.0, standalone, Turbopack build, cacheComponents: true. Heap snapshot diffs on production pods, two findings:

Turbopack standalone gotcha: patching dist/server/lib/{clone-response,dedupe-fetch}.js is dead code. The runtime executes minified copies inside dist/compiled/next-server/app-route-turbo.runtime.prod.js (which owns the process-wide fetch patch; the app-page copy is tree-shaken to a bare Symbol.for("next-patch")). Our dist backport of #94238 measured zero change overnight; a boot marker in dist/server/lib can still print while the bundled copy stays unpatched. Verify in the compiled bundle.

Two separate retainer families:

  1. Fetch dedupe clone retention (#94238's target): pullAlgorithm -> ... -> ArrayBuffer.backing_store chains grew 318 -> 799 in 9 minutes (~100 never-drained tee branches/min), arrayBuffers ~14MB/min linear until cgroup OOM. After applying the PR's semantics to the compiled bundle (WeakRef + 60s unref'd timer cancel instead of cacheSignal): chains become a bounded steady state, slope drops 3-4x traffic-adjusted.
  2. Survives that fix: segmentData / prerenderChunks / rscData Buffers pinned by promise/closure contexts, ~700-900Mi/h RSS at daytime traffic on a high-cardinality workload (thousands of pages x 18 locales, crawler-heavy). Matches @j4tmr and @aadelgrossi.

Can share sanitized snapshots or run instrumented builds.

0-don avatar Aug 13 '26 10:08 0-don

Follow-up: root-caused and fixed a second retention mechanism (the cacheComponents "render retention" family, distinct from the fetch-clone one above).

Retainer analysis on 16.3.0 standalone+Turbopack prod heap snapshots (BFS from GC roots, weak edges excluded): runtime prerenders park an abort-reason Error on the render AbortSignal, and that signal outlives the render inside long-lived registries (InstantValidation registry values plus abort listeners). V8 keeps an Error's stack as structured CallSiteInfo frames until .stack is first read, and those frames hold the closure contexts of the whole render: prerenderChunks / segmentData / rscData buffers. Nothing ever reads .stack on these swallowed abort reasons, so every prerender pins its buffer state permanently. In our traffic: ~82MB across ~3,900 pinned buffers per 15min, per pod.

Workaround that kills it from app code (instrumentation.ts register()):

const origAbort = AbortController.prototype.abort;
AbortController.prototype.abort = function (reason?: unknown) {
  if (reason instanceof Error) void reason.stack;
  const out = origAbort.call(this, reason);
  const settled = this.signal.reason;
  if (settled instanceof Error) void settled.stack;
  return out;
};

Reading .stack once materializes the string and V8 drops the frames, so the pin becomes a short string. Verified on same-age prod pods: that anchor family went from 82MB x ~3,900 buffers to 0.7MB x 39.

Suggested real fix: create prerender abort reasons stackless (plain object reason or Error.stackTraceLimit = 0 around construction), or format the stack eagerly at creation, or stop retaining settled render signals in those registries.

0-don avatar Aug 13 '26 13:08 0-don

Additional data from a production marketplace (two deployments, tens of thousands of landing pages, crawler-heavy traffic): [email protected] and 16.3.1 (both reproduce identically), output: "standalone", Turbopack build, cacheComponents: true, Node 22/24.

Key characterization: the retention is per unique rendered URL, not per request. Hammering one URL 8,000 times is flat; ~1,000 unique URLs OOM a 320MB heap. In production this was ~1.2MB retained per unique URL (~100MB/h under crawler traffic), OOM-cycling a 1GB-capped container every ~9h with Ineffective mark-compacts near heap limit - the live set survives a full mark-compact. A heap snapshot after rendering exactly 280 unique URLs contains exactly 280 complete page HTML documents (109.5MB of strings) plus 86.7MB of JSArrayBufferData.

By disabling suspects one at a time and re-measuring the slope, we found three separate retention families:

1. Abort-reason Error lazy stack pinning render closures (~0.6MB/URL) - same mechanism @0-don described. Retainer chain from the snapshot:

render store (.cacheController) -> AbortController#signal -> AbortSignal <kReason>
  -> Error -> lazy stack (CallSiteInfo[]) -> closure contexts -> resolved render
  promise -> { html: "<!DOCTYPE html>..." }

Note for anyone applying the AbortController.prototype.abort monkey-patch: it was only partial for us. Some aborts reach the signals through native propagation (e.g. AbortSignal.any/timeout dependents), which never calls the patched prototype. Only Error.stackTraceLimit = 0 fully eliminated this family in our tests (not shippable for us - it strips every stack trace).

2. The ISR page memory cache in the compiled Turbopack runtime bundles does not evict. With cacheMaxMemorySize at its default (52428800 verified in the baked required-server-files.json), the snapshot shows the leaked HTML sitting in FileSystemCache's module-level memoryCache LRU inside app-page-turbo.runtime.prod.js - 109MB+ of nominal entry size in an LRU configured for 50MB, zero evictions. Either the maxSize plumbing or the size accounting is broken in the bundled copy. Workaround that surgically removes this family without touching the (healthy, bounded) use cache LRU: __NEXT_TEST_MAX_ISR_CACHE=0 (the on-disk ISR cache still works). cacheMaxMemorySize: 0 also works but additionally turns the use cache default handler into a no-op, which re-renders every cached section per request.

3. Never-drained fetch-clone tee branches (#94238's target, ~0.1-0.2MB/URL). With families 1+2 disabled, a retainer-path histogram over all remaining ArrayBuffers shows ~2,800 of 3,825 sitting in ReadableStreamDefaultController internal queues - buffered chunks of tee branches that are never read. No app-level fix we could find; patching dist/server/lib/{clone-response,dedupe-fetch}.js is dead code under Turbopack as noted above (the runtime executes the minified copies in dist/compiled/next-server/*.runtime.prod.js).

Combined app-level mitigations (abort-stack materialization + __NEXT_TEST_MAX_ISR_CACHE=0) reduce the slope ~2-4x for us; the remainder (family 3 + the native-abort share of family 1) still forces periodic restarts.

Happy to share the reproduction harness (standalone server + mock API + unique-URL load profiles + snapshot analyzers) or sanitized heap snapshots.

fiberitro avatar Aug 17 '26 14:08 fiberitro

When the fix will be released?

andreasdc avatar Aug 17 '26 22:08 andreasdc

Still reproduces on 16.3.1.

Measured the reproduction on next 16.3.1 (Node 24.18, arm64, standalone, cacheComponents: true), 6 cycles × 2000 requests at 64 connections against /[slug]?kb=2048 with a distinct slug per request, forced GC before every sample:

  • post-GC heap barely moves: 33.1 → 33.8 MB, +0.18 MB/1000 req
  • rss reaches 544.5 MB under load while the route retains 33.8 MB
  • between collections the process holds 37.5 MB of arrayBuffers against 1.0 MB after a forced GC — 37x

That last number is the one that matches the title here. The memory is reclaimable: a forced GC takes it back every cycle, which is why the retention curve looks almost flat and why a run that only samples post-GC calls this route healthy. A server that is not running full GCs between requests never gets that back, and the arrayBuffers keep climbing — which is the shape of the production reports in this thread.

One control worth adding, because it points away from cache keys: the same run with a single slug instead of a distinct one per request holds just as much between collections — 38.6 MB of arrayBuffers, 39x what it retains — while its post-GC verdict comes back stable. So in this profile the sustained arrayBuffers do not track key cardinality at all; only the small post-GC residue does. Worth knowing before anyone tunes cache keys expecting it to help.

Caveat on that: I load in 6 cycles with a forced GC between them, not the sustained 180s the reproduction script uses, so this speaks to what is held between collections rather than to how far it climbs when nothing collects.

Raw snapshots and run.json available if useful. Measured with next-leak.

xabierlameiro avatar Aug 18 '26 19:08 xabierlameiro

We hit what looks like the same leak family in production (self-hosted e-commerce storefront) and can contribute a full retainer-path attribution from heap snapshots, plus several exclusion experiments. Hope this helps narrow the fix.

Setup: Next 16.3.0 and 16.3.3 (both verified leaking identically), output: "standalone", cacheComponents: true, Node 22 (alpine, Docker), real traffic + a sitemap-sweep load test (~400 sequential requests over 202 routes).

Symptom: steady growth of both heapUsed and arrayBuffers (~1–1.5 GB/h under real traffic; ~1.5 GB retained after only 404 requests in the load test). Process dies with FATAL ERROR: Reached heap limit Allocation failed every ~7 h at the default 4 GB limit. Retention is real, not GC lag: a forced full GC (heap snapshot via --heapsnapshot-signal) after 3 min of idle still shows the memory held (snapshot size 1.1 GB vs 128 MB before load).

Retainer path (identical across dozens of the largest JSArrayBufferData targets, from a snapshot after load + idle):

JSArrayBufferData (0.8 MB each)
  <-backing_store- ArrayBuffer <-buffer- Uint8Array <-value- Object <-[i]- Array
  <-queue- Object <-kState- ReadableStreamDefaultController <-controller- Object
  <-kState- InternalReadableStream        // unconsumed tee'd branch, queue full
  <-value- Object <-entry- Object <-reactions_or_result- Promise
  <-[i]- array <-table- Map <-cache- Object
  <-resumeDataCache- Object               // <-- per-request Resume Data Cache
  <-kResourceStore- Promise               // AsyncLocalStorage store
  <-"key -> value pair in WeakMap" - [array] <-table- WeakMap
  <-context- system/Context <-previous- system/Context   // context chain
  <-context- [closure] <-_nextOriginalFetch- d [closure] // patched fetch
  <-fetch- global

So: resumeDataCache entries hold unconsumed tee'd stream branches (chunks sit in the stream controller queue), and the per-request RDC stays reachable after the response through an AsyncLocalStorage/context chain that is ultimately pinned by the scope of the patched globalThis.fetch (the wrapper carrying _nextOriginalFetch).

Exclusions we verified (each with the identical load test):

  • Not Sentry: a build with Sentry fully disabled (empty DSN, no Sentry.init) leaks identically (1.54 GB vs 1.68 GB retained after idle).
  • Not the built-in "use cache" LRU: a custom cacheHandlers.default that stores fully-buffered chunks (no tee(), honest LRU accounting) works fine but changes nothing — in snapshots the @next/cache-handlers-map subtree holds only ~1.6 MB while the RDC chain holds hundreds of MB.
  • cacheMaxMemorySize: 0: no effect on the leak.
  • Not host OOM (OOMKilled=false, host has >20 GB free); V8 heap itself hits the limit.

Since PR #94238 targets the dedupe-fetch response clones: in our snapshots the dominant chain goes through resumeDataCache (not the dedupe cache), so it may be worth checking whether the RDC path is covered as well.

Happy to provide snapshot excerpts or run patches against our reproduction setup.

Dennisjoch avatar Aug 31 '26 13:08 Dennisjoch

@Dennisjoch I have seen that chain in this repro, and there it was not the one holding the bytes. Worth saying before anyone fixes only that path.

On the public repro (mdotk/next-standalone-memory-repro, next 16.2.2) I cut 200 requests per cycle at 120 ms with raw sockets, three cycles, precisely to chase streams that never finish. Growth after a forced GC was +0.6 MB per cycle. The kResourceStore chain shows up in those snapshots, as you describe it, but what filled the heap tracked the number of distinct cache keys instead: the same load driven with one fixed slug ran nine times the traffic and stayed at 33 MB against 2916 MB, and left 2.7 MB in fetch-cache where the unique-slug runs left 30 GB.

That does not contradict your snapshots. It means the RDC chain can be present without being the dominant retainer, so a fix aimed only at it may leave the bigger one standing.

Where our numbers actually disagree is the version, not the mechanism.

  • 16.2.2, unique slugs, 4053 requests: 2916 MB heap after three forced GCs and 30 s idle. About 4% comes back. That is your symptom.
  • 16.3.1, same shape of load, distinct slug per request, forced GC before every sample: post-GC heap went 33.1 → 33.8 MB across six cycles. RSS still reached 544.5 MB and arrayBuffers sat at 37.5 MB between collections against 1.0 MB after a forced one, but none of it survived a collection.

You have 16.3.0 and 16.3.3 retaining identically. I do not think either measurement is wrong. Two variables are uncontrolled between the setups: yours is Node 22 on alpine with 202 real routes, mine is Node 24 on arm64 with a single parameterised route. Either can decide this, and the Node line matters more than it looks when the target is arrayBuffers.

One control on your side would separate the two.

Run the sitemap sweep again at the same request count, but against a single route with one fixed set of params instead of 202. If retention collapses the way it did here, we are on one leak that scales with distinct cache keys and your RDC path is how the keyed entries stay reachable. If you retain just as much on one key, it is a second mechanism, your path is the whole story for it, and the key-count behaviour is something else that still needs a name.

I can run 16.3.3 on Node 22 to close the other half of the gap if that helps. Happy to share run.json, the raw snapshots or the exact commands for any of the above.

(Measured with next-leak, which I maintain.)

xabierlameiro avatar Sep 04 '26 22:09 xabierlameiro

After thorough testing, including on prod, I can confirm that the bug is fixed in ⁠[email protected]⁠. Combined with switching the runtime to Bun v1.4.1, we managed to reduce RAM usage in Docker by half and prevent any further growth. No issues observed with the canary build at the moment. Give it a try.

axelrodvl avatar Sep 04 '26 23:09 axelrodvl

Environment:

  • Next.js 14.2
  • Node.js 25

I managed to fix the OOM on my side with two changes:

1. Adding a timeout to outgoing fetch calls. My app gets a lot of bot traffic, and some requests were hanging without the TCP connection ever being closed, so they kept piling up in memory. Adding an abort signal fixed that:

const res = await fetch(fullUrl, {
  ...fetchOptions,
  signal: AbortSignal.timeout(12000),
});

2. Switching from the default standalone cache to Redis. In my opinion there's an issue with how fetch and the built-in cache behave in standalone mode, where memory isn't being released properly. Moving the cache to Redis helped.

Redis alone was not enough. When I removed the abort timeout and kept only Redis, the pods started crashing again with OOM. It was the combination of both changes that fixed it for me.

Also: always consume or cancel the response body. Node's fetch (undici) keeps the connection and its buffers alive until the body is read. If you return early without reading it (e.g. on a non-OK status), the resources aren't released, and under heavy traffic this adds up:

if (!res.ok) {
  await res.body?.cancel(); 
  throw new Error(`Request failed: ${res.status}`);
}

const data = await res.json(); // or res.text()

Hope this helps anyone else running into the same issue.

alex-dev-makarov avatar Oct 14 '26 20:10 alex-dev-makarov

Data point for anyone deciding whether to upgrade: on Node 25 this still reproduces on 16.4.3. On Node 26 I could not reproduce it on either 16.2.2 or 16.4.3.

Setup: the linked repro (mdotk/next-standalone-memory-repro) with its config unchanged: output: "standalone", cacheComponents: true, compress: false, next build --webpack. Linux x64. Each copy was rebuilt with the Node version it ran on, and the server was started with --expose-gc. I used the documented load: 180 s, CONCURRENCY=64 PAGE_WEIGHT_KB=2048 API_WEIGHT_KB=2048 MIX=page,api,page,page, a unique slug per request. I added one route that calls gc() and returns process.memoryUsage(), identical in both copies. "Post-GC" means after 3 forced GCs plus 30 s idle. React is 19.1.0 with 16.2.2 (the repro's lockfile) and 19.3.0 with 16.4.3.

Node Next max-old-space requests peak rss post-GC rss / heapUsed / arrayBuffers (MB)
25.9.0 16.2.2 6144 3440 6952 4619 / 2853 / 3321
25.9.0 16.4.3 6144 4759 6117 6048 / 355 / 4828
25.9.0 16.4.3 5120 4584 4740 4651 / 113 / 1140
26.7.0 16.2.2 5120 6699 819 634 / 41 / 76
26.7.0 16.4.3 5120 6195 885 732 / 42 / 73
26.7.0 16.4.3 6144 7110 883 718 / 43 / 77
  • On Node 25 both Next versions retain gigabytes after GC. At a 5120 heap cap the process saw-tooths near the ceiling and climbs again; the cap bounds it but does not stop it. No run died within 180 s.
  • On Node 26, memory goes flat about 30 s into the load. This holds for both Next versions at a 5120 heap cap and for 16.4.3 at 6144 (16.2.2 was not run at 6144). The heap returns to baseline after GC.
  • With the same code, Next version, and load, swapping only Node 25.9.0 for 26.7.0 flips the result at both heap caps.
  • The on-disk fetch-cache still grows one file per unique request in every run, 4.6–9.4 GB in 180 s.

I have not bisected which Node 26 change makes the difference, and I have not tested Node 22 or 24.

nextor2k avatar Oct 27 '26 20:10 nextor2k

Re-measured with the reproduction from this issue (mdotk/next-standalone-memory-repro, webpack build, /[slug], a new slug per request), 4 cycles of 2,000 requests, 24 connections, forced GC between cycles. Peak RSS and peak arrayBuffers under load:

Node 24.22 Node 25.9 Node 26.14
16.2.2 597 MB / 143 MB 2,056 MB / 620 MB —
16.4.6 588 MB / 147 MB 1,417 MB / 592 MB 536 MB / 152 MB
16.5.0-canary.77 582 MB / 149 MB 2,069 MB / 643 MB —

After a forced GC arrayBuffers go back to 50 MB in every run (the default cacheMaxMemorySize), so nothing is retained; on Node 25 the process climbs far higher under load before the memory comes back. The Next.js version makes no difference here; the Node version does. Node 25 reached end of life on 2026-06-01, so moving to 24 or 26 is the fix for this one.

One change to the repro: lib/payload.js throws without REPRO_ORIGIN, so I made it fall back to http://127.0.0.1:${PORT}.

Measured with next-leak.

xabierlameiro avatar Dec 02 '26 08:12 xabierlameiro