How-To Guide

How to Design Health Check Endpoints

Split liveness from readiness, keep dependency checks out of liveness, add startup probes, and cache results so probes cannot stampede.

On this page

  1. Introduction
  2. Liveness: is the process wedged
  3. Readiness: can this instance serve
  4. Startup: protect slow booters
  5. Cache the checks and probe politely
  6. Graceful shutdown as readiness
  7. Test the contracts
  8. Common pitfalls
  9. Conclusion

Introduction

Health endpoints look like the simplest thing a service exposes and quietly encode its most consequential operational decisions. The prober reading them, Kubernetes, a load balancer, a monitoring system, takes actions with opposite remedies: restart the process, or remove it from rotation. A single endpoint cannot serve both, and conflating them produces the two classic failure modes. The restart storm: readiness failures, a dependency outage, feed the liveness signal, the orchestrator restarts every instance, which reconnects to the still-broken dependency and fails again, and the fleet spends the outage restarting instead of serving. The zombie serving: a wedged process, deadlocked or exhausted, reports healthy because its health route is served by the same deadlocked machinery, or worse, reports healthy while the load balancer keeps sending it traffic it cannot process. The correct design is three endpoints with three contracts, liveness, readiness, and startup, each answering one question for one remediation. This tutorial designs all three, the dependency-checking discipline with timeouts and caching, and the graceful-shutdown interplay that makes readiness the traffic-drain valve it should be.

Liveness: is the process wedged

Liveness answers exactly one question: is this process able to do work at all, or is it wedged beyond recovery. The remediation for a failed liveness check is a restart, which is a destructive, last-resort action, and the check must be designed for that audience. Liveness checks nothing external: no database ping, no downstream call, no queue poll, because an external outage is not a wedge, and reporting it as one converts the orchestrator into an amplifier of the outage. A useful liveness signal is internal and cheap: an event-loop responsiveness check in Node, writing and reading a token within a deadline; a heartbeat goroutine updating a timestamp that the handler reads; a memory check that fails only on exhaustion the process cannot recover from. The frequency question answers itself from the remediation: liveness failures are rare, restarts are expensive, so the threshold, consecutive failures before action, is set high enough that a transient scheduler stall does not restart the fleet. A liveness endpoint that pings the database is the single most common health-check bug, and its signature is a dependency incident accompanied by a restart storm in the metrics.

Readiness: can this instance serve

Readiness answers: should traffic be routed to this instance right now. The remediation is removal from load-balancer rotation, non-destructive and immediately reversible, so readiness may and should check the dependencies the request path needs. The design discipline is threefold. Scope: check only dependencies whose failure genuinely prevents serving, the primary database for a CRUD service, not the optional recommendation service the code degrades around, or the system loses its degradation modes exactly when it needs them. Timeouts: each dependency probe gets a short timeout, a second or two, because readiness runs frequently and a slow dependency turns the probe into a slow endpoint, which the orchestrator interprets as a failure anyway. Aggregate honestly: any critical dependency down means not ready, reported as 503 with a body naming what is down, because that body is what the on-call reads during the incident.

export async function readiness(): Promise<HealthResult> {
 const checks = await Promise.allSettled([
  probe(db.query('select 1'), 1_000, 'database'),
  probe(cache.ping(), 500, 'cache'),
 ]);
 const failed = checks.filter(c => c.status === 'rejected');
 return {
  ready: failed.length === 0,
  status: failed.length === 0 ? 200 : 503,
  checks: checks.map(c => c.status === 'fulfilled' ? c.value : c.reason),
 };
}

Note what readiness does not do: it does not fail the process, crash, or exit. Readiness is a routing opinion, not a process state, and conflating the two, exiting when a dependency fails, is the restart storm wearing different clothes.

Startup: protect slow booters

The third check exists because many services need minutes to become ready: caches to warm, schemas to migrate, models to load, connections to establish. Without a startup probe, the orchestrator applies liveness deadlines from the first second, a service that takes 120 seconds to boot fails its liveness check at 30 and gets killed, forever chasing readiness it is never allowed to reach. The startup check answers: has the boot sequence completed. Until it succeeds, liveness and readiness probes are suppressed, and the failure remediation, a restart after the startup budget expires, is correct for a boot that genuinely hangs. Kubernetes models this directly with the startupProbe and a generous failureThreshold. The implementation detail that matters: the boot sequence should publish its progress, phase markers in the startup response, so a boot that hangs is diagnosable from the endpoint, warming cache, 40 percent, rather than from a log spelunk. The startup endpoint turns healthy once initialization finishes, and readiness then takes over the traffic decision, a handoff that is easy to implement and easy to forget, and forgetting it leaves the service in a state where it serves traffic before it is warm or never serves at all.

Cache the checks and probe politely

