Sources indicate that every deploy kills your old processes. The only question is whether they die politely or take a few dozen user requests down with them.
Recent findings suggest that if you've ever seen a burst of 502 Bad Gateway or ECONNRESET errors right after a rollout, and then everything magically recovers, you've met the problem this post is about. The fix is called graceful shutdown, and in Node.js it takes about 40 lines of code plus two lines of infrastructure config.
Here's what happens, why the defaults bite you, and the exact code we use on production APIs.
Whether it's docker stop, a Kubernetes rolling update, or an autoscaler removing an instance, the sequence is roughly:.
According to recent reports, node's default behaviour on SIGTERM is to exit immediately. That means:.
Graceful shutdown is simply: catch SIGTERM, stop taking newly introduced work, finish the work you have, close your connections, then exit.
Industry observers note that server.close() stops the server from accepting latest connections and calls back once existing ones are done. Better than nothing, but there are three gaps:.
Here's a complete Express + PostgreSQL example that handles all three:.
Industry observers note that the shuttingDown flag flips the readiness probe to 503. Kubernetes (or your AWS/GCP load balancer health check) stops routing newly introduced requests to this instance, while requests already in flight carry on.
It has been revealed that the 5-second sleep covers the race between SIGTERM and endpoint removal. During those seconds the server is still fully working, so any late requests succeed. Tune it to your load balancer: a couple of health-check intervals is a sensible starting point.
In a recent development, connection: close makes every response during draining tell the client to drop the socket. Combined with server.closeIdleConnections() (Node 18.2+), keep-alive connections no longer hold the shutdown hostage.
pool.end() waits for checked-out database clients to be released and then closes the pool cleanly, so PostgreSQL doesn't log a pile of "unexpected EOF" errors.
Sources indicate that the force-exit timer is your safety net. .unref() means the timer itself won't keep the process alive. Keep this deadline shorter than the orchestrator's grace period so you exit on your own terms.
In a recent development, APIs aren't the only thing that gets interrupted. If you run queue consumers, close them in the same shutdown function so the current job finishes and no new job is picked up. With BullMQ, for example:.
The same idea applies to cron-style timers (clearInterval), WebSocket servers (send a close frame, then close), and Kafka/RabbitMQ consumers (stop consuming, commit offsets or ack, then disconnect).
Order matters: stop intake first, finish work, then close shared resources (database, Redis, message broker). Closing the database before the in-flight requests finish just turns graceful shutdown into a different kind of crash.
In a recent development, this one trips up a lot of teams. If your Dockerfile looks like this:.
In a recent development, that's the shell form, which runs your app under /bin/sh -c. The shell becomes PID 1, and it doesn't forward SIGTERM to Node. Your handler never runs, Docker waits out the grace period, then SIGKILLs everything.
Use the exec form and run Node directly:.
There's a second subtlety: a process running as PID 1 doesn't get the kernel's default signal behaviour. Without a handler, Node as PID 1 will simply ignore SIGTERM. Our handler above covers that, but adding a tiny init process is still a good idea because it also reaps zombie child processes:.
Or in Kubernetes/Dockerfile, use tini as the entrypoint.
Two settings to check in your Deployment:.
It has been revealed that if you'd rather keep the delay out of your application code, you can use a preStop hook instead of the in-app sleep(5_000). Kubernetes runs the hook before sending SIGTERM, and its duration counts toward the grace period:.
The native sleep action is available on recent Kubernetes versions (1.30+ by default). On older clusters, exec: { command: ["sleep", "5"] } does the same job, provided your image actually contains a sleep binary (distroless images don't).
Don't trust it until you've watched it work under load:.
Without graceful shutdown you'll see errors and resets in the autocannon summary. With it, the in-flight requests complete, new connections start failing only after the server has actually stopped listening, and the logs show a clean Shutdown complete.
In a real cluster, run a load test while doing kubectl rollout restart deployment/my-api and watch your 5xx rate. It should stay flat.
Graceful shutdown is one of those things nobody notices when it works, and everybody notices when it doesn't: a spike of failed checkouts every time you deploy, half-processed jobs, mysterious connection errors in the database logs. Forty lines of code and a couple of probe settings make deployments boring again, which is exactly what you want.
In a recent development, at Prism Infoways, we build and run web apps, APIs and cloud infrastructure for growing businesses, and zero-downtime deploys are part of every production setup we ship as part of our API development services. If your releases still come with a side of 502s, we're happy to help.
How do you handle shutdown in your Node.js services? Share your setup or war stories in the comments.
