Skip to content

http: close connections that go idle after server.close() - #66000

Open
WhatCats wants to merge 1 commit into
nodejs:mainfrom
WhatCats:http-close-when-idle
Open

WhatCats wants to merge 1 commit into
nodejs:mainfrom
WhatCats:http-close-when-idle

Conversation

@WhatCats

@WhatCats WhatCats commented Sep 12, 2026 •

Copy link
Copy Markdown

Summary

server.close() calls closeIdleConnections() internally (since bd7a808), which closes every connection that is idle at that exact moment. A connection that's actively sending a request or waiting for a response when close() runs is correctly left alone and once that response finishes, nothing ever rechecks it. It reverts to being a normal keep-alive connection and stays open until keepAliveTimeout reaps it (65s by default), rather than closing as part of the server.close() call.

Interestingly, when investigating, I noticed this exact gap is also independently documented in Bun's source: https://github.com/oven-sh/bun/blob/df573dace6178d4ff94a797313bc8b5fdcf515e4/src/runtime/server/mod.rs#L1747-L1751

// node:http servers are exempt: Node's `close()` sweeps idle
// connections exactly once (the JS layer already called
// `closeIdleConnections()`), and a connection whose response
// completes after `close()` stays keep-alive until its timeout
// reaps it — verified against Node v26.

Reproduce

Call server.close() while a request is in flight. The close event doesn't fire until keepAliveTimeout (+ keepAliveTimeoutBuffer) elapses, even though the response completed almost immediately. (see test/parallel/test-http-server-close-when-idle.js)

Fix

Count close() calls on the server. A connection accepted before the latest close() is closing:

  • Its last queued response is sent with Connection: close, unless its headers were already written, and the socket closes once that response finishes.
  • Requests whose handlers already ran are still answered. A request pipelined behind the last response is not processed (RFC 9112 §9.6), Upgrade and CONNECT included.
  • Connections accepted after a later listen() are not affected.

Breaking change

A connection that is busy when server.close() is called now closes once it has answered the requests it accepted, instead of staying keep-alive until keepAliveTimeout. Its last response says Connection: close, and later pipelined requests on it are not processed. Four existing tests relied on the old behaviour and were updated.

AI disclosure

I used Claude Code to help with this PR: investigating the original issue, drafting the fix and tests and drafting comments. I reviewed all the changes myself and verified them by building Node and running the new and updated tests plus the test-http-*, test-https-*, test-http2-compat-* and test-net-server-* suites.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/http
  • @nodejs/net

@nodejs-github-bot nodejs-github-bot added http Issues and PRs related to the http subsystem. needs-ci PRs that need a full CI run. labels Sep 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Welcome to Node.js, and thank you for your first contribution!

Before review, please take a moment to read:

Please make sure every commit is signed off. For a first pull request, GitHub Actions require collaborator approval and Jenkins CI must be started by a collaborator or triager, so an initial wait is normal.

@ronag
ronag requested a review from mcollina September 12, 2026 18:29

@pimterry pimterry left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Totally agree this is weird behaviour and we should fix it, thanks @WhatCats! I think there are tweaks to make here though:

  • I don't think we should expose an option on closeIdleConnections - I'm not sure when this would be used on servers in scenarios except with server.close(), boolean arguments are messy, it's a bit confusing as an API. Can we scope the change just to server.close(), which is the real problem?
  • As in my comments, I don't think checking active() works. I think you can probably simplify this though: don't set a marker at all, instead both _storeHeader and resOnFinish can reach the server (from this[kSocket]?.server or the server arg respectively). We could just check if the server is closing down, and if not then don't keep alive. Does that work?

Comment thread lib/internal/http.js Resolved
Comment thread lib/_http_server.js Resolved
@codecov

codecov Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.58%. Comparing base (d2da05f) to head (edbaebf).
⚠️ Report is 385 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #66000      +/-   ##
==========================================
- Coverage   90.67%   90.58%   -0.09%     
==========================================
  Files         800      802       +2     
  Lines      280918   286903    +5985     
  Branches    54273    55401    +1128     
==========================================
+ Hits       254720   259902    +5182     
- Misses      16293    17089     +796     
- Partials     9905     9912       +7     
Files with missing lines Coverage Δ
lib/internal/http/server.js 96.54% <100.00%> (-0.15%) ⬇️

