javascript 113 lines · 3 tabs

Express Health-Check Router With a Pluggable Dependency Checks Registry

Shared by codesnips Aug 2026
3 tabs
const withTimeout = (promise, timeoutMs, name) => {
  let timer;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(
      () => reject(new Error(`check '${name}' timed out after ${timeoutMs}ms`)),
      timeoutMs
    );
  });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
};

class ChecksRegistry {
  constructor({ defaultTimeoutMs = 2000 } = {}) {
    this.defaultTimeoutMs = defaultTimeoutMs;
    this.checks = new Map();
  }

  register(name, fn, { timeoutMs } = {}) {
    if (this.checks.has(name)) {
      throw new Error(`check '${name}' already registered`);
    }
    this.checks.set(name, { fn, timeoutMs: timeoutMs || this.defaultTimeoutMs });
    return this;
  }

  async runAll() {
    const entries = [...this.checks.entries()];
    const settled = await Promise.allSettled(
      entries.map(async ([name, { fn, timeoutMs }]) => {
        const start = Date.now();
        const result = await withTimeout(Promise.resolve().then(fn), timeoutMs, name);
        return { name, durationMs: Date.now() - start, ...result };
      })
    );

    return settled.map((outcome, i) => {
      const name = entries[i][0];
      if (outcome.status === 'fulfilled') {
        return { name, status: outcome.value.status || 'up', ...outcome.value };
      }
      return { name, status: 'down', durationMs: null, error: outcome.reason.message };
    });
  }
}

module.exports = { ChecksRegistry, withTimeout };
3 files · javascript Explain with highlit

This snippet builds a production-style health-check endpoint for an Express service by separating three concerns: a registry of named checks, the individual dependency probes, and the router that aggregates them. The core idea is that liveness and readiness are not one boolean but the composition of many independent probes, each of which can succeed, fail, or time out on its own.

In checksRegistry.js, a ChecksRegistry stores probe functions keyed by name and exposes runAll. Each probe is wrapped in withTimeout so a hung dependency (a stuck TCP connect, a slow query) cannot stall the whole endpoint — an unresolved probe rejects after timeoutMs instead of hanging the request forever. Probes are executed concurrently via Promise.allSettled, so one failure never short-circuits the others and every dependency still reports its own status. Each result is normalized into { name, status, durationMs, error }, and a probe is allowed to mark itself degraded (reachable but slow or partial) rather than a hard down.

Probes themselves live in checks.js. postgresCheck runs a trivial SELECT 1, redisCheck issues a PING, and diskCheck demonstrates a degraded result when free space drops below a threshold. Each is just an async function returning a status, which keeps them trivially unit-testable and decoupled from the transport.

In healthRouter.js, the registry is populated once at wiring time. The router exposes /live as a cheap liveness probe that only confirms the process is up — crucial because a liveness failure typically triggers a pod restart, so it must not depend on downstream services. /ready calls registry.runAll, then folds the individual statuses into an overall verdict: any down yields 503, any degraded still returns 200 but flags the condition, and the full breakdown is returned as JSON for dashboards and probes to scrape.

The key trade-off is that readiness aggregation is only as good as its timeouts and its down/degraded classification; too aggressive and healthy nodes flap out of rotation, too lenient and traffic routes to a broken instance. Reaching for this pattern makes sense whenever a service has several external dependencies and needs Kubernetes, a load balancer, or an uptime monitor to distinguish 'restart me' from 'don't send me traffic yet'.


Related snips

Share this code

Here's the card — post it anywhere.

Express Health-Check Router With a Pluggable Dependency Checks Registry — share card
Link copied