Repository navigation
fix: release compression stream when client disconnects mid-response - #96173
Merged
petehunt merged 1 commit intoJul 25, 2026
Merged
Conversation
Contributor
Stats from current PR✅ No significant changes detected📊 All Metrics📖 Metrics GlossaryDev Server Metrics:
Build Metrics:
Change Thresholds:
⚡ Dev Server
📦 Dev Server (Webpack) (Legacy)📦 Dev Server (Webpack)
⚡ Production Builds
📦 Production Builds (Webpack) (Legacy)📦 Production Builds (Webpack)
📦 Bundle SizesBundle Sizes⚡ TurbopackClient Main Bundles
Server Middleware
Build DetailsBuild Manifests
📦 WebpackClient Main Bundles
Polyfills
Pages
Server Edge SSR
Middleware
Build DetailsBuild Manifests
Build Cache
🔄 Shared (bundler-independent)Runtimes
📎 Tarball URLCommit: bb60cb0 |
Contributor
Tests PassedCommit: bb60cb0 |
petehunt
marked this pull request as ready for review
July 24, 2026 21:04
gnoff
approved these changes
Jul 24, 2026
marcoshernanz
added a commit
that referenced
this pull request
Jul 25, 2026
petehunt
force-pushed
the
petehunt/fix-compression-stream-leak-94919
branch
from
July 25, 2026 05:28
2242a47 to
ff01fbe
Compare
The vendored compression middleware only ends its zlib stream from its own res.end() wrapper, so a client that disconnects mid-response leaves the stream open. An open zlib stream is pinned by its native handle and survives GC, permanently retaining its ~256 KiB deflate state per aborted request.
petehunt
force-pushed
the
petehunt/fix-compression-stream-leak-94919
branch
from
July 25, 2026 05:30
ff01fbe to
bb60cb0
Compare
m-kawafuji
pushed a commit
to m-kawafuji/next.js
that referenced
this pull request
Aug 8, 2026
…ercel#96173) ## Summary Fixes vercel#94919. When a client disconnects mid-response, the compression middleware's zlib stream is never released, and every aborted compressed response permanently retains its deflate state (~256 KiB). On a server taking traffic that aborts mid-stream (bots, CDNs, users navigating away) RSS climbs until the process is OOM-killed. `router-server.ts` applies the vendored `compression` middleware, which ends its zlib stream *only* from inside its own `res.end()` wrapper. On a client disconnect Next destroys the response instead, so that wrapper never runs and the stream stays open. An open zlib stream is pinned by its native handle, so it is not merely uncollected-for-now — it survives GC entirely. This is why the reported symptom looks unlike a normal JS leak: the JS heap stays nearly flat while RSS grows without bound, because the retained deflate state is native memory. It affects `next start`, `next dev`, and custom servers — anything going through the router server with the default `compress: true`. Deployments that let a proxy handle compression never see it. Note that ending the stream is not sufficient to recover it: its `data` handler writes to the already-destroyed response, `res.write()` returns `false`, the middleware pauses the stream, and it never reaches `end`. It has to be destroyed. `releaseCompressionStream` carries a comment explaining this so the cleanup isn't "simplified" back into a no-op later. The stream is reached through the one handle the middleware exposes: it forwards `res.on('drain', …)` to the zlib stream once that stream exists, and `EventEmitter#on` returns the emitter it was called on. Upstream `compression@1.8.1` still has no premature-close handling, so this can't be fixed by bumping the vendored copy. The added test asserts that assumption and will fail if a future vendored version handles this itself, signalling that the workaround can be dropped. ### Before / after Measured with a minimal custom Node server (no Express/axios) rendering a 1.25 MB dynamic App Router page, 8 rounds × 300 requests cancelled after the first chunk, `heapUsed`/`rss` sampled **after forced GC** each round. Same build, cleanup toggled behind a temporary env var: | | without cleanup | with cleanup | | --- | --- | --- | | zlib contexts never released | 2400 of 2400 (100%) | **0** of 2600 | | RSS | 98.2 → 1069.6 MiB, linear | 100 → 401.5 MiB, plateaus | | `external` | 3.6 → 76.5 MiB | 3.6 → 4.5 MiB | | `heapUsed` | 21.2 → 79.1 MiB | 21.2 → 27.4 MiB | Without the cleanup, RSS grows by a steady ~93 MiB per 300 aborted requests across rounds 2–8 (≈310 KiB per request, consistent with zlib's default deflate state plus per-stream buffers), and every unreleased stream is *still reachable after repeated forced GC* — permanent retention rather than GC lag. With the cleanup, all 2600 contexts are closed and RSS plateaus, with the residual difference from baseline being allocator retention rather than per-request growth. As a control, 200 fully-read responses issued into the same un-fixed process all closed normally, isolating mid-stream disconnects as the trigger. The issue also attributes the leak to a retained RSC element tree held via the `WeakMap` in `use-flight-response.tsx`. That part did not reproduce on canary: across 8000 aborted requests spanning dynamic renders, `redirect()`, `notFound()` and render throws, and 3000 full reads of the same 1.25 MB payload, post-GC heap stayed flat at ~29 MiB. The native `zlib_memory` line in the reporter's heap-snapshot diff was the actual cause. ## Verification - `pnpm test-start-turbo test/e2e/custom-server/custom-server.test.ts` and `pnpm test-dev-turbo test/e2e/custom-server/custom-server.test.ts` — covers `Content-Encoding: gzip` through a custom server, i.e. the code path being changed (46 and 45 passing) - `npx jest packages/next/src/server/lib` — 188 passing, including the 4 new cases - Manual: verified a gzipped response still decompresses byte-identical to the same response with `accept-encoding: identity` (1,250,721 bytes), with no errors or `MaxListenersExceededWarning` under sustained load - Manual: the before/after table above, re-measured against this branch's HEAD <!-- NEXT_JS_LLM --> Co-authored-by: Pete Hunt <239742+petehunt@users.noreply.github.com>
gaojude
pushed a commit
that referenced
this pull request
Aug 25, 2026
…zip (#97698) ## Summary On Next 16.3+, App Router HTML and RSC responses are piped with `pipeNodeReadableToNodeResponse`. Under gzip backpressure it called `res.once('drain')` on every write that returned `false`, which leaks one listener per backpressured write onto the zlib stream: ``` MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 drain listeners added to [Gzip]. MaxListeners is 10. ``` The `compression` middleware overrides only `res.on`, forwarding it to the zlib stream once that stream exists (or buffering it until then). It leaves `removeListener` pointing at the response, so a `once` listener is added to the stream but never removed from it. `off` cannot reach it either. `createWriterFromResponse`, directly above in the same file, already uses a single `res.on('drain')` for the response lifetime. This makes the Node-readable path match: pause on `write() === false`, resume from one listener, `off` on `close`. Resuming on that event is correct for both cases. With compression active the wrapped `res.write` writes into the zlib stream, so `false` means the zlib stream's buffer is full and its `drain` is the right signal — the middleware separately wires the socket's `drain` to `stream.resume()`. With compression inactive the listener stays on the response, where `off` does remove it. The pause is latched so a `drain` only resumes a readable that this function paused, and a `drain` arriving after teardown is ignored. ### Scope - Distinct from #96173 / `releaseCompressionStream`, which destroys the zlib stream on **abort**. This warning fires on a **live** stream that is still flowing: slow clients, large streamed HTML/RSC. - Deliberately leaves the bare `readable.destroy()` in the `close` handler alone. That is the separate abort-reason bug in #96704, with fixes already open in #96715 and #96717. - Not fixable by bumping the vendored `compression`: as #96173 established, upstream `compression@1.8.1` still has no premature-close handling, and it is a prebuilt bundle here. `setMaxListeners` or `compress: false` would only hide this. - Mentioned as a `compress: false` workaround in #95130. ## Verification `packages/next/src/server/pipe-readable.test.ts` drives real backpressure (48 × 64 KiB through a throttled reader) and asserts exactly one `drain` registration on the zlib stream, no `MaxListenersExceededWarning`, and a complete, byte-correct payload after `gunzip`. The payload assertion is what catches a latch that stalls the stream. Confirmed it fails without the fix. Measured against the real compiled function on Next 16.3, patching only the drain handling: | | before | after | | --- | --- | --- | | `drain` registrations on `[Gzip]` | 48 (one per backpressured write) | **1** | | `MaxListenersExceededWarning` | 1 | **0** | | decompressed payload | complete | complete | At 120 × 64 KiB the before-count scales with writes (120 registrations); the after-count stays at 1. Separately reproduced end to end on a Next 16.3 standalone production build with `compress: true`: slow-consuming a large gzipped page emitted the warning, and after this change it did not, with `Content-Encoding: gzip` still set and valid gzip on the wire. I could not run `pnpm test` in this checkout, so please treat CI as the source of truth for harness integration. The assertions themselves were validated against the real function as described above. --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Jude Gao <jude.gao@vercel.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #94919.
When a client disconnects mid-response, the compression middleware's zlib stream is never released, and every aborted compressed response permanently retains its deflate state (~256 KiB). On a server taking traffic that aborts mid-stream (bots, CDNs, users navigating away) RSS climbs until the process is OOM-killed.
router-server.tsapplies the vendoredcompressionmiddleware, which ends its zlib stream only from inside its ownres.end()wrapper. On a client disconnect Next destroys the response instead, so that wrapper never runs and the stream stays open. An open zlib stream is pinned by its native handle, so it is not merely uncollected-for-now — it survives GC entirely.This is why the reported symptom looks unlike a normal JS leak: the JS heap stays nearly flat while RSS grows without bound, because the retained deflate state is native memory. It affects
next start,next dev, and custom servers — anything going through the router server with the defaultcompress: true. Deployments that let a proxy handle compression never see it.Note that ending the stream is not sufficient to recover it: its
datahandler writes to the already-destroyed response,res.write()returnsfalse, the middleware pauses the stream, and it never reachesend. It has to be destroyed.releaseCompressionStreamcarries a comment explaining this so the cleanup isn't "simplified" back into a no-op later.The stream is reached through the one handle the middleware exposes: it forwards
res.on('drain', …)to the zlib stream once that stream exists, andEventEmitter#onreturns the emitter it was called on. Upstreamcompression@1.8.1still has no premature-close handling, so this can't be fixed by bumping the vendored copy. The added test asserts that assumption and will fail if a future vendored version handles this itself, signalling that the workaround can be dropped.Before / after
Measured with a minimal custom Node server (no Express/axios) rendering a 1.25 MB dynamic App Router page, 8 rounds × 300 requests cancelled after the first chunk,
heapUsed/rsssampled after forced GC each round. Same build, cleanup toggled behind a temporary env var:externalheapUsedWithout the cleanup, RSS grows by a steady ~93 MiB per 300 aborted requests across rounds 2–8 (≈310 KiB per request, consistent with zlib's default deflate state plus per-stream buffers), and every unreleased stream is still reachable after repeated forced GC — permanent retention rather than GC lag. With the cleanup, all 2600 contexts are closed and RSS plateaus, with the residual difference from baseline being allocator retention rather than per-request growth.
As a control, 200 fully-read responses issued into the same un-fixed process all closed normally, isolating mid-stream disconnects as the trigger.
The issue also attributes the leak to a retained RSC element tree held via the
WeakMapinuse-flight-response.tsx. That part did not reproduce on canary: across 8000 aborted requests spanning dynamic renders,redirect(),notFound()and render throws, and 3000 full reads of the same 1.25 MB payload, post-GC heap stayed flat at ~29 MiB. The nativezlib_memoryline in the reporter's heap-snapshot diff was the actual cause.Verification
pnpm test-start-turbo test/e2e/custom-server/custom-server.test.tsandpnpm test-dev-turbo test/e2e/custom-server/custom-server.test.ts— coversContent-Encoding: gzipthrough a custom server, i.e. the code path being changed (46 and 45 passing)npx jest packages/next/src/server/lib— 188 passing, including the 4 new casesaccept-encoding: identity(1,250,721 bytes), with no errors orMaxListenersExceededWarningunder sustained load