Graceful Shutdown
A clean termination sequence triggered by SIGTERM that stops accepting new traffic, drains all in-flight requests, closes database connections cleanly, and exits without dropping user transactions
Table of Contents
Structure Diagram
What is Graceful Shutdown?
A clean termination sequence triggered by SIGTERM that stops accepting new traffic, drains all in-flight requests, closes database connections cleanly, and exits without dropping user transactions. It is a core concept in Observability & Reliability within Cloud / DevOps.
Core Principles
Graceful Shutdown ensures that when a server or container is terminated during a deployment, scale-in, or node drain, in-flight user requests and database transactions finish cleanly instead of being severed mid-air with 502/504 errors.
Upon receiving SIGTERM, the process stops accepting new connections, drains active requests to completion, flushes telemetry buffers and closes database/queue pools cleanly, and exits with status 0 before the orchestrator sends a hard SIGKILL.
Practical Takeaways
- Add a Kubernetes
preStopsleep hook: In Kubernetes, podSIGTERMdelivery and Endpoint/ALB removal happen concurrently. Adding apreStopsleep of 5–10 seconds gives load balancers time to stop routing new traffic before the server closes its listening socket. - Size
terminationGracePeriodSecondsaccurately: Set the grace period longer thanpreStopduration plus your longest legitimate request or job timeout soSIGKILLnever interrupts active work. - Avoid the PID 1 shell trap: Use JSON exec form (
CMD ["node", "server.js"]) in Dockerfiles instead of shell form soSIGTERMreaches your application process directly.
Notable Examples
- Zero-Error Rolling Deployments: Eliminates transient 502 Bad Gateway spikes during frequent production rollouts.
- AWS ALB Deregistration Delay: Holds open existing connections while routing all new requests away from draining targets.
- Kafka & Queue Workers: Finishes processing and committing the current batch before leaving the consumer group.