Skip to content
jshacks.dev
Node.js

How to Implement Health Checks in a Node.js Service

Add liveness, readiness and startup endpoints to a Node.js 26 service with node:http, time-box dependency checks and wire them to Kubernetes and Docker probes.

7 min read
Summarize in AI
Flat illustration of a heartbeat line above application health tiles, with the Prometheus, Sentry and Grafana logos.

A health check that always returns 200 OK is worse than none, because it tells the orchestrator everything is fine while the database pool is exhausted. A health check that calls the database on every probe is also a trap: a slow database makes every instance look dead at once, and the orchestrator restarts the whole fleet into the outage. The useful design splits the question in two. Liveness asks whether the process should be killed. Readiness asks whether it should receive traffic right now. This post builds both endpoints with node:http on Node.js 26, adds time-boxed dependency checks, handles shutdown correctly and shows the probe configuration for Kubernetes and Docker.

Liveness and readiness are different questions

The two probes have different consequences, so they need different logic.

ProbeQuestionFailure meansShould check
LivenessIs the process stuck?Restart the containerOnly that the event loop answers
ReadinessCan it serve a request now?Stop sending trafficDependencies the request path needs
StartupHas it finished booting?Keep waiting, then restartThat initialization completed

The rule that prevents most outages: liveness must never depend on an external system. If the database is down and liveness fails, Kubernetes restarts every pod, and a database outage becomes a total outage with a restart storm on top. Readiness may depend on the database, because removing a pod from the load balancer is cheap and reversible.

A minimal server with both endpoints

Start with the shape, keeping the handlers tiny.

health-basic.jsJavaScript
import { createServer } from "node:http";

let ready = false;

const server = createServer((req, res) => {
  if (req.url === "/livez") {
    res.writeHead(200, { "content-type": "text/plain" }).end("ok");
    return;
  }
  if (req.url === "/readyz") {
    const status = ready ? 200 : 503;
    res.writeHead(status, { "content-type": "text/plain" }).end(ready ? "ready" : "starting");
    return;
  }
  res.writeHead(404).end();
});

server.listen(3000, () => {
  ready = true;
  console.log("listening on 3000");
});
Shell
curl -i localhost:3000/readyz
Text
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Fri, 20 Nov 2026 10:00:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Content-Length: 5

ready

The Date header will differ. The liveness endpoint is intentionally trivial: if the event loop is blocked by a runaway loop, the handler never runs, the probe times out and the orchestrator restarts the process. That is exactly the failure liveness exists to detect, and it needs no logic to detect it.

Checking dependencies in readiness

Readiness should verify what a real request needs. Model each dependency as a function that resolves on success and rejects on failure, and always time-box it. A check that hangs for 30 seconds is a failed check that also pins a probe connection.

checks.jsJavaScript
export function withTimeout(promise, ms, name) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error(`${name} timed out after ${ms} ms`)), ms);
    promise.then(
      (value) => { clearTimeout(timer); resolve(value); },
      (error) => { clearTimeout(timer); reject(error); },
    );
  });
}

export async function runChecks(checks) {
  const entries = Object.entries(checks);
  const results = await Promise.all(
    entries.map(async ([name, fn]) => {
      const started = performance.now();
      try {
        await withTimeout(fn(), 1000, name);
        return [name, { status: "up", ms: Math.round(performance.now() - started) }];
      } catch (error) {
        return [name, { status: "down", error: error.message }];
      }
    }),
  );
  return Object.fromEntries(results);
}

Promise.all is safe here because each branch catches its own error and never rejects. The checks run in parallel, so the total latency is that of the slowest one, bounded by the 1,000 ms timeout.

Wire it to the endpoint with example checks. In a real service the functions would call your pool, for instance a SELECT 1 query, a Redis PING or a HEAD request to a downstream API.

health-deps.jsJavaScript
import { createServer } from "node:http";
import { runChecks } from "./checks.js";

const checks = {
  database: async () => {
    await new Promise((resolve) => setTimeout(resolve, 20));
  },
  cache: async () => {
    throw new Error("connection refused");
  },
};

const server = createServer(async (req, res) => {
  if (req.url === "/readyz") {
    const results = await runChecks(checks);
    const healthy = Object.values(results).every((r) => r.status === "up");
    res.writeHead(healthy ? 200 : 503, { "content-type": "application/json" });
    res.end(JSON.stringify({ status: healthy ? "ready" : "degraded", checks: results }));
    return;
  }
  if (req.url === "/livez") {
    res.writeHead(200).end("ok");
    return;
  }
  res.writeHead(404).end();
});

server.listen(3000);
Shell
curl -s -w "\n%{http_code}\n" localhost:3000/readyz
Text
{"status":"degraded","checks":{"database":{"status":"up","ms":21},"cache":{"status":"down","error":"connection refused"}}}
503

