Repository navigation
Description
Version
v22.23.4, v24.13.0, v26.13.1. Also reproducible on current main (eg v28.0.0-nightly202611301726c3bd19), and the issue dates back to the creation of server.closeIdleConnections
Platform
Darwin 25.6.0 arm64
Subsystem
http
What steps will reproduce the bug?
This zero-dependency mjs script runs an HTTP server that returns a large response as a single write, and an HTTP client that pauses its read after accepting the headers, calls server.close(), and waits a bit before resuming reading the body. With the current implementation of server.closeIdleConnections() and server.close(), the response body gets truncated and the client gets an ECONNRESET instead of finishing reading the body.
import http from 'node:http';
import { once } from 'node:events';
import { setTimeout as sleep } from 'node:timers/promises';
const SIZE = 64 * 1024 * 1024;
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-length': SIZE });
res.end(Buffer.alloc(SIZE), () => console.log('end() callback: response fully written'));
console.log(`after end(): finished=${res.finished} writableFinished=${res.writableFinished}`);
});
server.listen(0);
await once(server, 'listening');
const req = http.get({ port: server.address().port });
const [res] = await once(req, 'response');
res.pause(); // slow client: the kernel buffers fill and the rest of the body is queued in Node
await sleep(300);
server.close(); // the connection is still sending its response
await sleep(200);
let received = 0;
res.on('data', (chunk) => { received += chunk.length; });
res.resume();
try {
await once(res, 'end');
console.log(`client received ${received} of ${SIZE} body bytes`);
} catch (err) {
console.log(`client error after ${received} bytes: ${err.code}`);
}
server.closeAllConnections();
How often does it reproduce? Is there a required condition?
It reproduces any time an HTTP response has been end()ed (at the application level) but the data has not been fully written to the socket by Node (eg, due to backpressure at the TCP level from the client) when server.close() or server.closeIdleConnections() runs.
What is the expected behavior? Why is that the expected behavior?
The expected behavior is that server.close() (or server.closeIdleConnections()) will only close idle connections, and so the response should be fully streamed to the client and the program should print:
after end(): finished=true writableFinished=false
end() callback: response fully written
client received 67108864 of 67108864 body bytes
(This is what you see if you don't close the server.)
What do you see instead?
On v24.13.0 (and all versions of Node that I tested including the latest nightly v28.0.0-nightly202611301726c3bd19) we instead get:
after end(): finished=true writableFinished=false
end() callback: response fully written
client error after 1914823 bytes: ECONNRESET
The connection is destroyed and the client gets a truncated body. The end() callback and 'finish' still fire on the server, so the server cannot tell that the response was not delivered.
Additional information
server.closeIdleConnections() is overly aggressive and can forcibly close connections where data is still queued in Node's write buffers, leading to truncated responses. This issue has existed since the initial creation of server.closeIdleConnections (#42812 by @ShogunPanda , Node 18.2.0). That original implementation was even more incorrectly aggressive and did not check that responses were finished at all; soon afterwards in #43890 (also @ShogunPanda , Node 18.7.0) a check was added to not close connections if the response is not finished. (Until Node 19, this only affected explicit calls to server.closeIdleConnections(); v19 made server.close() call server.closeIdleConnections() too.)
Unfortunately, the check added in #43890 is not quite good enough. finished is set synchronously at the end of OutgoingMessage.prototype.end(), right after the last chunk has been queued on the socket (https://github.com/nodejs/node/blob/v24.13.0/lib/_http_outgoing.js#L1077-L1095, this.finished = true on line 1095).
But the data may still sit in the socket's write queue, waiting on the client! For a large response, this may involve multiple TCP round trips due to backpressure. If you call socket.destroy(), it will cancel this low-level data streaming... and that's what closeIdleConnections does.
The good news is that the Node HTTP code has a better flag that means that all response data has actually been fully written: writableFinished (finished && outputSize === 0 && socket.writableLength === 0, https://github.com/nodejs/node/blob/v24.13.0/lib/_http_outgoing.js#L175-L183). Switching closeIdleConnections to use this flag fixes the bug.
Proposed fix (see #67915, note that filename is different on main)
--- a/lib/_http_server.js
+++ b/lib/_http_server.js
@@ Server.prototype.closeIdleConnections
for (let i = 0, l = connections.length; i < l; i++) {
- if (connections[i].socket._httpMessage && !connections[i].socket._httpMessage.finished) {
+ if (connections[i].socket._httpMessage && !connections[i].socket._httpMessage.writableFinished) {
continue;
}
I validated that this makes the reproduction above print the expected output in v24 and v26.
Note that this change will mean that connections in this particular state at shutdown time will not be closed by the single sweep that closeIdleConnections does. If #66000 is merged, these connections will be caught by the code it adds.
History
- http: added closeAllConnections and closeIdleConnections to http.server #42812 (v18.2.0) added
closeIdleConnections()with no check at all. - http: wait for pending responses in closeIdleConnections #43890 (v18.7.0, "wait for pending responses in closeIdleConnections", fixing It will throw an error when both using
server.closeIdleConnections()&server.close()#43771 / Since fastify 4, fastify no longer waits for existing requests to finish when calling fastify.close() fastify/fastify#4098) added thefinishedcheck. Its test,test/parallel/test-http-server-close-idle-wait-response.js, covers a response that has not been ended yet; an ended-but-unflushed response slips through becausefinishedis set atend(). - Use Keep-Alive by default in global agents and close idle connections in server #43522 (v19.0.0, backported in v18.19.0) made
server.close()callcloseIdleConnections(), which is when a plainclose()started truncating responses.
AI usage disclosure
I discovered this bug while working on updating some old graceful-shutdown code in @apollo/server (which predates closeIdleConnections) to use closeIdleConnections instead. I asked a coding agent to evaluate (based on reading Node.js source code) whether the closeIdleConnections version was equivalent to our version, and it noticed that closeIdleConnections differed from our older code in this way. Further investigation and an initial draft of this issue was performed by my agent but I understand and agree with its conclusions and have edited/reworded most of the text here anyway.
Activity
http: don't destroy connections still writing a response
http: don't destroy connections still writing a response
ApolloServerPluginDrainHttpServer: fix memory leak (#8261)