InterviewHubPRO
Section Overview
Q19

Question 19 of 60

Part 2: Runtime Internals, Libuv & The Event Loop (6 - 20)

32%
Node.js & Libuv•Part 2: Runtime Internals, Libuv & The Event Loop (6 - 20)

Graceful Shutdown implementation.

In Simple Words: Listen for SIGTERM and SIGINT signals, stop accepting new connections, finish in-flight requests, close DB pools, and exit cleanly.

javascript
function setupGracefulShutdown(server, dbPool) {
  const shutdown = async (signal) => {
    console.log(`Received ${signal}. Shutting down...`);
    server.close(async () => {
      console.log('HTTP server closed.');
      await dbPool.end();
      process.exit(0);
    });

    // Force exit after 10s timeout:
    setTimeout(() => {
      console.error('Forced shutdown due to timeout.');
      process.exit(1);
    }, 10000).unref();
  };

  process.on('SIGTERM', () => shutdown('SIGTERM'));
  process.on('SIGINT', () => shutdown('SIGINT'));
}