How to Implement Graceful Shutdown for In-Flight Work
Shut down without dropping work: stop accepting, drain in-flight requests, bound the drain with a deadline, and close dependencies last.
On this page
Introduction
A process that exits the moment it is asked to stop drops the work in progress. On a rolling deploy, a restart, or a scale-down, that means the users with a request in flight get an error at exactly the moment your change is unrelated to them. Graceful shutdown removes that class of error: stop accepting new work, finish what is in progress, then exit. It is what makes a deploy invisible instead of a brief outage.
This tutorial implements a graceful shutdown: stop accepting, drain the in-flight work, bound the drain with a deadline, and close the dependencies last. The examples use a Node.js server and signal handling, and the sequence applies to any long-running process with in-flight work.
Stop accepting new work first
The first step on a shutdown signal is to stop accepting new work, so the backlog does not grow while you drain. For an HTTP server, stop listening for new connections; for a worker, stop pulling new jobs. If new work kept arriving while the drain runs, the drain would never finish because the backlog grows as fast as it is processed.
In a container orchestration, the platform sends a signal and, after a grace period, kills the process. The signal handling starts the drain, and the grace period is the deadline. Also fail the readiness probe so the load balancer stops sending new requests to this instance before the drain begins, which removes the traffic rather than just refusing it. The sequence is: fail readiness, wait a moment for the load balancer to notice, then stop accepting.
let shuttingDown = false;
process.on('SIGTERM', () => {
shuttingDown = true; // readiness now fails, so the LB drains us
server.close(() => { // stop accepting new connections
// the callback fires when all connections are closed: drain complete
closeDependencies().then(() => process.exit(0));
});
});
Drain the in-flight work
Let the requests already in progress finish. For an HTTP server, close the listener so no new connections arrive, and wait for the active connections to complete. For a queue worker, finish the job it is running and stop claiming more. The drain is the period during which the work already accepted runs to completion, and it is what makes the shutdown graceful rather than abrupt.
Track the in-flight count so you can wait for it to reach zero. A request that is in a slow downstream may take a while, so the drain has a natural duration, which is why the deadline is needed. Do not accept new work during the drain, because accepting it resets the completion condition and the drain never ends.
let inFlight = 0;
server.on('request', (req, res) => {
inFlight++;
res.on('finish', () => { inFlight--; }); // decrement when a request completes
});
// during drain: wait until inFlight === 0 (or the deadline fires)
Bound the drain with a deadline
Give the drain a maximum time, so a stuck task does not hang the shutdown forever. When the deadline fires, force-close the remaining work and exit, logging what was abandoned. An unbounded drain is worse than dropping a task, because the platform kills the process after its grace period anyway, and the abandoned task is dropped with no log.
Choose the deadline below the platform’s grace period, so you exit cleanly before the force kill. If the platform gives thirty seconds, drain for about twenty-five and force-close, leaving time to close dependencies and exit. The deadline should also account for the slowest expected request, so the common drain finishes before it, and only the genuinely stuck work hits the deadline.
Close dependencies last
The database pool, the cache client, and the message consumer must stay open while in-flight work uses them, and close only after the drain. Closing them first causes in-flight requests to fail with a closed-connection error, which is the opposite of graceful. Close them in the order the work depends on them, after the in-flight count reaches zero.
Close each dependency with its own graceful close, which flushes buffered writes and completes in-flight queries before closing the socket. A hard close drops those. Then exit with a success code so the platform records a clean termination. The sequence is: stop accepting, drain, close dependencies gracefully, exit, and each step in that order.
async function closeDependencies() {
await server.close(); // already draining; ensure connections are done
await db.end(); // flush and close the pool gracefully
await redis.quit(); // flush pending commands, then close
await consumer.stop(); // finish and acknowledge in-flight jobs
}
Test the shutdown under load
Send a shutdown signal while requests are in flight and assert each in-flight request completes successfully rather than failing. Assert no new requests are accepted after the signal, by sending one and asserting it is refused or not routed. Assert a stuck request is force-closed after the deadline and the process exits within the grace period. Assert the process exit code is success.
# start a slow request, send SIGTERM, and assert the request still completes
curl -s 'http://localhost:3000/slow' & # takes ~3s
sleep 0.5
kill -TERM $(cat server.pid)
wait # the slow request must return 200, not an error
# and the process must exit cleanly within the deadline
Common pitfalls
Exiting immediately on the signal so in-flight work fails, accepting new work during the drain so it never completes, no deadline so a stuck task hangs the shutdown, closing dependencies before the drain so in-flight requests error, and a hard close that drops buffered writes are the recurring mistakes. Stop-accept, drain, a bounded deadline, close-last with graceful closes, and a readiness failure first address them.
Conclusion
Graceful shutdown makes a deploy invisible. On the signal, fail readiness so the load balancer drains, stop accepting, wait for the in-flight work with a bounded deadline, then close dependencies gracefully and exit. Self-check by sending a slow request, sending the signal, and asserting the request completes and the process exits within the deadline. Then a restart does not become a brief outage.
Sources: Node.js: Graceful shutdown, Kubernetes: Pod termination and graceful shutdown, MDN: Server close and connection draining.
FAQ
- Why not just exit on SIGTERM?
- An immediate exit drops the requests in progress, so a deploy causes errors for the users with requests in flight. A graceful shutdown stops new work, finishes the in-flight work, and then exits, so a rolling deploy is invisible to users.
- What if a task never finishes?
- Bound the drain with a deadline and force-close after it. An unbounded drain can hang the shutdown on one stuck task, which is worse than dropping it. Log what was abandoned so the stuck task is visible.
Report a problem with this articleOpens a pre-filled issue on GitHub.