Graceful shutdown
Prerequisite: node-timeouts-retries-and-circuit-breakers. Objective: Trace draining and deadline. Local baseline: Node.js 22.16.0 on Linux, ESM. Each example is independent: save as main.mjs in a disposable directory and run node main.mjs. The author harness uses a five-second timeout. Static snippets are not ByteMind interactive execution.
How it works
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.
Drain an active HTTP request using explicit gates
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');Expected output:
accepting falseactive finishedclosedThe active request is held by a promise, then deliberately released. The close promise establishes completion rather than a sleep.
Model deadline and completion decisions
function decide({active,expired}){if(active===0)return 'close dependencies';if(expired)return 'force stop';return 'continue draining';}for(const input of [{active:2,expired:false},{active:0,expired:false},{active:1,expired:true}])console.log(decide(input));Expected output:
continue drainingclose dependenciesforce stopThis is a policy model, not actual signal or connection cleanup; the earlier example tests normal HTTP drain.
Common mistakes
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.
Practice
Design a shutdown test with one active request and one stuck request; state which result should be allowed before the deadline and how forced interruption is reported.
Reference candidate: node-graceful-shutdown-lookup (route unverified). Documentation: https://nodejs.org/download/release/v22.16.0/docs/api/http.html. Selected versioned documentation opened.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Graceful shutdown — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
When should readiness become false?
What confirms the normal HTTP drain in the example?
What needs separate cleanup from ordinary HTTP connections?