0 day streak
javascript / expert
Snippet

Graceful Shutdown Orchestration

A professional Node.js application must handle termination signals like `SIGTERM`. `server.close()` stops the server from accepting new connections but waits for existing ones to finish. A secondary timeout ensures the process eventually terminates even if some connections are stuck.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const http = require('http');
const server = http.createServer((req, res) => res.end('OK'));
process.on('SIGTERM', () => {
console.log('SIGTERM received. Closing server...');
server.close(() => {
console.log('Server closed. Exiting process.');
process.exit(0);
});
// Force exit after timeout if connections hang
setTimeout(() => {
console.error('Forcing exit after timeout');
process.exit(1);
}, 10000);
});
nodejs
Breakdown
1
server.close(() => { ... })
Wait for all active keep-alive connections to close before exiting.
2
setTimeout(..., 10000)
Safety hatch to prevent the process from hanging indefinitely.