Graceful shutdown lets your Node.js app close smoothly. It finishes tasks and frees resources before stopping.
Graceful shutdown handling in Node.js
process.on('SIGINT', () => { // cleanup code here server.close(() => { console.log('Server closed'); process.exit(0); }); });
process.on listens for system signals like SIGINT (Ctrl+C).
server.close() stops accepting new connections and waits for existing ones to finish.
SIGTERM signal, common in container or cloud environments.process.on('SIGTERM', () => { console.log('SIGTERM received, shutting down'); server.close(() => process.exit(0)); });
process.on('SIGINT', async () => { await cleanupDatabase(); server.close(() => process.exit(0)); });
This Node.js server listens on port 3000. When you press Ctrl+C, it logs a message, stops accepting new requests, and exits cleanly.
import http from 'node:http'; const server = http.createServer((req, res) => { res.end('Hello, world!'); }); server.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); process.on('SIGINT', () => { console.log('\nSIGINT received: closing server'); server.close(() => { console.log('Server closed gracefully'); process.exit(0); }); });
Always close resources like database connections inside the shutdown handler.
If you don't call process.exit(), the app may hang waiting for tasks.
Test shutdown by pressing Ctrl+C in the terminal where your app runs.
Graceful shutdown helps your app stop safely without losing data.
Use process.on to listen for stop signals like SIGINT or SIGTERM.
Close servers and cleanup resources before exiting.
Practice
Solution
Step 1: Understand graceful shutdown concept
Graceful shutdown means stopping the app carefully so it finishes ongoing work and saves data.Step 2: Identify the purpose in options
Only To stop the app safely without losing data or leaving tasks unfinished describes stopping safely without losing data or leaving tasks unfinished.Final Answer:
To stop the app safely without losing data or leaving tasks unfinished -> Option AQuick Check:
Graceful shutdown = safe stop without data loss [OK]
- Confusing graceful shutdown with app restart
- Thinking it improves startup speed
- Assuming it increases memory usage
Solution
Step 1: Recall correct event listener syntax
Node.js uses process.on('signal', callback) to listen for signals like SIGINT.Step 2: Check options for correct syntax and signal
process.on('SIGINT', () => { console.log('Shutting down'); process.exit(); }); uses process.on with 'SIGINT' and a callback, which is correct. process.on('SIGTERM', () => { console.log('Shutting down'); }); uses SIGTERM, which is valid but not SIGINT as asked. Options B and D use invalid methods.Final Answer:
process.on('SIGINT', () => { console.log('Shutting down'); process.exit(); }); -> Option CQuick Check:
Use process.on('SIGINT', callback) for SIGINT [OK]
- Using process.listen instead of process.on
- Using process.signal which does not exist
- Confusing SIGINT with SIGTERM
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello');
});
process.on('SIGINT', () => {
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});
server.listen(3000);
What happens when you press Ctrl+C in the terminal?Solution
Step 1: Understand SIGINT handler
The code listens for SIGINT (Ctrl+C), then calls server.close to stop new connections and waits for existing ones to finish.Step 2: Analyze server.close callback
When server.close finishes, it logs 'Server closed' and calls process.exit(0) to exit cleanly.Final Answer:
The server stops accepting new connections, logs 'Server closed', then exits -> Option BQuick Check:
Ctrl+C triggers server.close then exit [OK]
- Thinking server exits immediately without closing
- Assuming Ctrl+C is ignored
- Expecting a crash error
process.on('SIGINT', () => {
server.close();
console.log('Server closed');
process.exit(0);
});
What is the problem?Solution
Step 1: Understand asynchronous server.close
server.close() is asynchronous and takes a callback to run after closing.Step 2: Identify order of commands
Here, process.exit(0) runs immediately after server.close() call, not waiting for close to finish, causing abrupt exit.Final Answer:
process.exit(0) runs before server.close finishes, causing abrupt exit -> Option AQuick Check:
Wait for server.close callback before exiting [OK]
- Calling process.exit too early
- Thinking SIGINT is unsupported
- Misunderstanding server.close existence
Solution
Step 1: Understand multiple signal handling
Both SIGINT and SIGTERM can trigger shutdown, so we must avoid running shutdown twice.Step 2: Check for duplicate shutdown prevention
let isShuttingDown = false; process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown); function shutdown() { if (isShuttingDown) return; isShuttingDown = true; server.close(() => { console.log('Closed'); process.exit(0); }); } uses a flag isShuttingDown to run shutdown only once, preventing duplicate server.close and exit calls.Step 3: Analyze other options
process.on('SIGINT', () => server.close(() => process.exit(0))); process.on('SIGTERM', () => server.close(() => process.exit(0))); calls server.close twice if both signals arrive. process.on('SIGINT', () => { server.close(); process.exit(0); }); process.on('SIGTERM', () => { server.close(); process.exit(0); }); calls process.exit immediately without waiting. process.on('SIGINT', () => { console.log('Shutting down'); }); process.on('SIGTERM', () => { console.log('Shutting down'); }); only logs without closing.Final Answer:
Code with a flag to prevent duplicate shutdown and safely close server once -> Option DQuick Check:
Use a flag to avoid duplicate shutdown calls [OK]
- Calling server.close multiple times causing errors
- Exiting process before server closes
- Not handling both signals properly
Ready to prove it?
Pass the test and this pattern moves unknown