... and 234 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@WhatCats
WhatCats force-pushed the http-close-when-idle branch from 48691f3 to d8b770e Compare September 18, 2026 19:53
@WhatCats

Copy link
Copy Markdown
Author

Gotcha. I reworked it into just an internal thing server.close uses and added a kServerClosing server flag it uses instead of a per socket kCloseWhenIdle flag as suggested. Also I had to slightly adjust two other HTTP tests based on this new behavior and I expanded the test-http-server-close-when-idle.js one I added to include the case you mentioned.

@WhatCats WhatCats changed the title http: option to mark active connections to close when idle http: close connections that go idle after server.close() Sep 18, 2026

@pimterry pimterry left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks @WhatCats!

@pimterry

Copy link
Copy Markdown
Member

Ah, there's now a conflict here, can you rebase this @WhatCats?

@pimterry

Copy link
Copy Markdown
Member

Hmm, also, is this semver-major? Ping @nodejs/http

Previously if you had requests in flight during server.close() they weren't shut down: they continued normal keep-alive and only closed when if timed out (65s later) or I think could even just keep making requests indefinitely. With this change, we now send a connection: close header on pending responses sent after close() is called, and then we close the connections right after. Old behaviour is clearly a bug - server is closing, it shouldn't keep accepting new requests - but it's definitely visible change on the wire, plausibly fixing the bug will break weird things.

What do we think? I'm inclined to lean yes.

@MikeMcC399

This comment was marked as resolved.

@WhatCats

Copy link
Copy Markdown
Author

I probably should have mentioned you the first time. But here we go again:
@MikeMcC399 @pimterry it is rebased now.

@pimterry pimterry added the semver-major PRs that contain breaking changes and should be released in the next major version. label Nov 17, 2026
@pimterry pimterry added the request-ci Add this label to start a Jenkins CI on a PR. Only starts once the PR has an approving review. label Nov 17, 2026
@github-actions github-actions Bot removed the request-ci Add this label to start a Jenkins CI on a PR. Only starts once the PR has an approving review. label Nov 17, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@pimterry pimterry added the resume-ci Add this label to resume the latest eligible Jenkins CI run on a PR with an approving review. label Nov 18, 2026
@github-actions github-actions Bot removed the resume-ci Add this label to resume the latest eligible Jenkins CI run on a PR with an approving review. label Nov 18, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@MikeMcC399 MikeMcC399 added the author ready PRs with CI started, the required approvals, and no outstanding review comments. label Nov 19, 2026

@araujogui araujogui left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with pipelined requests, the response being written when close() is called closes the socket, so accepted requests queued behind it get no response. Could the check apply only to the last queued response?

@MikeMcC399 MikeMcC399 removed the author ready PRs with CI started, the required approvals, and no outstanding review comments. label Nov 28, 2026
@WhatCats

WhatCats commented Nov 29, 2026 •

Copy link
Copy Markdown
Author

@araujogui Now the headers are left alone, and the connection only closes once the last queued response has finished. By then all pipelined requests have been parsed, so they all get answered. I added a test for that too.

The tradeoff is that the last response still says Connection: keep-alive before the server closes. That could already happen before when keepAliveTimeout hits.

Also, the first commit message still says the response stops advertising keep-alive. That's no longer true, so that part should be dropped when this lands.

@WhatCats

Copy link
Copy Markdown
Author

Also, my closed-source coding agent flagged that a client that keeps pipelining can hold the connection open for as long as it keeps sending. This matters for this PR because the point is that server.close() actually closes connections, and this is the one case where it still doesn't so I will also add a fix and test for that.

@pimterry

Copy link
Copy Markdown
Member

with pipelined requests, the response being written when close() is called closes the socket, so accepted requests queued behind it get no response. Could the check apply only to the last queued response?

@araujogui @WhatCats I think the original behaviour here was reasonable, and probably better than the updated version.

RFC says:

A server that sends a "close" connection option MUST initiate closure of the connection (see below) after it sends the response containing the "close" connection option. The server MUST NOT process any further requests received on that connection.

