pattern/observability/health-check
- Bun
- Bun RedisClient
- ElysiaJS
- PostgreSQL
- Redis
- TypeScript
- node-postgres
- Docker
/live e /ready para o orquestrador, /health com detalhe por dependência; crítica derruba o /ready, opcional só degrada.
pattern/observability/health-check
Cenário
Redis fora: /health 207, instância segue no balanceamento. PostgreSQL fora: /ready 503 e /live 200, sem reinício.
Planta
Fluxo4 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
Check com critical, timeoutMs e run sobre conexões existentes
Crítico falhoucritical; opcional: degraded; timeout = falha
/ready só críticos; /health todos; pior status define 200, 207 ou 503
/live não toca dependência
Trade-offs
O que se ganha, o que se paga
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./
src/
Executar com Docker
./docker.shuntil docker exec health-check-db sh -c 'pg_isready -h 127.0.0.1 -U postgres' >/dev/null 2>&1; do sleep 1; doneuntil docker exec health-check-cache redis-cli ping >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f health-check-db health-check-cacheSaí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.
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
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Rediscache / estrutura de dados
redis:7-alpine:6379
Variáveis de ambiente
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Health Check?
Liga os logs da mesma requisição. Abrir Correlation ID
Seu progresso
0/157 estudados
Fica salvo só neste navegador.