Graceful Shutdown and Process Management
Graceful Shutdown & Process Lifecycle
In distributed, containerized environments (Kubernetes, Docker Swarm), instances are ephemeral. They are scaled up and terminated dynamically based on traffic parameters. A process abruptly exiting mid-flight leads to data corruption and dropped connections.
The SIGTERM Protocol
When orchestrators terminate a pod, they send a polite SIGTERM signal. A production-ready Node.js app must intercept this signal to execute a Graceful Shutdown sequence.
- Stop Acceptance: Immediately command the HTTP server to refuse new incoming connections.
- Drain Requests: Allow existing, in-flight HTTP requests time to finalize and respond.
- Teardown Connections: Close database connection pools and flush log streams.
- Exit: Finally invoke
process.exit(0)to signal a clean termination.