Skip to content

fix: release compression stream when client disconnects mid-response - #96173

Merged
petehunt merged 1 commit into
vercel:canaryfrom
petehunt:petehunt/fix-compression-stream-leak-94919
Jul 25, 2026
Merged

petehunt merged 1 commit into
vercel:canaryfrom
petehunt:petehunt/fix-compression-stream-leak-94919

Conversation

@petehunt

@petehunt petehunt commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

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.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

@github-actions

github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Stats from current PR

✅ No significant changes detected

📊 All Metrics
📖 Metrics Glossary

Dev Server Metrics:

  • Listen = TCP port starts accepting connections
  • First Request = HTTP server returns successful response
  • Cold = Fresh build (no cache)
  • Warm = With cached build artifacts

Build Metrics:

  • Fresh = Clean build (no .next directory)
  • Cached = With existing .next directory

Change Thresholds:

  • Time: Changes < 50ms AND < 10%, OR < 2% are insignificant
  • Size: Changes < 1KB AND < 1% are insignificant
  • All other changes are flagged to catch regressions

⚡ Dev Server

Metric Canary PR Change
Cold (Listen) 813ms 812ms ✓
Cold (Ready in log) 778ms 780ms ✓
Cold (First Request) 1.276s 1.292s ✓
Warm (Listen) 811ms 812ms ✓
Warm (Ready in log) 775ms 778ms ✓
Warm (First Request) 1.249s 1.279s ✓
📦 Dev Server (Webpack) (Legacy)

📦 Dev Server (Webpack)

Metric Canary PR Change
Cold (Listen) 813ms 813ms ✓
Cold (Ready in log) 780ms 783ms ✓
Cold (First Request) 3.443s 3.409s ✓
Warm (Listen) 812ms 813ms ✓
Warm (Ready in log) 782ms 783ms ✓
Warm (First Request) 3.471s 3.459s ✓

⚡ Production Builds

Metric Canary PR Change
Fresh Build 5.126s 5.156s ✓
Cached Build 5.097s 5.252s ✓
📦 Production Builds (Webpack) (Legacy)

📦 Production Builds (Webpack)

Metric Canary PR Change
Fresh Build 24.203s 24.352s ✓
Cached Build 24.443s 24.467s ✓
node_modules Size 547 MB 547 MB ✓
📦 Bundle Sizes

Bundle Sizes

⚡ Turbopack

Client

