Lesson 8 of 19 · 18m
Graceful Shutdowns, Drains, and PodDisruptionBudgets
Termination and endpoint removal race each other — preStop, SIGTERM handling, and PDBs are how you make the race harmless.
Every deploy, your dashboard shows a small spike of 502s. The rollout is "rolling," the pods are "graceful," and yet requests still die mid-flight. The reason is a race most people never learn exists: when a pod is deleted, two things happen in parallel and nothing orders them.
What actually happens on pod delete
The API server stamps a deletionTimestamp on the pod, and two independent systems react:
- The kubelet on the node runs the termination sequence:
preStophook if defined →SIGTERMto PID 1 in each container → wait up toterminationGracePeriodSeconds(default 30) →SIGKILL. - The endpoints controller removes the pod's IP from the EndpointSlices, and kube-proxy (or your CNI) updates dataplane rules on every node.
Neither waits for the other. A pod can be dead to its process while still receiving traffic, because the old iptables rules haven't been reprogrammed yet — especially on clusters with thousands of endpoints where reprogramming takes seconds. The wrong mental model is "drain first, kill second." The real sequence is "both at once, race resolved by luck." It's why rolling updates drop in-flight requests even though maxUnavailable: 0 — the app got SIGTERM while a client was still being routed to it.
Making termination actually graceful
Three concrete fixes, layered:
spec:
terminationGracePeriodSeconds: 60
containers:
- name: api
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 10"]- Handle SIGTERM in the app. Stop accepting new connections, keep serving in-flight requests until they finish or the grace period ends. Every serious HTTP framework supports this — graceful shutdown is a feature, not a hope. A process that ignores SIGTERM and gets SIGKILLed at second 30 drops every request it was holding.
- Delay the SIGTERM slightly. A
preStopsleep of 5–15 seconds keeps the container alive while endpoint removal propagates. This is the standard fix for the 502-on-deploy spike — the pod stays up serving while the dataplane catches up. - Size the grace period.
terminationGracePeriodSecondsis a hard ceiling — preStop + drain + in-flight requests all share the same budget. If your longest request is 45s, 30s of grace truncates it.
One more edge the textbook skips: keep-alive connections. Clients that reuse connections (your ingress's upstream keep-alive, an HTTP/2 stream, a gRPC channel) don't re-resolve endpoints — they hold the connection to the terminating pod's IP open. Your "stop accepting new connections" handler needs to close listeners and eventually close idle keep-alives, or a client can ride a dead pod until SIGKILL. Watch it in the wild: a rollout "completes" while traffic still flows to the old pods for minutes.
PodDisruptionBudgets: the drain-side contract
There are two kinds of disruption. Involuntary: node death, kernel panic, cloud instance evaporates. Voluntary: kubectl drain, cluster upgrades, autoscaler scale-down, someone deleting pods. PDBs only constrain the voluntary kind — they cannot stop hardware from failing.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: api-pdb
spec:
minAvailable: 2
selector:
matchLabels:
app: apikubectl drain works by cordoning the node, then deleting each pod through the Eviction subresource (policy/v1 Eviction) — not a plain delete. The Eviction API consults PDBs: if evicting this pod would drop api below minAvailable, the eviction is rejected and drain retries with backoff. A drain that hangs forever is almost always a PDB that can never be satisfied — minAvailable equal to the replica count means no pod may ever leave.
maxUnavailable: 1 is usually better ergonomics than minAvailable — it survives scale-up without edits. Since Kubernetes 1.27, unhealthyPodEvictionPolicy: AlwaysAllow lets drain proceed through pods that are already unhealthy (they're not providing availability anyway).
Practice
Handle SIGTERM, give preStop a few seconds of runway, set one PDB per service, and prove it: kubectl drain <node> --ignore-daemonsets --delete-emptydir-data on a staging node, watch evictions respect the PDB, then kubectl uncordon. Fifteen minutes of rehearsal buys you the confidence that the next node failure — voluntary or not — is a non-event.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
What is Platform as a Service? The Sweet Spot Between "Too Easy" and "Too Much Work"
Platform as a Service sits between raw servers and fully managed software. You push code, the platform runs it. No Nginx config, no OS patches, no 3 AM server alerts. Here is what PaaS actually gives you, what it costs you in control, and how to decide if it is the right layer for your application.
The World now is Serverless and Container based
A new report from Datadog reveals that serverless computing could be entering the mainstream. This has already been the case in my world for the past few years. Results show that more than half of all organizations are using serverless on one of the three major public cloud providers: Amazon,
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.