A client that receives a "close" connection option MUST cease sending requests on that connection and close the connection after reading the response message containing the "close" connection option; if additional pipelined requests had been sent on the connection, the client SHOULD NOT assume that they will be processed by the server.

It is normal that a server closes a connection with pending pipelined requests, it's actually required to send no response in that case, and clients should be able to handle that.

In practice pipelining support really doesn't matter much anyway imo, because roughly zero real clients use it - no browsers have used it for a decade, curl dropped it in entirely 2019, etc. By a large margin the most common pipelining clients are benchmarking tools.

We shouldn't actually break pipelining, but I think anywhere there are tradeoffs (like not signalling close or stopping server shutdown, as in @WhatCats's last message) I'd rather have better & safer behaviour for normal use and accept mild inconvenience for pipelining, instead of trying to actively support pipelining. OTOH short keep-alive + close really has caused us plenty of real-world issues in the past (see #59193) because normal client send requests at the same time as the connection close arrives, get RSTs back, and rarely handle it well.

Does that make sense? What do you think @araujogui?

@WhatCats

WhatCats commented Nov 30, 2026 •

Copy link
Copy Markdown
Author

I tested this PR and the alternatives against Node, Bun, Go and Rust HTTP clients. I used undici as the pipelining client, with pipelining: 3 and blocking: false. The Node variants were ported by hand onto v26.13.1's _http_server.js. I haven't built main.

Problems before the changes

  • Idle: a connection that is busy at close() stays open until keepAliveTimeout. The close event came after about 6 s with the default 5 s timeout plus its 1 s buffer.
  • Still served: that connection keeps serving new requests after close().
  • Pipelining: a pipelined burst gets all its answers, but the connection stays open until the timeout.

Problems after the PR

  • First commit (Connection: close on every response): all clients handle it cleanly, but already-queued pipelined requests are dropped. Only 1 of 3 is answered.
  • Current head (headers untouched, socket destroyed after the last queued response): all queued requests are answered, but the response still says keep-alive. Rust reqwest reuses the dead connection and fails 10/10 with connection closed before message completed. Go only copes because it retries automatically.

New problems found

  • Handlers run but answers are lost: in the first commit, the handler runs for dropped pipelined requests (3 handlers, 1 response). In the current head, a POST that arrives after the queue cap runs and its response is never delivered. This is the existing "MUST NOT process further requests" gap in RFC 9112 §9.6.
  • Reset risk: destroySoon() closes fully rather than staged. Go's server showed an ECONNRESET in this situation, so it isn't Node-specific.

Other servers

I ran the same shutdown test against Go net/http and Rust hyper servers.

  • Header: both send Connection: close on the in-flight response and answer only that request.
  • Dropped requests: queued pipelined requests are dropped and their handlers never run (1 handler).
  • Client side: undici retries the dropped requests and gets a clean "connection refused".

Proposed fixes (theoretical)

  1. Send Connection: close only when the response is final at header time: the server is closing, nothing is queued behind it, and we aren't mid-parse unless the request arrived after close().
  2. Once the server is closing, don't dispatch a request that sits behind a response marked close, or behind the queue cap.

If keeping already-queued pipelined requests isn't worth it, the simpler option matching Go and hyper is the first commit plus fix 2.

@pimterry @araujogui

@glasser

glasser commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Since it looks like this solution to an issue related to idle connection termination is being actively developed, I just wanted to drop a link to an issue #67910 and a PR #67915 I just filed which are also about idle connection termination. Mine is about a case where closeIdleConnections() is too aggressive and destroys sockets that aren't quite idle yet. The two PRs are complementary (they fix different issues, and they merge cleanly on top of each other). My PR means that the responses that would have been truncated without my PR will now end up in the state where they won't be closed without this PR, though.

@pimterry

pimterry commented Dec 1, 2026

Copy link
Copy Markdown
Member

@WhatCats Thanks for looking at this. Personally I'd lean towards option: 2 the first commit + handler fix as you suggest, matching Go & Hyper. Simpler and strict is good, and from my understanding that's all valid correct behaviour. Let's see what @araujogui thinks first though.

@araujogui

Copy link
Copy Markdown
Member

@WhatCats Thanks for looking at this. Personally I'd lean towards option: 2 the first commit + handler fix as you suggest, matching Go & Hyper. Simpler and strict is good, and from my understanding that's all valid correct behaviour. Let's see what @araujogui thinks first though.

