Graceful Shutdown for a Node.js HTTP Server

Calling process.exit() when a deployment sends SIGTERM is certainly a quick way to stop a server. Whether it is a good way depends on what the server was doing at the time.
A response might be half‑written. A handler might still need its database connection. An idle keep‑alive connection might be doing nothing useful at all. Treating those three cases identically makes the shutdown code pleasantly short and the resulting incident rather longer.
For a long‑lived Node.js service, I want a shutdown sequence with a clear order: stop admitting work, let accepted work finish within a budget, close the resources it depends on, then report the outcome. I also want to test that sequence with a real process and real sockets. Mocking process.exit() proves very little about whether a response reaches its caller.
Decide That the Process is Draining
My example has a readiness state and an admission gate. The first signal changes that state before starting the asynchronous cleanup:
if (draining) {
res.writeHead(503, { Connection: 'close' });
res.end('Draining');
return;
}This check belongs before the handler starts work. A load balancer can take time to observe a readiness change, and a connection accepted earlier may still carry another request. Saying "unready" is useful coordination, but it is not a substitute for deciding what the application will admit.
The fixture's readiness endpoint returns successfully before shutdown. Once shutdown starts, the listener closes, so a new probe may find the process unreachable rather than receiving a 503 response. The existing‑connection check is separate: the test sends another HTTP request down an already‑active connection and confirms that the gate rejects it without increasing the admitted‑work count.
In a deployment platform, establish how readiness removal and termination are ordered. I would not insert an arbitrary sleep and call that load‑balancer integration. A propagation allowance needs to come from the actual platform behaviour and fit inside the total termination budget.
Let the HTTP Server Close Normally First
The ordinary drain starts with server.close(). It stops new connections and waits for existing activity to finish. In Node 20.3.1, it also closes idle HTTP connections; the idle‑connection behaviour changed in Node 19, as recorded in the versioned HTTP documentation.
That version detail matters when copying shutdown code from an older service. Calling closeIdleConnections() may be part of supporting an earlier runtime, but I don't need it to make the pinned Node 20 example close its idle keep‑alive connection.
My test opens one idle connection and holds a separate request in progress. After sending SIGTERM, it releases the held response and reads the complete body at the client. It also waits for the idle socket to close. The evidence is the response and connection lifecycle, not just a server log announcing that shutdown began.
The fixture releases held work through its parent‑process control channel. That is test machinery, not a second public endpoint which remains available after the listener has closed.
Close Dependencies After Their Users
A database pool should remain available whilst an accepted request still needs it. The same applies to a queue client, a file handle, or another shared resource used by active handlers.
My synthetic resource records the active‑request count when disposal begins. The successful test requires that count to be zero and checks that disposal runs once. It would fail if the service closed its dependencies first and merely hoped the outstanding handlers were nearly finished.
With several independent disposers, there may be value in collecting all their outcomes so one rejection doesn't prevent attempting the others. My guide to Promise.allSettled() explains that distinction. Independence still needs checking: a resource which another disposer uses cannot be closed in an arbitrary parallel group.
A rejected disposal should affect the reported shutdown result. The example uses a non‑zero exit code for that case. It does not report success because the HTTP listener happened to close successfully earlier in the sequence.
Give Repeated Signals One Answer
Two signals must not start two disposal sequences. The example retains the shutdown promise and returns it on subsequent calls. Its draining flag changes synchronously on the first call, before any awaited work.
The test sends a second SIGTERM whilst the held request is still active. It then checks that the request completes, the resource closes once, and the process exits normally. This is more useful than testing two calls against a shutdown function whose dependencies have all been mocked as instant successes.
Installing a signal handler also changes the process's default signal behaviour. The application has taken responsibility for finishing. On the normal path, I set process.exitCode, clear the shutdown timer, close the remaining owned handles, and let the process exit. Node's process documentation explains why an immediate process.exit() can cut pending output short.
Keep One Budget Around the Whole Sequence
A request may never finish. Neither may a disposer. A deadline covering only the HTTP drain leaves the second case free to hang indefinitely.
The lab starts one timer when shutdown begins and keeps it until the entire sequence settles. A deliberately stuck handler reaches that deadline. A second fault lets HTTP close but leaves resource disposal pending; it must reach the same deadline too.
At expiry, the example closes active HTTP connections, destroys tracked upgraded sockets, and exits with failure. That is the deliberate last‑resort path. It can interrupt work and does not turn an unfinished operation into a successful one. Normal draining should have had its chance before getting here.
The small test budget is chosen to make the cases run quickly. A production value needs to leave room inside the supervisor's termination allowance for the application to finish and report its outcome. Request timeouts, upstream cancellation, background workers, and any platform drain period all belong in that calculation.
Remember Connections Which Stopped Being HTTP
An upgraded connection needs its own lifecycle. My fixture accepts a tiny synthetic protocol so that the test can hold such a socket open. It is not a WebSocket implementation.
On the ordinary path, the service explicitly ends that connection. In the faulty variant, it leaves the upgraded socket open and reaches the shutdown deadline. This demonstrates why an HTTP connection helper is not a complete policy for every socket the process owns.
A real WebSocket service needs an appropriate closing handshake and a bounded wait for peers. A long‑lived subscription or background worker may need another owner and another stop operation. List those resources explicitly; otherwise the tidy HTTP callback can conceal the process which is still sitting there afterwards.
Test the Process from Outside It
My shutdown lab runs the service as a child process, sends real POSIX signals, drives HTTP and upgraded connections, and records the exit status. Each case has an independent parent watchdog which kills a child that outlives the test budget and waits for it to close.
That outside supervision matters because a JavaScript timer is not a hard interruption mechanism. As I explain in my event‑loop guide, a blocked thread cannot run its queued callbacks. A shutdown timer on that same thread cannot rescue it. The supervisor still needs its own enforced limit.
A graceful shutdown is successful when the accepted work, resource cleanup, and final process result agree. "The process disappeared" is a considerably less demanding test.
Postscript
November 2026: I've rerun my shutdown lab on Node 22.23.5 as well as the original Node 20.3.1 baseline. My download includes both the ordinary drain cases and a deliberately blocked event loop, which only the independent parent watchdog can terminate. The historical runtime remains useful for reproducing the article; use a supported runtime for a deployed service.