Main Bundles
Canary PR Change
0a-p0meqxynjz.js gzip 10.3 kB N/A -
0avtke4yefj4-.js gzip 13.1 kB N/A -
0cz1d0mv5g_q7.js gzip 39.4 kB 39.4 kB ✓
0gl2iykkguh4d.js gzip 65.6 kB N/A -
0llk16ml1vb4v.js gzip 169 B N/A -
0p3o46_wsr2_o.js gzip 154 B N/A -
0pt5of3ch6d2u.js gzip 13.6 kB N/A -
0xnsdo-6y9r3k.js gzip 5.72 kB N/A -
0yi7is8u4covm.js gzip 8.77 kB N/A -
13x7w_xsyz1kg.js gzip 155 B N/A -
1elt1qium-r2m.css gzip 115 B 115 B ✓
1mgk3uqcaf-zj.js gzip 153 B N/A -
1prv-wg6jgtt2.js gzip 8.77 kB N/A -
1t47vod02e_4a.js gzip 8.75 kB N/A -
1tf1phijqlx9j.js gzip 220 B 220 B ✓
1tw002sq5bo4l.js gzip 10 kB N/A -
1vemgnqgwu6tb.js gzip 71.1 kB N/A -
1wlerik1n7zbr.js gzip 8.7 kB N/A -
2560rh2e_a8s4.js gzip 156 B N/A -
29qjgpjtp2p4b.js gzip 158 B N/A -
2a4p0ueayidsb.js gzip 155 B N/A -
2lviwqiqxm904.js gzip 3.52 kB N/A -
2pevdqjpbf3xk.js gzip 9.45 kB N/A -
2qd2anu9eizlz.js gzip 8.75 kB N/A -
2sv39ae5_8vfj.js gzip 8.81 kB N/A -
2utx6n7w65xqa.js gzip 8.7 kB N/A -
2zps1per6wm9r.js gzip 154 B N/A -
2zq1gws80ir40.js gzip 159 B N/A -
3-ukivglqkfeq.js gzip 8.78 kB N/A -
30oyryl5q4xf-.js gzip 45.2 kB N/A -
325xisqrylugu.js gzip 450 B N/A -
3961aoocb426j.js gzip 154 B N/A -
3jc9ghvds1spf.js gzip 2.29 kB N/A -
3juwkvkgvywfe.js gzip 10.6 kB N/A -
3kbove7q58uqh.js gzip 13.2 kB N/A -
3msg5ym65p0gm.js gzip 157 B N/A -
3qn7vntp30gaj.js gzip 1.47 kB N/A -
3r14vs4fuhwfd.js gzip 154 B N/A -
3u9ziwgnnaj5j.js gzip 7.4 kB N/A -
3wav-92p7x_3n.js gzip 159 B N/A -
turbopack-0-..piqo.js gzip 3.8 kB N/A -
turbopack-0j..b5x8.js gzip 3.82 kB N/A -
turbopack-0v..yhs0.js gzip 3.8 kB N/A -
turbopack-10..em3o.js gzip 3.8 kB N/A -
turbopack-12..6pt0.js gzip 3.8 kB N/A -
turbopack-1b..dbqb.js gzip 3.8 kB N/A -
turbopack-2c..7zii.js gzip 3.8 kB N/A -
turbopack-2d..xgsa.js gzip 3.8 kB N/A -
turbopack-2f..78o9.js gzip 3.8 kB N/A -
turbopack-2f..mu_6.js gzip 3.8 kB N/A -
turbopack-3-..gdef.js gzip 3.81 kB N/A -
turbopack-3h..ra5s.js gzip 3.81 kB N/A -
turbopack-3t..9_2x.js gzip 3.81 kB N/A -
turbopack-3u..wmfk.js gzip 3.78 kB N/A -
00z5q9hgk77pj.js gzip N/A 71.1 kB -
030a1njeh5b77.js gzip N/A 10 kB -
0b-mp_6p0pfc3.js gzip N/A 156 B -
0b2x8e0etci0g.js gzip N/A 157 B -
0ev_hnv3jxpfc.js gzip N/A 45.2 kB -
0ko7a5wuygdwg.js gzip N/A 158 B -
0ot0qt5np20h7.js gzip N/A 8.78 kB -
0s54zgx71aknn.js gzip N/A 158 B -
0w9fbc7peumpk.js gzip N/A 158 B -
1-zng1g6w4dpf.js gzip N/A 65.6 kB -
12m9rr7_7cexd.js gzip N/A 8.7 kB -
186r3y_rfvr0b.js gzip N/A 8.78 kB -
19v97848yrjp7.js gzip N/A 8.81 kB -
1nd_0rwgz2ozk.js gzip N/A 9.45 kB -
1oi9pltr_e10m.js gzip N/A 10.6 kB -
1rd9tzqgzsz2w.js gzip N/A 8.77 kB -
1rq1g_cwv642d.js gzip N/A 10.3 kB -
1s02_qdjk8zrj.js gzip N/A 153 B -
1uojw_uabeg93.js gzip N/A 450 B -
1w-7lusgyl81y.js gzip N/A 8.7 kB -
2-t8d8btwm08o.js gzip N/A 161 B -
21h56wdn9zddo.js gzip N/A 8.75 kB -
22kihrt4w3tzq.js gzip N/A 169 B -
24lh7-r5fnerg.js gzip N/A 156 B -
2dm6x96suml11.js gzip N/A 156 B -
2lg10omv7xu14.js gzip N/A 3.52 kB -
2ovff1533zvno.js gzip N/A 13.2 kB -
2s4z8jy0z7v93.js gzip N/A 1.46 kB -
2y6gb5bs4mnam.js gzip N/A 8.75 kB -
3_hwgducey93o.js gzip N/A 163 B -
341h71ln1jpl3.js gzip N/A 2.29 kB -
34ttpt_n7605h.js gzip N/A 5.72 kB -
36ckfq9o-ys-a.js gzip N/A 13.1 kB -
38j_hl1ifbc1t.js gzip N/A 155 B -
38n1na-4zsfpn.js gzip N/A 7.41 kB -
3vdh6_u50pu5t.js gzip N/A 13.6 kB -
41s7k-ro6g1v-.js gzip N/A 155 B -
turbopack-05..7b3f.js gzip N/A 3.81 kB -
turbopack-06..phwb.js gzip N/A 3.81 kB -
turbopack-0h..9068.js gzip N/A 3.81 kB -
turbopack-0t..c0df.js gzip N/A 3.81 kB -
turbopack-0x..s5xy.js gzip N/A 3.81 kB -
turbopack-12..tshx.js gzip N/A 3.81 kB -
turbopack-14..ec0c.js gzip N/A 3.8 kB -
turbopack-16..sui7.js gzip N/A 3.81 kB -
turbopack-2d..dsjf.js gzip N/A 3.81 kB -
turbopack-2m..0qgm.js gzip N/A 3.78 kB -
turbopack-37..hwsl.js gzip N/A 3.82 kB -
turbopack-3b..scbf.js gzip N/A 3.81 kB -
turbopack-3m..kumf.js gzip N/A 3.81 kB -
turbopack-3p..pfuc.js gzip N/A 3.81 kB -
Total 448 kB 448 kB ⚠️ +99 B

