Intermediate LevelExpress JS
How do you implement graceful shutdown in Express using http-terminator?
❓ Interview Prompt: Explain graceful server shutdown, handling SIGTERM/SIGINT signals, draining active HTTP connections, and http-terminator.
When Kubernetes or Docker terminates a container (sending a 'SIGTERM' signal), killing the Express process immediately drops all active HTTP requests in flight, causing 502 errors for clients!
Graceful Shutdown Architecture:
1
Trap 'SIGTERM' and 'SIGINT' process signals.
2
Stop accepting new incoming HTTP connections.
3
Use 'http-terminator' to drain and complete all active in-flight requests gracefully before exiting the Node.js process.
Code Implementation Example
javascript
import express from 'express';
import { createHttpTerminator } from 'http-terminator';
const app = express();
const server = app.listen(3000);
const httpTerminator = createHttpTerminator({ server });
async function gracefulShutdown(signal) {
console.log(`Received ${signal}. Draining connections...`);
await httpTerminator.terminate();
console.log('HTTP server closed cleanly. Exiting process.');
process.exit(0);
}
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));💡Implementing graceful Express server shutdown using http-terminator.
🎯 Interview Key Takeaway
Trap SIGTERM signals and use http-terminator to drain active in-flight HTTP requests cleanly before process exit.
#Graceful Shutdown#SIGTERM#http-terminator#Intermediate
Back to all Express JS Questions→