Middle+
Tell me about graceful shutdown and where it is applied?
sobes.tech AI
Answer from AI
Graceful shutdown is the process of properly terminating an application, allowing it to complete current operations, free resources, and save state before stopping.
Application of graceful shutdown:
- Deploying new versions of the application: Allows a smooth transition from an old version to a new one without data loss or user session interruption.
- Scheduled reboots or maintenance: Ensures all open connections are closed and tasks are completed before the service stops.
- Responding to failures or scaling: Services can be properly stopped when load decreases or issues arise.
Example implementation in Node.js:
// process.js
const http = require('http');
const server = http.createServer((req, res) => {
setTimeout(() => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
}, 2000); // Simulate a long operation
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
// SIGTERM signal handler for graceful shutdown
process.on('SIGTERM', () => {
console.log('Received SIGTERM signal. Closing server...');
server.close(() => {
console.log('Server closed. Exiting process.');
process.exit(0);
});
// Force shutdown after some time if closing takes too long
setTimeout(() => {
console.error('Forcefully shutting down...');
process.exit(1);
}, 5000); // 5 seconds to shutdown
});
In this example, upon receiving the SIGTERM signal, the server stops accepting new connections but allows existing ones to finish. If shutdown takes too long, it forcibly terminates the process.