Health endpoints are polled aggressively, every few seconds per prober, and a fleet of probers can turn the health check into the load that fails the health check. Two mechanics defuse this. Result caching: dependency checks run on a schedule, every few seconds, and the endpoints serve the cached result, so probe frequency, ten probers at one second, does not multiply dependency load, the database sees one check per interval regardless of prober count. The cache TTL is short, a second or two, so the answer stays honest for routing decisions. Failure backoff: when a dependency is down, checking it every second adds load to the recovery, so a failing check backs off, exponential up to a bound, and the cached failure serves meanwhile. The politeness rules compound: probes get their own connection budget, the health server is often on a separate port precisely so that a saturated main listener does not make a healthy process look dead, and the response body stays small, because a megabyte health payload times probe frequency is a real traffic line-item. A health endpoint that is cheap and cached cannot become the outage it monitors.

Graceful shutdown as readiness

The most overlooked role of readiness is its behavior during shutdown, where it becomes the traffic-drain valve. The sequence: the process receives a termination signal, readiness immediately reports 503, the load balancer stops routing new traffic, the process drains in-flight requests, and only when the queue is empty does it close the listener and exit. Skipping the readiness flip makes every deploy a micro-outage: the balancer keeps routing to the instance for its deregistration interval, connections are reset mid-request, and users see errors proportional to deploy frequency. The implementation is a flag flipped in the signal handler, checked by the readiness endpoint before any dependency logic, draining ? 503 : runChecks(), with a drain timeout after which remaining requests receive honest failures rather than hanging forever. Liveness during shutdown stays 200 until the very end, because a restart of a draining process is the opposite of the drain’s intent. The shutdown path is also the highest-value test target, covered next, because it is exercised on every single deploy.

Test the contracts

Health endpoints have precise contracts with machinery, and the tests assert the contracts, not just the status codes. Dependency-down readiness: with the database unreachable, readiness returns 503 naming the database, liveness stays 200, and the process does not exit, which is the anti-restart-storm contract in three assertions. Wedged process: with the event loop blocked, liveness fails on its deadline while readiness also fails, but their consumers differ, and the test documents that split. Slow boot: a service with a 60-second init reports not-ready on startup and readiness until init completes, and survives liveness deadlines during the window. Probe storm: with a hundred concurrent probe requests, dependency call count equals one per cache interval, not one hundred. Shutdown drain: on SIGTERM, readiness flips to 503 immediately, in-flight requests complete, the listener closes after drain, and no new requests are accepted mid-drain. These five tests encode the operational behavior of the fleet, and they run in CI on every change, because health-check regressions are invisible in unit tests and expensive in production, where they surface as restart storms and deploy-time errors that the metrics then attribute to the wrong cause.

it('does not exit or flip liveness when the database is down', async () => {
 db.hang();
 const ready = await get('/readyz');
 const live = await get('/healthz');
 expect(ready.status).toBe(503);
 expect(live.status).toBe(200);
 expect(process.exitCode).toBeUndefined();
});

Common pitfalls

  • **Database ping in liveness. ** The classic: a dependency outage becomes a restart storm, and the orchestrator amplifies the incident it should have absorbed.
  • **One endpoint for both remediations. ** Restart and deroute are opposite actions; one signal cannot drive both without one failure mode or the other.
  • **Exit-on-dependency-failure. ** Crashing on readiness conditions is the restart storm in different clothes; readiness is an opinion, not a process state.
  • **Optional dependencies in readiness. ** The system loses its degradation modes precisely when the dependency is down and they are needed.
  • **Uncached checks. ** Probe frequency multiplies dependency load; the health check becomes the outage it monitors.
  • **No readiness flip on shutdown. ** Every deploy is a micro-outage of connection resets for the balancer’s deregistration interval.

Conclusion

Health endpoints are the service’s contract with its machinery, and the contract is three questions for three remedies. Liveness asks whether the process is wedged and drives restarts, so it checks nothing external and fails rarely. Readiness asks whether the instance should serve and drives routing, so it checks the critical dependencies with short timeouts, serves cached results so probers cannot become load, and flips false the moment shutdown begins, turning every deploy into a drain instead of a micro-outage. Startup asks whether boot has completed and protects slow starters from liveness deadlines. Return 200 or 503 with small honest bodies, keep the failure modes separate, and test the contracts: dependency down does not restart, probe storms do not multiply, drains complete. The endpoint that looks like a trivia question turns out to encode the fleet’s behavior during its worst moments, which is exactly why it deserves this much design.

Sources: Kubernetes: configure probes, gRPC: health checking protocol, MDN: 503 Service Unavailable.

FAQ

Why is one health endpoint wrong?
One endpoint conflates two opposite remediations: an unhealthy dependency should remove the instance from load balancers, while a wedged process should be restarted. Restarting for a dependency outage creates restart storms, and shedding load for a wedged process keeps a dead instance serving nothing.
Should readiness check every dependency?
Only the ones the request path cannot proceed without, and only those whose failure should stop traffic. Optional dependencies, ones the code degrades around, belong out of readiness or the system loses the ability to serve degraded.
What status codes should health endpoints return?
200 with a body for healthy, 503 for not, and nothing else. A 404 from a missing route is an orchestration misconfiguration, and creative codes or redirects are misread by every generic prober ever written.

Related Examples