skip to content

In a Node 24 HTTP server, what does server.close() wait for, and how do closeIdleConnections() and closeAllConnections() differ from it?

level: middleimportance: should knowfreq 55%

answer

  1. listening socket versus open connections
  2. idle means no request in progress
  3. one is polite, one is forceful
  4. upgraded sockets are left alone

basics

~10 s

server.close() stops new connections, closes idle ones, and calls back only when every connection has ended. closeIdleConnections() destroys only idle connections; closeAllConnections() destroys active ones too, except upgraded sockets such as WebSocket.

solid answer

~40 s

`server.close(callback)` stops the listening socket and, since Node 19, also closes connections that are not sending a request or waiting for a response; busy connections keep running, and the callback, like the `'close'` event, fires once every connection has ended. If the server was not running, the callback receives an `ERR_SERVER_NOT_RUNNING` error. `server.closeIdleConnections()` destroys only idle connections, which on Node 19 and later `close()` already does for you. `server.closeAllConnections()` destroys every HTTP connection, including requests in progress, but not sockets upgraded to another protocol such as WebSocket or HTTP/2. The docs recommend calling either one after `server.close()`, so no new connection slips in between.

code

javascript · 17 lines
javascript
import http from 'node:http';

const server = http.createServer((req, res) => res.end('ok'));
server.listen(3000);

function closeWithin(ms) {
  return new Promise((resolve, reject) => {
    server.close((err) => (err ? reject(err) : resolve()));
    const t = setTimeout(() => server.closeAllConnections(), ms);
    t.unref();
  });
}

process.once('SIGTERM', async () => {
  await closeWithin(10_000);
  console.log('server closed');
});

go deeper

for a junior

Remember that server.close() stops new connections but waits for the existing ones before its callback fires.

for a middle

Explain idle versus busy connections, what changed in Node 19, and why closeAllConnections() is the forceful last resort.

for a senior

Show the escalation pattern with a deadline, call order after close(), and the gap for upgraded sockets that none of these methods covers.

for a principal

Decide whether a team's drain ends by cutting connections at a deadline or by waiting for the platform to kill, and make that one shared choice.

## Two layers: the listener and the connections An `http.Server` in Node is a `net.Server` underneath. It owns two kinds of resource: - the **listening socket**, which accepts new TCP connections on a port; - the **connections** already accepted, each a `net.Socket` that may carry many HTTP requests one after another when **keep-alive** is used. Closing a server cleanly means dealing with both. The three methods split the job differently. ## `server.close([callback])` `close()` stops the listening socket, so no new connection is accepted. At the `net.Server` level it then **keeps existing connections**: the server is fully closed, and emits `'close'`, only when all of them have ended. The optional callback runs at the same moment; unlike the event, it receives an `Error` if the server was not open, the `ERR_SERVER_NOT_RUNNING` code. For HTTP servers, Node 19 changed `close()`: it now **closes idle connections before returning**. An idle connection here is one that is not sending a request and not waiting for a response, which is the state a keep-alive socket sits in between requests. Before Node 19, a single idle keep-alive client could hold `close()` open until `keepAliveTimeout` expired, which is why older shutdown code called `closeIdleConnections()` explicitly. What `close()` does **not** do: it does not touch connections that are busy at the moment of the call, and it does not mark their responses `Connection: close`. A busy socket that finishes its response becomes a normal keep-alive socket again and can carry further requests. ## `server.closeIdleConnections()` Added in Node 18.2.0, this destroys every connection that is currently idle, skipping any socket whose response is still being written. It is a point-in-time sweep: a connection that becomes idle a moment later is untouched. The Node 24 docs note there is no need to call it alongside `close()` from Node 19 onwards, though doing so is harmless, and if you do call it, call it after `close()` so a fresh connection cannot arrive between the two. ## `server.closeAllConnections()` Also added in 18.2.0, this is the **forceful** option: it destroys every established HTTP or HTTPS connection, including ones in the middle of a request. The client sees its connection reset and the request fails. Two limits matter: 1. It does **not** destroy sockets **upgraded** to a different protocol, such as WebSocket connections or HTTP/2 sessions; those must be closed by whatever handles the upgraded protocol. 2. It should be called **after** `close()`, for the same race-avoidance reason the docs give for the idle variant. Its usual place is the end of a drain budget: if requests are still running when time is up, cut them deliberately rather than waiting to be killed. ## Side by side | Method | Stops new connections | Idle connections | Busy connections | Upgraded sockets | |---|---|---|---|---| | `server.close()` (Node 19+) | yes | closed | left to finish | left | | `server.closeIdleConnections()` | no | destroyed | left | left | | `server.closeAllConnections()` | no | destroyed | destroyed | left | | `server[Symbol.asyncDispose]()` | as `close()` | as `close()` | as `close()` | as `close()` | `server[Symbol.asyncDispose]()` calls `close()` and returns a promise that fulfils when the server has closed; the Node 24 history marks it no longer experimental from v24.2.0. It lets `await using server = ...` close the server at the end of a block. ## Common mistakes - **Treating `close()` as synchronous.** It returns at once; the drain finishes later, when the callback or `'close'` fires. - **Calling `closeAllConnections()` first.** The listening socket is still open, so a new connection can arrive before `close()` runs. - **Expecting `closeAllConnections()` to end WebSocket sessions.** Upgraded sockets are outside its reach, so a server holding them never reaches `'close'` until their owner closes them. - **Assuming busy sockets close when their response ends.** Without `Connection: close` they stay keep-alive and may carry more requests. ## Putting them together A typical drain uses them in escalating order: 1. `server.close(callback)` to stop accepting and release idle sockets. 2. Wait for the callback, bounded by the drain budget. 3. If the budget is nearly spent, `server.closeAllConnections()` so the callback can fire and the process can exit on its own terms. The HTTP server's timeout settings themselves, `keepAliveTimeout`, `headersTimeout` and `requestTimeout`, are covered with the HTTP server; here they matter only as the reason a connection may stay open.

  • A Node 24 server has a client that keeps sending requests over one keep-alive connection. Does server.close() ever complete?
    Only when that connection ends. `close()` released it only if it was idle at the moment of the call; if it was busy, it finishes its response and stays open, and the client may send another request on it, which the server still serves. Setting `Connection: close` on responses while draining, or calling `closeAllConnections()` at a deadline, ends it.
  • Why do the Node docs recommend calling closeAllConnections() after server.close() rather than before?
    If you destroy connections first, the listening socket is still open and a new connection can be accepted before `close()` runs, so the server is not empty when you expected it to be. Calling `close()` first stops accepting, so the sweep that follows covers every connection the server will ever have.

  • server.close() destroys all open connections immediately
  • In Node 24 you must call closeIdleConnections() or close() never finishes
  • closeAllConnections() also tears down WebSocket connections
  • server.close() marks busy responses Connection: close
  • The close callback fires as soon as the port stops listening

Assumes Node 24; Node 19 made server.close() close idle connections, closeIdleConnections() and closeAllConnections() arrived in 18.2.0, and Symbol.asyncDispose became stable in 24.2.0.