Thanks for the explanation @pimterry. @WhatCats let's keep it simple and strict

`server.close()` only closes connections that are idle at that moment.
A busy one stays keep-alive after its response, serving requests until
`keepAliveTimeout` reaps it.

This is a breaking change: such a connection now closes once it has
answered every request it accepted. Its last response says
`Connection: close`, unless its headers were written before close().
A request that arrives behind a pending response after close() is not
processed. Connections accepted after close(), e.g. once the server
listens again, are not affected.

Four existing tests called close() while their connection was still in
use. They now expect `Connection: close`, or call close() only once
they are done with the connection.

Signed-off-by: WhatCats <whatcater@gmail.com>
Assisted-by: a closed-source coding agent
@WhatCats
WhatCats force-pushed the http-close-when-idle branch from 28fdacf to edbaebf Compare December 2, 2026 10:13
@WhatCats

WhatCats commented Dec 2, 2026

Copy link
Copy Markdown
Author

@pimterry @araujogui I force-pushed a reworked version. It's close to what you agreed on, with one difference I want to flag.

What the force push changed

  • The three commits are now one, on the same base, and every commit message is up to date. The first commit's message used to describe header behaviour the code no longer had.
  • Headers: the previous head left the headers alone and only closed the socket afterwards. That made clients like reqwest reuse a connection the server had already closed. Now the last response says Connection: close, unless its headers were already written before close().
  • Pipelining: the previous head limited the queue to the requests waiting when the first response finished. Handlers for requests arriving after that still ran, and their responses were lost. Now a request pipelined behind the response in flight is never processed, so its handler doesn't run.
  • Closing mark: I replaced the server-wide kServerClosing flag with a count of close() calls, which each connection records when it is accepted. Before, calling listen() again cleared the flag and turned older busy connections back into keep-alive ones. Now they stay closing, and connections accepted after listen() behave normally.
  • Docs and tests: the server.close() docs now describe the header and which pipelined requests are answered. I rewrote test-http-server-close-when-idle.js to cover all of this.
  • Other tests: three more existing tests called close() while their connection was still in use: test-http-pipeline-assertionerror-finish, test-http-pipeline-socket-parser-typeerror and test-http-raw-headers. They are updated too, alongside test-http-server-unconsume.

What it does now

  • After close(), the last response on a busy connection is sent with Connection: close, and the socket closes once that response finishes.
  • A request pipelined behind that response is not processed: its handler never runs, and it gets no response (RFC 9112 §9.6). That covers Upgrade and CONNECT too.
  • This also fixes the case where a client that keeps pipelining could hold the connection open forever.
  • If the response headers were already written before close(), they can't be changed. They still say keep-alive, but the connection closes after that response anyway.

Where it differs from "first commit + fix 2"

  • Requests whose handlers already ran before close() are still answered. Only the last of those responses says Connection: close.
  • I kept this because Node, unlike Go and hyper, runs pipelined handlers right away. With the strict version those handlers would already have run, and their responses would be discarded. A POST would then have its side effects but the client would never get an answer.
  • It costs one small helper (isLastResponse()) and two tests. If you'd still prefer the strict version, I'm happy to drop it.

Other notes

@mcollina mcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lgtm

@mcollina mcollina added the request-ci Add this label to start a Jenkins CI on a PR. Only starts once the PR has an approving review. label Dec 2, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@MikeMcC399 MikeMcC399 removed the request-ci Add this label to start a Jenkins CI on a PR. Only starts once the PR has an approving review. label Dec 2, 2026
@MikeMcC399

This comment was marked as outdated.

@araujogui araujogui added the resume-ci Add this label to resume the latest eligible Jenkins CI run on a PR with an approving review. label Dec 2, 2026
@github-actions github-actions Bot removed the resume-ci Add this label to resume the latest eligible Jenkins CI run on a PR with an approving review. label Dec 2, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@Ethan-Arrowood

Copy link
Copy Markdown
Contributor

Needs one more @nodejs/tsc approval for a major change

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

http Issues and PRs related to the http subsystem. needs-ci PRs that need a full CI run. semver-major PRs that contain breaking changes and should be released in the next major version.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants