Repository navigation
Description
Bug Description
If an HTTP/2 request is aborted while part of its request body is still queued behind flow control (the server hasn't read it yet), no RST_STREAM is sent and the stream is left orphaned inside nghttp2. When the server later reads the body and grants window, the client process loops in native code emitting 0-length DATA frames. Its event loop never runs again, RSS grows at about 0.5–1 GiB/s, and the process is OOM-killed. Nothing reaches the wire during the loop.
We hit this in production. A Node service sends POSTs over h2c with Agent({ allowH2: true }) and request({ body, signal }) to a Go sidecar, and the sidecar back-pressures when it's busy. The service was OOM-killed several times a day. The kernel OOM reports point at node::http2::Http2Session::CopyDataIntoOutgoing, with gigabytes of 9-byte frame headers queued. After we applied the patch below, those OOMs went from ~7/day to 0 over the following 4 days.
This may be the root cause of #6181, which has the same CopyDataIntoOutgoing OOM but no reproduction.
Reproducible By
Save as repro.js and run node repro.js from a directory where require('undici') resolves. The client runs in a forked child, and the parent kills it at 1 GiB, so the machine never actually runs out of memory.
'use strict'
const http2 = require('node:http2')
const fs = require('node:fs')
const { fork, execFileSync } = require('node:child_process')
// The client runs in a forked child: once the bug triggers, its event loop never runs
// again, so the parent watches the child's RSS and kills it at 1 GiB.
if (process.argv[2] === 'child') {
const { H2CClient } = require('undici')
const client = new H2CClient(`http://127.0.0.1:${process.argv[3]}`)
const ac = new AbortController()
client.request({ path: '/', method: 'POST', body: Buffer.alloc(2 * 1024 * 1024), signal: ac.signal }).catch(() => {})
// Abort while most of the body is still queued behind flow control.
setTimeout(() => ac.abort(), 100)
setInterval(() => {}, 1000)
return
}
// Parent: a server that doesn't read the 2 MiB body for 1s, so the upload stalls at the
// 64 KiB stream window and the abort lands while most of the body is queued.
function rssMiB (pid) {
try {
const m = /VmRSS:\s+(\d+)/.exec(fs.readFileSync(`/proc/${pid}/status`, 'utf8'))
if (m) return Number(m[1]) / 1024
} catch {}
return Number(execFileSync('ps', ['-o', 'rss=', '-p', String(pid)]).toString().trim()) / 1024
}
const server = http2.createServer()
server.on('session', (s) => s.on('error', () => {}))
server.on('stream', (stream) => {
stream.on('error', () => {})
stream.on('close', () => console.log(`server: stream closed, rstCode=${stream.rstCode}`))
setTimeout(() => stream.resume(), 1000)
})
server.listen(0, '127.0.0.1', () => {
const child = fork(__filename, ['child', String(server.address().port)])
let peak = 0
const done = (code, msg) => { clearInterval(t); child.kill('SIGKILL'); server.close(); console.log(msg); process.exit(code) }
const t = setInterval(() => {
peak = Math.max(peak, rssMiB(child.pid))
if (peak > 1024) done(1, `RUNAWAY: client RSS passed ${Math.round(peak)} MiB after one aborted upload`)
}, 100)
setTimeout(() => done(0, `ok: client RSS peaked at ${Math.round(peak)} MiB`), 5000)
})Output on undici 8.12.2 / Node 22.23.4:
RUNAWAY: client RSS passed 1092 MiB after one aborted upload
Expected Behavior
The abort sends RST_STREAM(CANCEL), the server sees the stream reset, and client memory stays flat. With the patch below:
server: stream closed, rstCode=8
ok: client RSS peaked at 69 MiB
Cause
The abort handler in writeH2 (lib/dispatcher/client-h2.js) calls stream.close() and then util.destroy(stream). The destroy was added in #5462 and made synchronous in #5559.
stream.close()uses NGHTTP2_NO_ERROR. While the writable side is still ending, Node defers submitting the RST_STREAM until'finish'.'finish'needs the queued body flushed, which needs window the server hasn't granted, so the RST is never submitted.util.destroy(stream)then tears down Node's stream object._destroydoesn't submit its own RST because the stream is already marked closed, so the stream is dropped from Node while nghttp2 still holds it open with an active data provider.- When the server grants window, nghttp2 asks Node for more data. Node can't find the stream and returns 0 bytes without EOF. nghttp2 sends an empty DATA frame and asks again. Empty DATA frames consume no window, so this never stops.
The comment above the destroy ("close() has already queued the RST_STREAM frame on the native session") doesn't hold while the body is still queued. Step 3 is a Node core defect, filed as nodejs/node#67363. undici's abort sequence is a default-configuration way to trigger it. main and 8.12.4 still have this sequence.
Suggested fix
Give each stream its own AbortController, pass its signal to session.request(), and abort it instead of calling close(). Node then destroys the stream with an AbortError, which submits RST_STREAM(CANCEL) before the stream is torn down. Patch against 8.12.2 (we're running it in production):
diff --git a/lib/dispatcher/client-h2.js b/lib/dispatcher/client-h2.js
--- a/lib/dispatcher/client-h2.js
+++ b/lib/dispatcher/client-h2.js
@@ -1031,7 +1031,7 @@ function writeH2 (client, request) {
const headersTimeout = request.headersTimeout ?? client[kHeadersTimeout]
const bodyTimeout = request.bodyTimeout ?? client[kBodyTimeout]
const session = client[kHTTP2Session]
- const { method, path, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request
+ const { method, path, host, upgrade, expectContinue, protocol, headers: reqHeaders } = request
if (upgrade != null && upgrade !== 'websocket') {
util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`))
@@ -1043,6 +1043,11 @@ function writeH2 (client, request) {
headers[HTTP2_HEADER_AUTHORITY] = host || client[kHostAuthority]
headers[HTTP2_HEADER_METHOD] = method
+ // Owned by this request's stream. Aborting it makes Node destroy the stream
+ // with an AbortError, which submits RST_STREAM(CANCEL) before the stream is
+ // torn down, even while the request body is still queued.
+ const streamAbort = new AbortController()
+
// Single pre-shaped state object shared by all stream event handlers.
// All fields are declared up-front so the object keeps a stable hidden
// class for the whole request lifetime.
@@ -1079,18 +1084,17 @@ function writeH2 (client, request) {
if (state.stream != null) {
clearRequestStream(request)
- // On Abort, we close the stream to send RST_STREAM frame.
+ // On Abort, cancel the stream through its signal so Node sends
+ // RST_STREAM(CANCEL) and destroys it in one step. stream.close() defers
+ // the RST_STREAM until the writable side finishes, which never happens
+ // while the peer withholds flow-control window for a queued body; the
+ // destroy below then drops the stream from Node while nghttp2 keeps its
+ // data provider, and the session loops on empty DATA frames until the
+ // process runs out of memory.
const stream = state.stream
- stream.close()
-
- // close() alone leaves cleanup waiting on the 'close' event; on a busy,
- // long-lived multiplexed session that event can fail to fire, leaving the
- // native Http2Stream (and the whole request graph it pins) alive for the
- // session's life. Destroy the stream synchronously to release the handle
- // deterministically. Deferring the destroy (e.g. via setImmediate) leaks
- // the same way when the event loop is stalled and the callback never runs
- // under abort churn (#5558); close() has already queued the RST_STREAM
- // frame on the native session, so a synchronous destroy still sends it.
+ streamAbort.abort()
+
+ // Destroy synchronously in case the signal did not (#5558).
if (!stream.destroyed) {
util.destroy(stream)
}
@@ -1147,7 +1151,7 @@ function writeH2 (client, request) {
headers[HTTP2_HEADER_SCHEME] = protocol === 'http:' ? 'http' : 'https'
}
- stream = openStream(client, request, session, abort, headers, { endStream: false, signal })
+ stream = openStream(client, request, session, abort, headers, { endStream: false, signal: streamAbort.signal })
if (stream == null) {
unrefH2Session(session)
return false
@@ -1161,7 +1165,7 @@ function writeH2 (client, request) {
// will create a new stream. We trigger a request to create the stream and wait until
// `ready` event is triggered
// We disabled endStream to allow the user to write to the stream
- stream = openStream(client, request, session, abort, headers, { endStream: false, signal })
+ stream = openStream(client, request, session, abort, headers, { endStream: false, signal: streamAbort.signal })
if (stream == null) {
unrefH2Session(session)
return false
@@ -1263,7 +1267,7 @@ function writeH2 (client, request) {
headers[HTTP2_HEADER_EXPECT] = '100-continue'
}
- stream = openStream(client, request, session, abort, headers, { endStream: shouldEndStream, signal })
+ stream = openStream(client, request, session, abort, headers, { endStream: shouldEndStream, signal: streamAbort.signal })
if (stream == null) {
return false
}What we tested:
- The repro above passes with this patch.
- On 8.12.2,
test/http2*.js,test/h2*.js,test/fetch/http2*.jsandtest/issue-5936.jsgive the same results before and after the patch. - In production, the OOMs stopped after we deployed it (~7/day → 0 over 4 days).
- We tested two alternatives.
stream.close(NGHTTP2_CANCEL)fixes Buffer/string bodies, but a streaming body that's still being piped still runs away: the pipeline's 'aborted' handler destroys the stream before the RST is submitted (the http2:Http2Stream#close()sends no RST_STREAM when an'aborted'listener destroys the stream node#66306 path).util.destroy(stream, err)without theclose()fixes both body types, but the server sees INTERNAL_ERROR instead of CANCEL.
Environment
- Linux x64
- Node.js 22.22.0, 22.23.4, 24.19.0 and 26.7.0
- undici 8.7.0, 8.9.0, 8.10.2, 8.12.2, 8.12.3 and
main, with Buffer/string bodies. Streaming bodies still being piped also run away on 7.30.1 and 8.6.0.
Additional context
- HTTP/2: client session outgoing queue grows without bound (Http2Session::CopyDataIntoOutgoing), OOM-killing the process #6181 has the same
CopyDataIntoOutgoingOOM in production, with no root cause found yet. - HTTP/2: aborting fetch on an established session causes uncaught socket idle timeout #6143 / fix(h2): handle orphan streams left behind by aborted requests #6147 come from the same
close()+destroy()orphaned stream, but with a different symptom (an uncaught idle-timeout error). fix(h2): handle orphan streams left behind by aborted requests #6147 cancels an orphan only when response HEADERS arrive, which doesn't help here: the loop starts before any response. - HTTP/2: setImmediate-deferred util.destroy(stream) in the abort path leaks aborted streams until OOM when the event loop stalls #5558 and Memory leak: aborted HTTP/2 requests strand the response body and leak the request graph (regression in #5483 / 8.6.0) #5566 are the leaks that led to the synchronous destroy.
- http2: canceled upload leaves session memory accounting over budget node#66742: aborted unsent uploads over-count session memory, so after enough of them a session resets new responses with ENHANCE_YOUR_CALM (see also H2: a session Node has reset for memory (ENHANCE_YOUR_CALM) stays in the pool and fails every later request #6149). That's separate and happens with or without this fix.
This report was prepared with an AI coding assistant and reviewed by me.
Activity