Senior LevelSystem Design & Architecture
How do you implement Graceful Shutdown handlers in containerized microservices?
β Interview Prompt: Explain Graceful Shutdown, Linux `SIGTERM` vs `SIGKILL` signals, draining HTTP connection pools, and Kubernetes `terminationGracePeriodSeconds`.
When Kubernetes terminates a pod during deployment or auto-scaling, it sends a 'SIGTERM' signal before forcefully killing the container with 'SIGKILL' 30 seconds later:
Graceful Shutdown Checklist:
1
Intercept 'SIGTERM' signal in application code.
2
Stop accepting new incoming HTTP requests (return 503 or close listener).
3
Allow active in-flight HTTP requests and background queue jobs to complete within a timeout window.
4
Close database connection pools and Redis sockets cleanly before exiting.
Code Implementation Example
typescript
process.on('SIGTERM', async () => {
logger.info('SIGTERM received. Initiating Graceful Shutdown...');
// 1. Stop accepting new HTTP connections
server.close(async () => {
// 2. Drain database connection pools
await dbPool.end();
logger.info('Cleanup complete. Exiting process.');
process.exit(0);
});
});π‘Implementing a SIGTERM Graceful Shutdown handler in Node.js.
π― Interview Key Takeaway
Implement SIGTERM handlers to drain active HTTP requests and close database connection pools during container shutdowns.
#System Design#Graceful Shutdown#SIGTERM#Kubernetes#Senior
Back to all System Design & Architecture Questionsβ