InsightsDevOps
Graceful shutdown on Kubernetes without dropped requests
Why rolling updates, scale-downs and node drains cause a burst of 502s and reset connections, and how a preStop sleep, signal handling in the application, a sized grace period and load balancer settings let pods leave without taking requests with them.
Published October 22, 20264 min read
Many services show a small spike of errors on every deploy. A few 502s from the ingress, some connection reset by peer in a caller's logs, a retry or two that nobody looks into. It happens again on every scale-down and every node drain, so it gets written off as "normal deploy noise".
It is not noise. It comes from a race between two things Kubernetes does at the same time when a pod is deleted, and it can be fixed with a handful of settings and about twenty lines of application code.
What happens when a pod is deleted
Deleting a pod, whether by kubectl delete, a rolling update, the autoscaler or a drain, sets a deletion timestamp on it. From that moment two independent processes start in parallel:
- On the node, the kubelet starts shutting the pod down. It runs each container's
preStophook if there is one, then sendsSIGTERMto process 1 in each container, and sendsSIGKILLto whatever is still running when the grace period expires. - In the control plane, the endpoint for that pod is marked
terminatingand stops beingreadyin its EndpointSlices. Every consumer of those slices then has to notice: kube-proxy on every node, the ingress controller, a service mesh, and any cloud load balancer controller that registers pod IPs as targets.
Nothing makes step 2 finish before step 1. If the application exits as soon as it receives SIGTERM, there is a window in which kube-proxy rules, ingress upstreams or load balancer targets still point at a pod that is no longer listening. Requests sent in that window fail.
The fix is ordering. Keep serving until the routing layers have caught up, then stop accepting connections, finish what is in flight and exit, all within the grace period.
Step 1: wait before shutting down
A preStop hook runs before SIGTERM is sent, so it is the natural place to wait. For years the usual way was exec: ["sh", "-c", "sleep 10"], which fails on distroless or scratch images that have no shell. Kubernetes now has a built-in sleep action, run by the kubelet rather than inside the container. It graduated to stable in Kubernetes 1.34 (KEP-3960):
spec:
terminationGracePeriodSeconds: 45
containers:
- name: checkout
image: registry.internal/checkout/api:4.1.0
ports:
- containerPort: 8080
lifecycle:
preStop:
sleep:
seconds: 10How long to sleep depends on what routes traffic to the pod. In-cluster routing through kube-proxy and most ingress controllers usually catches up within a few seconds. An external load balancer that registers pod IPs directly can take longer to stop sending new requests. Measure it with the test at the end of this article rather than copying a number.
Step 2: handle SIGTERM in the application
When SIGTERM arrives, the routing layers have stopped sending new work. The application should now:
- Stop accepting new connections.
- Let in-flight requests finish, up to a deadline shorter than what remains of the grace period.
- Close idle keep-alive connections so clients reconnect elsewhere.
- Flush telemetry, close database pools, and exit with status 0.
In Go, http.Server.Shutdown does most of this. It closes the listeners, closes idle connections and waits for active ones to finish:
func main() {
srv := &http.Server{Addr: ":8080", Handler: routes()}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
<-ctx.Done()
// The preStop sleep has already run, so routers have stopped sending traffic.
drainCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
if err := srv.Shutdown(drainCtx); err != nil {
log.Printf("drain deadline reached, closing remaining connections: %v", err)
}
closeDatabasePool()
flushTelemetry()
}Most frameworks have an equivalent: Spring Boot's server.shutdown=graceful, server.close() together with closeIdleConnections() in Node.js, Uvicorn and Gunicorn's own graceful timeouts. Check what yours does with keep-alive connections, because a server that waits for clients to close them can sit until SIGKILL.
Some things the built-in shutdown does not cover:
- WebSockets and other hijacked connections. Go's
Shutdownneither closes nor waits for them. Track them yourself, tell clients to reconnect, and close them before the deadline. - gRPC streams. Use the server's graceful stop, which sends
GOAWAYso clients open new streams on another pod, and fall back to a hard stop when the drain deadline passes. - Background work. Queue consumers should stop fetching, finish or abandon the current message and let the broker redeliver it. That is only safe if handlers are idempotent.
Make sure the signal arrives
The signal goes to process 1 in the container. If the image uses the shell form of CMD, process 1 is /bin/sh -c, which does not forward SIGTERM to the application. The application never hears about the shutdown and gets SIGKILL at the end of the grace period. Every deploy then takes the full grace period and drops whatever was in flight.
# Shell form: sh is PID 1 and swallows SIGTERM
# CMD /app/server --port 8080
# Exec form: the server is PID 1 and receives SIGTERM
CMD ["/app/server", "--port", "8080"]If a wrapper script is unavoidable, end it with exec so the application replaces the shell, or run a small init such as tini as process 1. Also note that the runtime sends the image's STOPSIGNAL instead of SIGTERM if one is set, which some base images do.
Step 3: size the grace period
The grace period has to cover the whole sequence with some margin:
| Phase | Example |
|---|---|
preStop sleep | 10 s |
| Application drain deadline | 25 s |
| Cleanup and margin | 10 s |
terminationGracePeriodSeconds | 45 s |
Set the application's drain deadline from the grace period, not independently of it, or the two drift apart as people edit one and forget the other. Passing the deadline in as an environment variable from the same Helm value or Kustomize patch keeps them together.
Do not set a long grace period just to be safe. Rolling updates, node drains and cluster upgrades all wait for it, and a pod that hangs on shutdown holds the whole operation for the full time. Long-running jobs that genuinely need minutes to finish belong in a design that checkpoints, not in a ten-minute grace period on a web service.
Step 4: line up the load balancer
When a cloud load balancer sends traffic straight to pod IPs, it has its own draining logic, and it has to agree with the pod's.
With the AWS Load Balancer Controller and target-type: ip, two settings matter:
- Deregistration delay. Once a target is deregistered it moves to
draining; the load balancer stops sending it new requests and waits up to the delay, 300 seconds by default, for in-flight ones. If the target closes the connection before then, the client gets a 5xx. Set the delay to slightly more than your longest normal request, and make sure the pod stays up for that long after deregistration. - Pod readiness gates. Labeling the namespace with
elbv2.k8s.aws/pod-readiness-gate-inject=enabledmakes new pods report ready only once their target is healthy in the target group. Without it, a rolling update can finish replacing old pods before any new pod is actually receiving traffic from the load balancer. The gate is injected when a pod is created, so label the namespace before the pods exist.
metadata:
annotations:
alb.ingress.kubernetes.io/target-type: ip
alb.ingress.kubernetes.io/target-group-attributes: deregistration_delay.timeout_seconds=30Other providers have equivalent connection-draining settings on their backend services. The rule is the same: the load balancer's drain window and the pod's remaining lifetime have to overlap.
Readiness during shutdown
Failing the readiness probe after SIGTERM is often recommended, including in the article on probes. Since Kubernetes 1.26, though, a terminating endpoint is marked not ready as soon as the pod gets its deletion timestamp, whatever the probe says. The pod's readiness is still reported as the endpoint's serving condition, and service proxies may route to endpoints that are serving and terminating when every endpoint of a Service is terminating, for example when a single-replica Deployment is replaced with maxSurge: 0. A pod that stays ready while it drains keeps that fallback available.
Failing readiness on shutdown still matters for anything that health-checks the pod itself instead of reading EndpointSlices, such as a load balancer health check aimed straight at the pod. Choose based on what routes to the service, and remember that it is not what removes the pod from a Service.
Sidecars
Mesh proxies and log shippers used to be a classic source of shutdown errors: the proxy exited first and the application's last responses had nowhere to go. Native sidecars, declared as init containers with restartPolicy: Always, fix the order. The kubelet sends them SIGTERM only after the last main container has exited, in reverse order of definition. If you used preStop hooks on a proxy to hold it open, switch to native sidecars and drop the hooks. Remember that the sidecars' own shutdown also comes out of the same grace period.
Test it under load
Run steady traffic through the real entry point while you restart the Deployment, and count the failures:
echo "GET https://checkout.staging.internal/healthz/deep" \
| vegeta attack -rate=50 -duration=180s > results.bin &
kubectl -n checkout rollout restart deployment/api
kubectl -n checkout rollout status deployment/api
wait
vegeta report results.binThe target is zero non-2xx responses over several restarts. If errors remain, vary one thing at a time: lengthen the preStop sleep to see if the problem is routing lag, check whether the container takes the full grace period to exit (a sign of the signal not arriving), and compare the load balancer's drain window with the pod's lifetime. Run the same test while draining a node, since that path also involves PodDisruptionBudgets.
Checklist
- Every serving workload has a
preStopsleep sized from measurement, using the built-in sleep action where the cluster supports it. - The application handles
SIGTERM: it stops accepting, drains with a deadline, closes idle and long-lived connections and exits cleanly. - The image runs the application as process 1, or behind an init that forwards signals.
terminationGracePeriodSecondscovers the sleep, the drain deadline and a margin, and both values come from the same configuration.- Load balancer deregistration delay and readiness gates match the pod's shutdown timing.
- A restart under load produces no errors, and that test runs again after changes to ingress, mesh or load balancer setup.