A deploy finishes, the dashboard is green, and a handful of users still saw an error page. The new code is fine. The problem is the old process, which exited while it was holding live requests, or kept receiving traffic after it had already stopped listening.
These failures are easy to ignore because they are small and brief. They also happen on every single release, so a team that ships ten times a day is producing ten little outages a day. This guide walks through what actually happens when a server is told to stop, and how to make that moment uneventful.
Photo by Jordan Harrison on Unsplash
Why deploys drop requests in the first place
A web process spends most of its life in the middle of something. It is reading a request body, waiting on a database, or streaming a response. When the process is killed outright, every one of those operations ends at once, and the client sees a reset connection or a gateway error.
There are two separate gaps to close. The first is in-flight work: requests the process has accepted but not finished. The second is routing delay: the period during which a load balancer still believes the old instance is healthy and keeps sending it new requests.
Teams often fix the first gap and then wonder why errors continue. Draining your own connections does nothing about a proxy that has not yet heard you are leaving. You need both, and you need them in the right order.
Learn what your platform sends and when
On Unix-like systems, a polite stop request usually arrives as SIGTERM. A process can catch it and clean up. SIGKILL cannot be caught or ignored, which the Linux signal manual states plainly. Everything you want to do has to happen between the first signal and the second.
How long that window lasts depends on the platform. docker stop waits 10 seconds by default before forcing the container down. Kubernetes gives a pod 30 seconds by default, controlled by terminationGracePeriodSeconds.
The Kubernetes pod lifecycle documentation is worth reading closely on one point. Any preStop hook runs first and its time counts against the same grace period. A 25 second hook inside a 30 second budget leaves your application about 5 seconds.
Write the number down for each environment you run. A shutdown routine that assumes 60 seconds on a platform that allows 10 will be cut off every time, and the logs will not explain why.
Make sure the signal reaches your code
A surprising share of shutdown bugs come from a handler that is correct and never runs. In a container, signals go to the process with ID 1. If that process is a shell or a package script wrapper, your application may never hear anything.
The common cause is the shell form of a container start command. Written as a plain string, the command runs under /bin/sh -c, and the shell does not forward signals to its child. Use the exec form, a JSON array, so your runtime is started directly. The Docker documentation describes the difference between the two forms.
If you need a startup script for environment setup, end it with exec so the application replaces the shell. If your application spawns child processes of its own, consider a small init process that forwards signals and reaps children.
Verify this before writing anything else. Add a log line at the top of your handler, stop the container, and confirm the line appears. If the container takes the full grace period to exit and prints nothing, the signal is not arriving.
Stop accepting new work, then finish what you have
Once the signal arrives, the core sequence is short. Close the listening socket so no new connections are accepted. Let active requests complete. Close idle keep-alive connections. Then release shared resources and exit.
In Node, server.close() stops new connections and waits for existing ones. The details of idle keep-alive handling have changed across releases, so check the Node HTTP module reference for the version you run. Recent versions also expose closeIdleConnections() and closeAllConnections() for finer control.
let shuttingDown = false;
process.on('SIGTERM', () => {
if (shuttingDown) return;
shuttingDown = true;
const deadline = setTimeout(() => process.exit(1), 20000);
deadline.unref();
server.close(async () => {
await db.end();
await queue.close();
process.exit(0);
});
server.closeIdleConnections();
});
Two details in that snippet matter. The guard flag makes a repeated signal harmless. The deadline timer guarantees the process exits on your terms, with a log entry and a non-zero code, before the platform kills it silently.
Order the cleanup from the outside in. Database pools and message clients must stay open until the last request that needs them has finished. Closing the pool first turns every in-flight request into a failure, which is worse than not handling the signal at all.

