Reliability

Graceful shutdown

Graceful shutdown is a sequence: stop admission, finish permitted in-flight work, close dependencies and terminate within a deadline. An HTTP server has a different drain boundary from a worker or a database client. In Node 22, server.close stops accepting new connections and closes idle HTTP connections while active requests finish. Existing upgraded sockets need separate ownership and cleanup; closeAllConnections is forceful and does not close upgraded sockets. Mark readiness false before draining and stop background producers as appropriate. Do not rely on an arbitrary sleep as proof of completion; await resource-specific completion signals. A deadline policy may interrupt work, so state changes need recovery and idempotency. Do not immediately call process.exit after beginning asynchronous cleanup. A drain can hang if active requests never finish; a supervisor should enforce a bounded stop policy. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/http.html.

Formal Syntax & Structure

nodejs syntaxnodejs
server.close(callback); server.closeAllConnections()

Working Example

Example Snippetnodejs
import {createServer} from 'node:http';import {once} from 'node:events';import assert from 'node:assert/strict';let started,release;const entered=new Promise(r=>started=r),gate=new Promise(r=>release=r);const server=createServer(async(req,res)=>{started();await gate;res.end('finished');});server.listen(0,'127.0.0.1');await once(server,'listening');const pending=fetch(`http://127.0.0.1:${server.address().port}`,{signal:AbortSignal.timeout(1500)});await entered;const closed=new Promise((ok,fail)=>server.close(e=>e?fail(e):ok()));console.log('accepting',server.listening);release();const response=await pending;assert.equal(await response.text(),'finished');console.log('active finished');await closed;console.log('closed');
Node.js Reference