Server

Middleware
Canary PR Change
middleware-b..fest.js gzip 780 B 775 B ✓
Total 780 B 775 B ✅ -5 B
Build Details
Build Manifests
Canary PR Change
_buildManifest.js gzip 429 B 434 B 🔴 +5 B (+1%)
Total 429 B 434 B ⚠️ +5 B

📦 Webpack

Client

Main Bundles
Canary PR Change
3322-HASH.js gzip 63.8 kB N/A -
4191.HASH.js gzip 169 B N/A -
7920-HASH.js gzip 4.68 kB N/A -
9784-HASH.js gzip 5.63 kB N/A -
b1ad9f4c-HASH.js gzip 62.9 kB N/A -
framework-HASH.js gzip 59.7 kB 59.7 kB ✓
main-app-HASH.js gzip 254 B 252 B ✓
main-HASH.js gzip 40 kB 40 kB ✓
webpack-HASH.js gzip 1.68 kB 1.68 kB ✓
3577.HASH.js gzip N/A 168 B -
578-HASH.js gzip N/A 64.5 kB -
8590-HASH.js gzip N/A 5.61 kB -
9750-HASH.js gzip N/A 4.69 kB -
a8984546-HASH.js gzip N/A 62.9 kB -
Total 239 kB 239 kB ⚠️ +606 B
Polyfills
Canary PR Change
polyfills-HASH.js gzip 39.4 kB 39.4 kB ✓
Total 39.4 kB 39.4 kB ✓
Pages
Canary PR Change
_app-HASH.js gzip 194 B 193 B ✓
_error-HASH.js gzip 181 B 182 B ✓
css-HASH.js gzip 334 B 331 B ✓
dynamic-HASH.js gzip 1.81 kB 1.81 kB ✓
edge-ssr-HASH.js gzip 255 B 253 B ✓
head-HASH.js gzip 349 B 351 B ✓
hooks-HASH.js gzip 382 B 384 B ✓
image-HASH.js gzip 581 B 582 B ✓
index-HASH.js gzip 260 B 259 B ✓
link-HASH.js gzip 2.48 kB 2.48 kB ✓
routerDirect..HASH.js gzip 317 B 318 B ✓
script-HASH.js gzip 384 B 386 B ✓
withRouter-HASH.js gzip 316 B 315 B ✓
1afbb74e6ecf..834.css gzip 106 B 106 B ✓
Total 7.95 kB 7.95 kB ⚠️ +1 B

Server

Edge SSR
Canary PR Change
edge-ssr.js gzip 128 kB 128 kB ✓
page.js gzip 290 kB 289 kB ✓
Total 418 kB 417 kB ✅ -1.17 kB
Middleware
Canary PR Change
middleware-b..fest.js gzip 620 B 616 B ✓
middleware-r..fest.js gzip 156 B 156 B ✓
middleware.js gzip 45.3 kB 45.2 kB ✓
edge-runtime..pack.js gzip 842 B 842 B ✓
Total 46.9 kB 46.8 kB ✅ -129 B
Build Details
Build Manifests
Canary PR Change
_buildManifest.js gzip 718 B 718 B ✓
Total 718 B 718 B ✓
Build Cache
Canary PR Change
0.pack gzip 4.61 MB 4.6 MB 🟢 6.55 kB (0%)
index.pack gzip 121 kB 122 kB ✓
index.pack.old gzip 122 kB 121 kB ✓
Total 4.85 MB 4.84 MB ✅ -6.42 kB

