Skip to content

Lesson 7 of 9 · 24m

Process Model, Signals, and Deployment Discipline

How Node services should start, stop, restart, and scale — including cluster tradeoffs, graceful shutdown, health checks, and the realities of containers.

Most runtime incidents are not exotic. A deploy closes sockets mid-request. A health check passes while the event loop is saturated. A container orchestrator sends SIGTERM, nobody listens, and thirty seconds later the process is SIGKILLed with in-flight work still open. Runtime competence means treating process lifecycle as part of the application.

One process is one failure domain and one scheduler

A single Node process can use multiple threads, but your JavaScript execution is still concentrated in one main loop. Scaling vertically inside one process has limits; scaling horizontally means multiple independent processes behind a load balancer or orchestrator.

Node’s built-in cluster module forks workers that share a listening socket. It can be useful on bare metal, but in containers it often duplicates what the platform already does. Prefer multiple container replicas unless you have measured a reason to cluster inside the container. Every extra layer of process management is another place signals, logs, and health state can get lost.

Graceful shutdown is a state machine

let closing = false;

function shutdown(signal) {
  if (closing) return;
  closing = true;
  console.log(`received ${signal}, closing`);
  server.close(async err => {
    if (err) process.exitCode = 1;
    await db.close();
    process.exit();
  });

  setTimeout(() => {
    console.error("forced shutdown after grace period");
    process.exit(1);
  }, 10_000).unref();
}

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

server.close() stops accepting new connections and waits for existing ones. It does not magically finish WebSockets, long-polling, SSE, or keep-alive idle sockets. Track those explicitly or close them after a bounded grace period. Also stop accepting queue jobs before draining current work.

The forced shutdown timer is not optional. Orchestrators have deadlines, and a stuck connection cannot be allowed to make deploys hang forever.

Health checks must answer different questions

Liveness means “should the orchestrator restart this process?” Readiness means “should traffic be sent here right now?” They are not synonyms.

app.get("/health/live", (req, res) => res.json({ ok: true }));
app.get("/health/ready", async (req, res) => {
  if (closing) return res.status(503).json({ ready: false, reason: "closing" });
  await db.ping();
  res.json({ ready: true });
});

Do not put expensive dependency checks into liveness. A downstream database outage can cause every pod to be restarted, making recovery worse. A process that is alive but unable to serve should fail readiness, not liveness.

Containers do not remove operating-system truth

Node versions before modern improvements were notoriously unaware of cgroup CPU and memory constraints. Current releases are better, but still verify actual values inside the container. CPU quotas influence parallelism; memory limits determine when the kernel OOM killer chooses you.

node -p "require('node:os').availableParallelism()"
node -e "console.log(process.memoryUsage())"

Set heap limits intentionally when necessary, but understand that native memory, buffers, workers, and dependency allocations are outside the V8 heap. --max-old-space-size is not a total-process memory budget.

Logs and crashes are lifecycle signals

Write logs to stdout/stderr as structured events. Do not hide fatal errors behind empty catches. For uncaught exceptions, log context and exit promptly; continuing after corruption of unknown state is usually worse. unhandledRejection deserves the same seriousness, especially since modern Node increasingly treats it as fatal by default.

Field notes

  • PID 1 behavior matters in containers. Use an init or ensure your process handles signals and reaps children correctly.
  • Test deploys under load. Graceful shutdown that only works when idle is untested code.
  • Long-lived connections need explicit deadlines and heartbeat design; otherwise deploys become connection roulette.
  • Horizontal scaling only works when local in-memory state is not secretly load-bearing.
  • Expose a version/build identifier endpoint or log line. Debugging “which artifact is running?” wastes incident time.

Was this lesson helpful?

Sign in to rate