Node.js theorytheory 0/50 · 0%
Reliability · medium

35. Graceful shutdown

Finishing in-flight work before the process exits.

On deployment or restart, a process typically receives `SIGTERM`. A graceful shutdown stops accepting new connections, waits for in-flight requests to finish, closes database pools and sockets, then exits — instead of dying mid-request and corrupting state or dropping responses.

js
const server = app.listen(3000);

process.on("SIGTERM", async () => {
  console.log("SIGTERM received, shutting down");
  server.close(() => console.log("http server closed"));
  await pool.end(); // close db connections
  process.exit(0);
});

Container orchestrators (Kubernetes, ECS) send `SIGTERM` and then wait a grace period before sending a hard `SIGKILL` — if your shutdown handler takes longer than that window, work is killed anyway, so it should be bounded and fast.

Check your understanding

  1. 1. What signal do orchestrators typically send before terminating a process?

  2. 2. What should a graceful shutdown handler do?

  3. 3. Why must a shutdown handler be bounded in time?