How to Implement Graceful Drain with Readiness Gates
Stop sending traffic to an instance before shutting it down, let in-flight requests finish, then exit so deploys are invisible.
On this page
Introduction
When an instance is removed from a load balancer, the balancer may take seconds to stop sending it new traffic, and during that window requests can still arrive. If the instance shuts down immediately on a termination signal, those requests fail. Graceful drain fixes this: on shutdown, the instance first marks itself not-ready so the load balancer stops routing to it, waits long enough for the change to propagate, then finishes the requests already in flight, then exits. The result is a deploy that users never notice. This article covers the sequence, the timings that make it work, and the failures that appear when a step is skipped.
Why Immediate Shutdown Fails
An orchestrator sends a termination signal, and most applications exit on it. But the load balancer or service mesh that routes to the instance is updated asynchronously, so for a short period after the signal it still considers the instance healthy and may route new requests to it. An instance that exits during that period drops those requests, producing errors that correlate with deploys. The bug is timing, not logic.
There are also in-flight requests: a request that arrived just before the drain began is still being processed, and exiting cuts it off mid-flight. A graceful shutdown waits for these to finish within a bounded time, so the request completes instead of failing. Both problems need to be handled, and handling only one leaves a window of errors.
The Drain Sequence
The sequence has four steps. On the termination signal, fail the readiness probe immediately so the orchestrator and load balancer mark the instance as draining. Wait for the propagation delay so no new traffic is routed to it. Keep serving in-flight requests and health probes as appropriate. After the in-flight work drains, or a maximum timeout passes, exit. Each step has a duration that must be sized to the system.
const http = require('node:http');
let ready = true;
let draining = false;
let inflight = 0;
const server = http.createServer((req, res) => {
if (req.url === '/healthz') { // liveness: still alive
res.writeHead(200).end('ok');
return;
}
if (req.url === '/readyz') { // readiness: gates traffic
res.writeHead(ready ? 200 : 503).end(ready ? 'ready' : 'draining');
return;
}
inflight++;
req.on('close', () => inflight--);
handle(req, res);
});
async function shutdown(signal) {
console.log('got ' + signal + ', draining');
ready = false; // step 1: fail readiness
await sleep(5000); // step 2: let the LB notice
const deadline = Date.now() + 25000; // step 3: bounded drain
while (inflight > 0 && Date.now() < deadline) await sleep(100);
server.close(() => process.exit(0)); // step 4: exit
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
Sizing the Timings
The propagation delay must exceed how long the load balancer takes to notice the failed readiness probe and stop routing, including health-check interval plus the balancer’s own update time. If you drain too quickly, requests already in flight to the instance from the balancer’s stale view keep arriving. Measure the actual delay rather than guessing; a common mistake is a two-second drain when the balancer polls every five seconds.
The in-flight timeout must exceed the longest request the instance can serve, including any retries and downstream calls. If it is shorter, a long request is cut off; if it is much longer, shutdowns drag during deploys. Set it from the observed p99.9 of request duration plus a margin, and make sure the orchestrator’s own grace period is longer than the sum of the propagation delay and the drain timeout, or the orchestrator will kill the instance before the drain completes.
# Kubernetes: the grace period must cover propagation + drain.
spec:
terminationGracePeriodSeconds: 60 # > 5s propagation + 25s drain + margin
containers:
- name: api
readinessProbe:
httpGet: { path: /readyz, port: 8080 }
periodSeconds: 5 # the LB notices within ~5s
failureThreshold: 1 # fail fast so drain starts promptly
livenessProbe:
httpGet: { path: /healthz, port: 8080 }
periodSeconds: 10
failureThreshold: 3 # a draining pod is still alive
lifecycle:
preStop:
exec: { command: ["/bin/sh", "-c", "sleep 5"] } # propagation delay
Readiness Versus Liveness
Readiness answers can this instance take traffic now, and liveness answers is this process healthy. They must be separate, because a draining instance is alive but not ready. If the liveness probe fails during drain, the orchestrator restarts the process instead of letting it finish, which defeats the drain. Gate traffic on readiness and reserve liveness for a real, unrecoverable fault.
The readiness probe must be cheap and reflect the ability to serve. A probe that checks a downstream dependency can flap and take a healthy instance out of rotation during a downstream blip; decide explicitly whether readiness should include dependencies. A good default is that readiness reflects the instance’s own ability to accept work, and dependency health is handled by degradation rather than by removing instances.
Draining Background Work
Long-lived connections need explicit handling. A WebSocket or server-sent-events connection does not finish on its own, so the drain must ask the client to reconnect, typically by sending a close frame or an event, and must bound how long it waits. A connection that is never closed will hold the drain until the timeout, so the drain should proceed after the timeout regardless.
Background jobs have the same problem: a job in progress should either finish within the drain window or be returned to the queue for another instance. Workers should stop pulling new jobs on the drain signal, finish the current one if it can, and release or requeue the rest. Without that, a deploy can leave a job half-done or drop it.
Testing the Drain
Test the drain under load: run continuous requests against the service, trigger a shutdown, and assert that zero requests fail and the instance exits within the expected time. This is the only way to know the timings are right, because a drain that works when idle can fail when busy. Repeat it as part of the pipeline so a change to the timings or the health probe is caught.
Also test the failure modes: a request that runs longer than the in-flight timeout should be cut off and retried by the client, and the orchestrator’s grace period should be long enough that the process exits before it is killed. A drain that relies on the orchestrator’s kill is not graceful; it is a crash with extra steps.
Conclusion
Graceful drain makes deploys invisible by failing readiness first, waiting for the load balancer to stop routing, finishing in-flight requests within a bounded timeout, and only then exiting. Size the propagation delay to the balancer’s real update time and the in-flight timeout to the longest request, keep readiness separate from liveness, handle long-lived connections and background jobs explicitly, and make the orchestrator’s grace period longer than the whole sequence. Test under load, because a drain that works when idle can still drop requests when busy.
Sources: Kubernetes: pod termination lifecycle, Kubernetes: readiness and liveness probes, Graceful shutdown.
FAQ
- Why fail readiness before shutting down?
- So the load balancer stops routing to the instance before it stops serving. Without that step, the balancer keeps sending requests for a short window after the process begins to exit, and those requests fail. Readiness gates the traffic; liveness stays healthy.
- Should readiness depend on downstream services?
- Usually not by default. A dependency blip can flap the probe and remove healthy instances, reducing capacity exactly when it is needed. Let readiness reflect the instance ability to accept work and handle dependency health with degradation.
Report a problem with this articleOpens a pre-filled issue on GitHub.