Stage 3 · Build
Production-Ready Services
Graceful Shutdown
Handle SIGTERM, stop accepting traffic, drain requests, close pools, and respect Kubernetes deadlines.
Why Graceful Shutdown
When Kubernetes terminates a pod, it sends SIGTERM and waits 30 seconds before SIGKILL. Without graceful shutdown, in-flight requests are dropped, database connections are leaked, and users see errors.
Signal Handling
HTTP Server Shutdown
Draining Connections
Cleanup Resources
Kubernetes Deadlines
Kubernetes gives you 30 seconds (default) between SIGTERM and SIGKILL. Your shutdown timeout must be less than this. A common pattern is 25 seconds for shutdown, leaving 5 seconds of buffer.
apiVersion: v1
kind: Pod
spec:
terminationGracePeriodSeconds: 35
containers:
- name: api
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 5"]
readinessProbe:
httpGet:
path: /readyz
port: 8080
initialDelaySeconds: 5
periodSeconds: 5preStop hook sleeps 5 seconds to let the load balancer remove the pod from rotation before the application starts shutting down. This prevents requests from being routed to a shutting-down pod.
If your shutdown timeout is 30 seconds and Kubernetes terminationGracePeriodSeconds is 30 seconds, Kubernetes will SIGKILL your process before it finishes shutting down. Set your timeout to 25 seconds.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.