Bird
Raised Fist0
Node.jsframework~10 mins

Graceful shutdown handling in Node.js - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Graceful shutdown handling
Start Server
↓
Server Running
↓
Receive Shutdown Signal
↓
Stop Accepting New Requests
↓
Finish Ongoing Requests
↓
Close Server & Cleanup
↓
Exit Process
The server starts and runs normally until it receives a shutdown signal, then it stops new requests, finishes ongoing ones, cleans up, and exits.
Execution Sample
Node.js
const http = require('http');
const app = (req, res) => {
  res.end('Hello World');
};
const server = http.createServer(app);
server.listen(3000);

process.on('SIGINT', () => {
  server.close(() => process.exit(0));
});
This code starts a server and listens for a shutdown signal to close the server gracefully before exiting.
Execution Table
StepEventServer StateAction TakenProcess State
1Start serverListening on port 3000Server starts accepting requestsRunning
2Server runningListening on port 3000Handles incoming requests normallyRunning
3Receive SIGINT (Ctrl+C)Listening on port 3000Stop accepting new requestsRunning
4Finish ongoing requestsClosing serverWaits for all requests to finishRunning
5Server closedClosedCleanup doneReady to exit
6Process exitN/AProcess exits with code 0Exited
💡 Process exits after server closes and cleanup completes
Variable Tracker
VariableStartAfter SIGINTAfter Close CallbackFinal
server.listeningtruefalsefalsefalse
process.runningtruetruetruefalse
Key Moments - 2 Insights
Why does the server stop accepting new requests after receiving SIGINT?
Because in step 3 of the execution_table, the server.close() method is called, which stops new connections but allows ongoing requests to finish.
What happens if we call process.exit() immediately without waiting for server.close()?
The server might terminate abruptly, dropping ongoing requests. The execution_table shows the importance of waiting for the close callback before exiting (step 4 and 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the server state right after receiving SIGINT?
AClosing server
BListening on port 3000
CClosed
DNot started
💡 Hint
Check row 3 under 'Server State' in the execution_table
At which step does the process exit in the execution_table?
AStep 6
BStep 4
CStep 5
DStep 3
💡 Hint
Look at the 'Process State' column for the exit event
If the server never finishes ongoing requests, what will happen to the process exit?
AProcess exits immediately
BProcess exits with error
CProcess waits indefinitely
DProcess restarts automatically
💡 Hint
Refer to step 4 where server waits for ongoing requests before closing
Concept Snapshot
Graceful shutdown in Node.js:
- Listen for shutdown signals (e.g., SIGINT)
- Call server.close() to stop new requests
- Wait for ongoing requests to finish
- Cleanup resources
- Exit process after server closes
This prevents dropping active connections.
Full Transcript
This visual execution shows how a Node.js server handles graceful shutdown. The server starts and listens for requests. When it receives a shutdown signal like SIGINT, it stops accepting new requests but keeps handling ongoing ones. Once all requests finish, the server closes and cleans up resources. Finally, the process exits cleanly. This prevents abrupt termination and dropped connections.

Practice

(1/5)
1. What is the main purpose of graceful shutdown in a Node.js application?
easy
A. To stop the app safely without losing data or leaving tasks unfinished
B. To restart the app automatically after a crash
C. To speed up the app startup time
D. To increase the app's memory usage

Solution

  1. Step 1: Understand graceful shutdown concept

    Graceful shutdown means stopping the app carefully so it finishes ongoing work and saves data.
  2. 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.
  3. Final Answer:

    To stop the app safely without losing data or leaving tasks unfinished -> Option A
  4. Quick Check:

    Graceful shutdown = safe stop without data loss [OK]
Hint: Graceful shutdown means stopping safely, not restarting or speeding up [OK]
Common Mistakes:
  • Confusing graceful shutdown with app restart
  • Thinking it improves startup speed
  • Assuming it increases memory usage
2. Which Node.js code snippet correctly listens for the SIGINT signal to start graceful shutdown?
easy
A. process.on('SIGTERM', () => { console.log('Shutting down'); });
B. process.listen('SIGINT', () => { console.log('Shutting down'); });
C. process.on('SIGINT', () => { console.log('Shutting down'); process.exit(); });
D. process.signal('SIGINT', () => { console.log('Shutting down'); });

Solution

  1. Step 1: Recall correct event listener syntax

    Node.js uses process.on('signal', callback) to listen for signals like SIGINT.
  2. 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.
  3. Final Answer:

    process.on('SIGINT', () => { console.log('Shutting down'); process.exit(); }); -> Option C
  4. Quick Check:

    Use process.on('SIGINT', callback) for SIGINT [OK]
Hint: Use process.on('SIGINT', callback) to handle Ctrl+C [OK]
Common Mistakes:
  • Using process.listen instead of process.on
  • Using process.signal which does not exist
  • Confusing SIGINT with SIGTERM
3. Consider this code snippet:
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?
medium
A. The server immediately exits without closing connections
B. The server stops accepting new connections, logs 'Server closed', then exits
C. The server ignores Ctrl+C and keeps running
D. The server crashes with an error

Solution

  1. 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.
  2. Step 2: Analyze server.close callback

    When server.close finishes, it logs 'Server closed' and calls process.exit(0) to exit cleanly.
  3. Final Answer:

    The server stops accepting new connections, logs 'Server closed', then exits -> Option B
  4. Quick Check:

    Ctrl+C triggers server.close then exit [OK]
Hint: SIGINT triggers server.close callback before exit [OK]
Common Mistakes:
  • Thinking server exits immediately without closing
  • Assuming Ctrl+C is ignored
  • Expecting a crash error
4. This code aims to handle graceful shutdown but has a bug:
process.on('SIGINT', () => {
  server.close();
  console.log('Server closed');
  process.exit(0);
});
What is the problem?
medium
A. process.exit(0) runs before server.close finishes, causing abrupt exit
B. SIGINT event is not supported by process
C. console.log should be before server.close
D. server.close() does not exist on http server

Solution

  1. Step 1: Understand asynchronous server.close

    server.close() is asynchronous and takes a callback to run after closing.
  2. 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.
  3. Final Answer:

    process.exit(0) runs before server.close finishes, causing abrupt exit -> Option A
  4. Quick Check:

    Wait for server.close callback before exiting [OK]
Hint: Always exit inside server.close callback to wait for close [OK]
Common Mistakes:
  • Calling process.exit too early
  • Thinking SIGINT is unsupported
  • Misunderstanding server.close existence
5. You want to handle both SIGINT and SIGTERM signals to gracefully shutdown your Node.js app. Which code correctly ensures the server closes once and exits safely without duplicate calls?
hard
A. process.on('SIGINT', () => server.close(() => process.exit(0))); process.on('SIGTERM', () => server.close(() => process.exit(0)));
B. process.on('SIGINT', () => { console.log('Shutting down'); }); process.on('SIGTERM', () => { console.log('Shutting down'); });
C. process.on('SIGINT', () => { server.close(); process.exit(0); }); process.on('SIGTERM', () => { server.close(); process.exit(0); });
D. 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); }); }

Solution

  1. Step 1: Understand multiple signal handling

    Both SIGINT and SIGTERM can trigger shutdown, so we must avoid running shutdown twice.
  2. 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.
  3. 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.
  4. Final Answer:

    Code with a flag to prevent duplicate shutdown and safely close server once -> Option D
  5. Quick Check:

    Use a flag to avoid duplicate shutdown calls [OK]
Hint: Use a flag to run shutdown logic only once for multiple signals [OK]
Common Mistakes:
  • Calling server.close multiple times causing errors
  • Exiting process before server closes
  • Not handling both signals properly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard