Senior LevelNode JS
How do you implement Production Graceful Shutdown in Node.js applications for Kubernetes SIGTERM?
❓ Interview Prompt: Explain Kubernetes Pod termination, SIGTERM signal handling, stopping new connections (`server.close()`), draining active requests, and DB pool cleanup.
When Kubernetes terminates a Pod, it sends a 'SIGTERM' signal before forcing 'SIGKILL' after a grace period (default 30s):
Graceful Shutdown Sequence:
1
Intercept 'process.on('SIGTERM')'.
2
Fail readiness health check probes immediately.
3
Call 'server.close()' to stop accepting new TCP connections while draining active in-flight HTTP requests.
4
Close database connection pools cleanly ('mongoose.disconnect()').
5
Exit 'process.exit(0)'.
Code Implementation Example
javascript
import http from 'node:http';
import mongoose from 'mongoose';
const server = http.createServer((req, res) => res.end('OK'));
server.listen(3000);
async function gracefulShutdown(signal) {
console.log('Received ${signal}. Starting graceful shutdown...');
// Stop accepting new connections
server.close(async () => {
console.log('HTTP server closed. Closing DB connection pool...');
await mongoose.disconnect();
console.log('Shutdown complete. Exiting.');
process.exit(0);
});
// Force exit if connections fail to drain within 10 seconds
setTimeout(() => {
console.error('Forced shutdown timeout exceeded!');
process.exit(1);
}, 10000);
}
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));💡Implementing production graceful shutdown handling SIGTERM in Node.js.
🎯 Interview Key Takeaway
Implement graceful shutdown intercepting SIGTERM to drain active connections before container termination.
#Graceful Shutdown#SIGTERM#Kubernetes#Production#Senior
Back to all Node JS Questions→