Node.js Developer interview question · Most asked

How do you implement graceful shutdown in a Node.js server?

Summary

On SIGTERM/SIGINT, stop accepting new connections (server.close()), let in-flight requests finish (with a timeout), close keep-alive connections, stop consumers, close DB pools and other resources, flush logs, then exit.

Longer Answer

In Kubernetes, fail the readiness probe first so traffic stops arriving, then drain. server.closeIdleConnections() and closeAllConnections() (Node 18.2+) help with keep-alive sockets. Always set a hard timeout so a stuck request doesn't block shutdown forever.

Code Example

function shutdown(signal) {
  logger.info({ signal }, "shutting down");
  server.close(async () => {
    await db.end();
    await queue.close();
    process.exit(0);
  });
  server.closeIdleConnections();
  setTimeout(() => process.exit(1), 10_000).unref();
}

process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);

Key Points

  • Handle SIGTERM/SIGINT
  • server.close() + drain
  • Close DB pools and consumers
  • Hard timeout fallback

More most-asked Node.js Developer questions

← All Node.js Developer questions