typescriptintermediate

Health, Readiness & Liveness Checks

Express routes implementing Kubernetes-style health, readiness, and liveness probe endpoints.

typescript
import { Router, Request, Response } from 'express';

interface HealthDependency {
  name: string;
  check: () => Promise<boolean>;
}

export function healthRouter(dependencies: HealthDependency[]) {
  const router = Router();

  router.get('/healthz', (_req: Request, res: Response) => {
    res.json({ status: 'ok', uptime: process.uptime() });
  });

  router.get('/readyz', async (_req: Request, res: Response) => {
    const results = await Promise.all(
      dependencies.map(async (dep) => {
        try {
          const ok = await dep.check();
          return { name: dep.name, ok };
        } catch {
          return { name: dep.name, ok: false };
        }
      })
    );
    const allOk = results.every((r) => r.ok);
    res.status(allOk ? 200 : 503).json({ ready: allOk, checks: results });
  });

  return router;
}

Use Cases

  • Kubernetes deployments
  • Load balancer health checks

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.