🔄 Shared (bundler-independent)

Runtimes
Canary PR Change
app-page-exp...dev.js gzip 368 kB 368 kB ✓
app-page-exp..prod.js gzip 204 kB 204 kB ✓
app-page-tur...dev.js gzip 368 kB 368 kB ✓
app-page-tur..prod.js gzip 204 kB 204 kB ✓
app-page-tur...dev.js gzip 364 kB 364 kB ✓
app-page-tur..prod.js gzip 202 kB 202 kB ✓
app-page.run...dev.js gzip 364 kB 364 kB ✓
app-page.run..prod.js gzip 202 kB 202 kB ✓
app-route-ex...dev.js gzip 81.8 kB 81.8 kB ✓
app-route-ex..prod.js gzip 55.6 kB 55.6 kB ✓
app-route-tu...dev.js gzip 81.8 kB 81.8 kB ✓
app-route-tu..prod.js gzip 55.6 kB 55.6 kB ✓
app-route-tu...dev.js gzip 81.4 kB 81.4 kB ✓
app-route-tu..prod.js gzip 55.4 kB 55.4 kB ✓
app-route.ru...dev.js gzip 81.4 kB 81.4 kB ✓
app-route.ru..prod.js gzip 55.4 kB 55.4 kB ✓
dev-validati...dev.js gzip 131 kB 131 kB ✓
dev-validati...dev.js gzip 132 kB 132 kB ✓
dev-validati...dev.js gzip 130 kB 130 kB ✓
dev-validati...dev.js gzip 130 kB 130 kB ✓
dist_client_...dev.js gzip 324 B 324 B ✓
dist_client_...dev.js gzip 326 B 326 B ✓
dist_client_...dev.js gzip 318 B 318 B ✓
dist_client_...dev.js gzip 317 B 317 B ✓
pages-api-tu...dev.js gzip 45.4 kB 45.4 kB ✓
pages-api-tu..prod.js gzip 34.1 kB 34.1 kB ✓
pages-api.ru...dev.js gzip 45.4 kB 45.4 kB ✓
pages-api.ru..prod.js gzip 34.1 kB 34.1 kB ✓
pages-turbo....dev.js gzip 54.9 kB 54.9 kB ✓
pages-turbo...prod.js gzip 39.7 kB 39.7 kB ✓
pages.runtim...dev.js gzip 54.8 kB 54.8 kB ✓
pages.runtim..prod.js gzip 39.7 kB 39.7 kB ✓
server.runti..prod.js gzip 68.1 kB 68.1 kB ✓
use-cache-pr...dev.js gzip 71.7 kB 71.7 kB ✓
use-cache-pr...dev.js gzip 71.8 kB 71.8 kB ✓
use-cache-pr...dev.js gzip 70.1 kB 70.1 kB ✓
use-cache-pr...dev.js gzip 70.1 kB 70.1 kB ✓
Total 4.05 MB 4.05 MB ⚠️ +1 B
📎 Tarball URL
https://vercel-packages.vercel.app/next/commits/bb60cb0d7410735aa6f34d5f1aa070f389adc5ca/next

Commit: bb60cb0

@github-actions

github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Tests Passed

Commit: bb60cb0

@petehunt
petehunt marked this pull request as ready for review July 24, 2026 21:04
marcoshernanz added a commit that referenced this pull request Jul 25, 2026
@petehunt
petehunt force-pushed the petehunt/fix-compression-stream-leak-94919 branch from 2242a47 to ff01fbe Compare July 25, 2026 05:28
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
petehunt force-pushed the petehunt/fix-compression-stream-leak-94919 branch from ff01fbe to bb60cb0 Compare July 25, 2026 05:30
@petehunt
petehunt merged commit 770f157 into vercel:canary Jul 25, 2026
119 checks passed
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>
@github-actions github-actions Bot added the locked label Sep 9, 2026
@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Sep 9, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

App Router RSC render tree retained per request → server memory leak / OOM (non-standalone, Node 22/24)

2 participants