Photo by Connor Scott McManus on Pexels
Handle keep-alive and long-lived connections
HTTP keep-alive is good for latency and awkward at shutdown. A client or proxy holding an idle connection may send another request on it just as you are closing. During draining, set Connection: close on responses over HTTP/1.1 so clients open a fresh connection next time, which will land on a healthy instance.
Your server's idle timeout should also be longer than the idle timeout of the proxy in front of it. If the application closes an idle connection first, the proxy can race it with a new request and report a bad gateway. This causes sporadic errors even between deploys.
WebSockets and server-sent events will not end on their own. Decide what happens to them. A sensible default is to send an application message asking the client to reconnect, wait briefly, then close with an appropriate status code. Spread reconnects with a small random delay so one retiring instance does not cause a stampede.
Large uploads and report downloads need an explicit policy too. Either give them a longer grace period on a dedicated service, or make them resumable so interruption is recoverable.
Give the load balancer time to notice
Routing updates are not instant. In Kubernetes, removing a terminating pod from service endpoints happens in parallel with signalling the pod. For a short stretch, traffic can still arrive at a process that has been told to stop.
The practical fix is to keep serving for a few seconds before closing the listener. A short preStop sleep does this without touching application code. Alternatively, the signal handler can mark the instance unready, wait, and only then call close.
Readiness and liveness checks should answer different questions. During shutdown the readiness endpoint should fail, so the instance is taken out of rotation. The liveness endpoint should keep passing, because a failed liveness check tells the orchestrator to restart a process that is behaving correctly.
Reverse proxies have their own graceful stop behaviour. The nginx process control documentation explains that QUIT performs a graceful shutdown while TERM is a fast one. If nginx sits in the same pod or host as your app, the proxy should stop taking requests before the application does.
Budget the grace period like a schedule
Treat the window as a timeline and assign each stage a share. For a 30 second budget, a reasonable plan is 5 seconds waiting for routing updates, up to 20 seconds draining requests, and a few seconds closing resources and flushing logs.
The longest request you allow sets the floor. If some endpoint may legitimately run for two minutes, no 30 second drain will save it. Move that work to a background job, or raise the grace period and accept slower rollouts.
Request timeouts help here. When every request has an upper bound shorter than the drain stage, you can promise that a clean shutdown completes. Without bounds, one stuck call holds the process until it is killed.
Flush telemetry last. Buffered logs, traces and metrics are often lost at exit, which removes the evidence you would use to debug the shutdown itself.
"A release process is only as calm as its worst thirty seconds. We would rather spend a day on how the old version leaves than keep explaining a few mystery errors after every deploy." - Dennis Traina, founder of 137Foundry
Apply the same discipline to workers and cron jobs
Background workers need the same behaviour with a different shape. On SIGTERM, stop pulling new messages first. Finish the current job if it fits in the budget, or return it to the queue without acknowledging it.
That second path only works if jobs are safe to run twice. A job that charges a card or sends an email needs an idempotency key or a recorded checkpoint. Interruption will happen eventually, through a crash if not through a deploy.
Long batch jobs should save progress in small units and resume from the last one. A job that must run uninterrupted for an hour will fight every release. Teams building queue-driven systems run into this often, and it is a recurring theme in our data integration work.

Photo by Tima Miroshnichenko on Pexels
Prove it with traffic running
A shutdown handler that has never been exercised under load is a guess. The test is simple: run a steady stream of requests against a staging environment, trigger a rolling deploy, and count failures. The target is zero connection errors and zero gateway errors.
Include slow requests in the mix. A test made only of fast health checks will pass even when draining is broken, because nothing is ever in flight at the moment of termination. Add a few endpoints that take several seconds.
Log three timestamps from every instance: signal received, listener closed, and process exit. Together they show whether the handler ran, how long draining took, and whether you finished on your own or hit the deadline.
Then keep the check in your pipeline. Shutdown behaviour regresses quietly when someone adds a new client library, a new background timer, or a new start script. Alert on deadline exits so a slow drain gets noticed before users report it.

Photo by Markus Spiske on Pexels
A short checklist before your next release
Confirm the runtime is the process that receives the signal. Confirm a handler stops new work, drains old work, closes resources, and exits before the platform deadline. Confirm readiness fails during shutdown while liveness does not.
Check that proxy and application idle timeouts are ordered correctly, and that workers either finish or safely requeue. Finally, run a deploy under load and read the numbers.
None of this is exotic, and most of it is a few dozen lines plus configuration. If your releases still produce unexplained errors, our web development services include tracing exactly this kind of deployment behaviour, and you can learn more about the team on the 137Foundry homepage.