Pular para o conteúdo

Health Check

/live e /ready para o orquestrador, /health com detalhe por dependência; crítica derruba o /ready, opcional só degrada.

passos
4
arquivos
6
testes
0
tecnologias
8

Cenário

Redis fora: /health 207, instância segue no balanceamento. PostgreSQL fora: /ready 503 e /live 200, sem reinício.

Planta

Fluxo
4/4
OrquestradorAPI de pagamentosOperaçãoPostgreSQLRedis/live, /ready/healthSELECT 1, críticoPING, opcional
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

/live e /ready para o orquestrador, /health com detalhe por dependência

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    Check com critical, timeoutMs e run sobre conexões existentes

  2. 2

    Crítico falhoucritical; opcional: degraded; timeout = falha

  3. 3

    /ready só críticos; /health todos; pior status define 200, 207 ou 503

  4. 4

    /live não toca dependência

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Opcional fora não tira a instância

  • Orquestrador e operação leem o mesmo estado

Custos

  • Classificação errada derruba ou mantém indevidamente

  • Endpoint a proteger

Código

pattern/observability/health-check

6 arquivos

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec health-check-db sh -c 'pg_isready -h 127.0.0.1 -U postgres' >/dev/null 2>&1; do sleep 1; done
  3. until docker exec health-check-cache redis-cli ping >/dev/null 2>&1; do sleep 1; done
  4. bun install# dependências
  5. bun run demo# roda o cenário
  6. docker rm -f health-check-db health-check-cache

Saída: tudo no ar → 200 nos três; Redis fora → /ready 200 e /health 207 degraded; PostgreSQL fora → /live 200, /ready e /health 503 critical.

Requisitos
BunDocker
Sobe junto
PostgreSQLRedis

Código

src/demo.ts

// Demo: the payments API's /live, /ready and /health over real PostgreSQL (critical) and Redis (optional): all up, Redis down, PostgreSQL down.
import { RedisClient } from "bun";
import { Elysia } from "elysia";
import pg from "pg";

type HealthCheck = { critical: boolean; timeoutMs: number; run: () => Promise<unknown> };
type CheckStatus = "ok" | "degraded" | "critical";
const HTTP_STATUS: Record<CheckStatus, 200 | 207 | 503> = { ok: 200, degraded: 207, critical: 503 };

// The timeout is raced, not passed: a hung dependency cannot stall the probe. A failed optional check only degrades.
async function probeRun(check: HealthCheck): Promise<{ status: CheckStatus; error?: string }> {
  const timeout = Bun.sleep(check.timeoutMs).then(() => Promise.reject(new Error(`timeout after ${check.timeoutMs} ms`)));
  const error = await Promise.race([check.run(), timeout]).then(() => undefined, (failure: Error) => failure.message);
  if (error === undefined) return { status: "ok" };
  return { status: check.critical ? "critical" : "degraded", error };
}

// /live touches nothing (a restart would not fix a database outage); /ready runs only the critical checks.
function controllerHealth(checks: Record<string, HealthCheck>) {
  const report = async (criticalOnly: boolean) => {
    const selected = Object.entries(checks).filter(([, check]) => !criticalOnly || check.critical);
    const results = Object.fromEntries(await Promise.all(selected.map(async ([name, check]) => [name, await probeRun(check)] as const)));
    const statuses = new Set(Object.values(results).map((result) => result.status));
    return { status: statuses.has("critical") ? "critical" : statuses.has("degraded") ? "degraded" : ("ok" as CheckStatus), checks: results };
  };
  return new Elysia()
    .get("/live", () => ({ status: "ok" }))
    .get("/ready", async ({ status }) => {
      const body = await report(true);
      return status(HTTP_STATUS[body.status], body);
    })
    .get("/health", async ({ status }) => {
      const body = await report(false);
      return status(HTTP_STATUS[body.status], body);
    });
}

// Every check reuses a connection the API already holds, never one of its own.
const healthCreate = (pool: pg.Pool, redis: RedisClient) =>
  controllerHealth({
    postgres: { critical: true, timeoutMs: 1_000, run: () => pool.query("SELECT 1") },
    redis: { critical: false, timeoutMs: 500, run: () => redis.send("PING", []) },
  });

const pool = new pg.Pool({ connectionString: Bun.env.HEALTH_CHECK_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/health_check_db" });
const redis = new RedisClient(Bun.env.HEALTH_CHECK_REDIS_URL ?? "redis://localhost:6379");
const redisDown = new RedisClient("redis://127.0.0.1:1", { autoReconnect: false, connectionTimeout: 200 });
const poolDown = new pg.Pool({ connectionString: "postgres://postgres:postgres@127.0.0.1:1/none", connectionTimeoutMillis: 200 });

for (const [label, api] of [["all up", healthCreate(pool, redis)], ["Redis down", healthCreate(pool, redisDown)], ["PostgreSQL down", healthCreate(poolDown, redis)]] as const) {
  for (const path of ["/live", "/ready", "/health"]) {
    const response = await api.handle(new Request(`http://localhost${path}`));
    console.log(`  [${label}] ${path.padEnd(7)} ${response.status} ${await response.text()}`);
  }
}
await Promise.all([pool.end(), poolDown.end()]);
redis.close();

Nível

intermediário

5/13

Linhas de TypeScript
51
Tipo
B — dois ou mais serviços (docker compose)

Padrões do catálogo que implementa

  • Health Check

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

  • Rediscache / estrutura de dados

    redis:7-alpine:6379

Variáveis de ambiente

HEALTH_CHECK_DATABASE_URL
postgres://postgres:postgres@localhost:5432/health_check_db
PostgreSQL: critical, without it no payment is processed.
HEALTH_CHECK_REDIS_URL
redis://localhost:6379
Redis cache: degraded when down, the API reads from PostgreSQL instead.

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Health Check?

Próximo projeto, ObservabilidadeLLM Observability
Esc

↑ ↓ navegarEnter abrir239 resultados