← Back to Node.js, page 3

nodejs-0042 · Hard senior

How do you shut down a Node.js HTTP server gracefully on SIGTERM?

On SIGTERM, stop accepting new connections with server.close(), let in-flight requests finish, close idle keep-alive connections, close other resources (database, queues), and exit. Add a forced exit timer in case something hangs. Orchestrators send SIGTERM first and SIGKILL after a grace period.

Full answer

When you deploy or scale down, the platform sends SIGTERM to the process. If the process dies at once, requests in progress fail. A graceful shutdown avoids lost work.

Sequence:

  1. Handle SIGTERM (and SIGINT for Ctrl+C): process.once('SIGTERM', shutdown).
  2. Mark the app as not ready. A health check endpoint should now fail, so the load balancer stops sending traffic.
  3. server.close(): stops accepting new connections. The callback runs when all connections have ended. Since Node 19, server.close() also closes idle keep-alive connections. server.closeIdleConnections() does that explicitly, and server.closeAllConnections() cuts everything, as a last resort.
  4. Wait for in-flight requests to complete.
  5. Close the rest: database pools, message queue consumers, timers. Flush logs.
  6. Exit with code 0. Set a deadline (for example 10 s, shorter than the platform grace period) after which you call process.exit(1). Call .unref() on that timer so it does not keep the process alive by itself.

Keep-alive connections are the usual reason shutdown hangs: an idle connection never ends by itself, so close() waits for the keepAliveTimeout.

Long-lived connections (WebSockets, server-sent events) need an explicit message to clients and a close. Do not forget background jobs: finish or hand back the job in progress.

javascript
const http = require('node:http');

const server = http.createServer((req, res) => {
  res.on('finish', () => console.log('3. in-flight request finished normally'));
  setTimeout(() => res.end('order saved'), 300); // a slow request
});

let shuttingDown = false;
function shutdown(signal) {
  if (shuttingDown) return;
  shuttingDown = true;
  console.log('2. received', signal, '- no new connections, finishing current requests');

  const deadline = setTimeout(() => {
    console.log('deadline hit, forcing exit');
    process.exit(1);
  }, 5000);
  deadline.unref(); // the timer alone must not keep the process alive

  server.close(() => {
    console.log('4. server closed, releasing other resources (database, queues)');
    // the process now exits by itself because nothing is left to do
  });
  server.closeIdleConnections();
}
process.once('SIGTERM', shutdown);

server.listen(0, '127.0.0.1', async () => {
  const url = 'http://127.0.0.1:' + server.address().port;
  const pending = fetch(url).then((r) => r.text());
  setTimeout(() => process.kill(process.pid, 'SIGTERM'), 50); // the platform sends the signal
  console.log('1. request started');
  await pending;
});

The script sends itself SIGTERM while a request is in progress. The request still completes, and the process exits without a forced kill. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. request started 2. received SIGTERM - no new connections, finishing current requests 3. in-flight request finished normally 4. server closed, releasing other resources (database, queues)

Key points

  • Handle SIGTERM, stop accepting new work, finish current work, exit.
  • server.close waits for connections to end. Close idle ones.
  • Fail the health check first so traffic stops.
  • Use a deadline timer that is unref'd.
  • Close databases and queues after the HTTP server.

Common mistakes

  • Calling process.exit() inside the SIGTERM handler.
  • Forgetting idle keep-alive connections, so close() waits for many seconds.
  • Closing the database before the in-flight requests have finished.
  • Setting a shutdown deadline longer than the platform grace period.

Follow-ups

  • How does Kubernetes use readiness probes during shutdown?
  • How would you close WebSocket connections?
  • What is the difference between SIGTERM, SIGINT and SIGKILL?

Tips

  • Number the steps. Interviewers like ordered answers.
  • Mention the health check change, since it is often forgotten.
  • Say SIGKILL cannot be handled.