The millisecond figure will vary between runs. The detail in the body is for humans and dashboards, and the status code is what the orchestrator reads. Be careful about what you put in the body: error messages can leak hostnames and credentials-adjacent detail, so on a public listener return only the status and keep the details in logs.

Do not check every dependency on every probe

Probes arrive every few seconds from every load balancer and orchestrator, so a check that queries the database each time adds real load, and it multiplies by instance count. Two habits keep it cheap. First, use the lightest possible operation: SELECT 1, PING, a pool state check, not a business query. Second, cache the result for a short period so a burst of probes costs one check.

cached.jsJavaScript
export function cached(fn, ttlMs) {
  let value;
  let expires = 0;
  let inflight;

  return async () => {
    const now = Date.now();
    if (value && now < expires) return value;
    inflight ??= fn()
      .then((result) => {
        value = result;
        expires = Date.now() + ttlMs;
        return result;
      })
      .finally(() => {
        inflight = undefined;
      });
    return inflight;
  };
}

Wrapping runChecks as cached(() => runChecks(checks), 2000) means that however many probes arrive within two seconds, the dependencies see one query. The inflight promise also collapses concurrent probes into a single run, which matters during the exact moment a dependency is slow and probes pile up.

One more distinction: separate hard dependencies from soft ones. If the recommendations service is down but checkout works, the instance should stay ready. Include in readiness only what the core request path cannot survive without, and report the rest in a separate /status endpoint that nothing automated acts on.

Readiness during shutdown

A deploy sends SIGTERM, and the order of operations decides whether users see errors. The instance should flip readiness to failing first, wait for the load balancer to notice, then stop accepting connections and finish in-flight requests.

shutdown.jsJavaScript
import { createServer } from "node:http";

let ready = false;
let shuttingDown = false;

const server = createServer((req, res) => {
  if (req.url === "/readyz") {
    const ok = ready && !shuttingDown;
    res.writeHead(ok ? 200 : 503).end(ok ? "ready" : "not ready");
    return;
  }
  res.writeHead(200).end("hello");
});

server.listen(3000, () => {
  ready = true;
});

process.on("SIGTERM", () => {
  shuttingDown = true;
  console.log("draining");
  setTimeout(() => {
    server.close(() => {
      console.log("closed");
      process.exit(0);
    });
    server.closeIdleConnections();
  }, 5000);
});
Text
draining
closed

The five-second delay gives the load balancer time to see the failing readiness probe and stop routing new requests. Without it, the server closes while requests are still being routed to it, and clients see connection resets. server.close() stops accepting new connections and calls back when active ones finish, and closeIdleConnections() drops keep-alive sockets that would otherwise hold the process open until they time out. Set the delay to a little more than your probe period times the failure threshold.

The Kubernetes configuration

Tie the endpoints to the three probes. Give the startup probe room for slow boots, so the liveness probe can stay strict afterwards.

deployment.yamlYAML
containers:
  - name: api
    image: example/api:1.4.0
    ports:
      - containerPort: 3000
    startupProbe:
      httpGet: { path: /readyz, port: 3000 }
      periodSeconds: 2
      failureThreshold: 30
    livenessProbe:
      httpGet: { path: /livez, port: 3000 }
      periodSeconds: 10
      timeoutSeconds: 2
      failureThreshold: 3
    readinessProbe:
      httpGet: { path: /readyz, port: 3000 }
      periodSeconds: 5
      timeoutSeconds: 2
      failureThreshold: 2

The startup probe allows up to 60 seconds, then hands over to the other two. Keep timeoutSeconds above your internal check timeout only if you want a slow dependency to fail the probe by timeout rather than by body, otherwise the probe can time out before your own 1,000 ms limit reports anything useful. The Kubernetes documentation on configuring probes lists every field.

Docker and Compose

Plain Docker has no readiness concept, only a HEALTHCHECK that marks a container healthy or unhealthy. Node.js images do not ship curl, so use Node itself, which already supports fetch.

DockerfileDockerfile
HEALTHCHECK --interval=15s --timeout=3s --start-period=20s --retries=3 \
  CMD node -e "fetch('http://127.0.0.1:3000/livez').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"

Use the liveness path here, for the same reason as before: a container that Docker marks unhealthy can be restarted by tooling, and you do not want that triggered by a database blip. In Compose, a depends_on with condition: service_healthy waits for this check, which is how you start an app only after its database accepts connections.

What to leave out

  • Do not run migrations, warm caches or heavy work inside a probe handler.

  • Do not require authentication for probe endpoints, but do not expose them on the public listener. Bind them to an internal port or restrict the route at the proxy.

  • Do not return 200 with "status": "down" in the body. Orchestrators read the status code.

  • Do not make liveness depend on any dependency. If you remember one rule, remember this one.

Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.