Órbita
- Código
- Arquitetura
- Dados
- Integração
- Resiliência
Quando usar
Chamadas a dependências externas instáveis
Órbita
Quando usar
Chamadas a dependências externas instáveis
Problema
Falha de um serviço derrubando os demais em cascata
Quando usar
Chamadas a dependências externas instáveis
circuit-breaker
Interrompe chamadas a um serviço com falha e libera aos poucos após recuperação.
Planta de estados
Reproduzir passo a passoComo funciona
AbortSignal de CALL_TIMEOUT_MS por chamada
CLOSED: terceira falha seguida abre e grava openedAt
OPEN: ErrorCircuitOpen sem chamar até OPEN_TIMEOUT_MS
HALF_OPEN: uma sonda; sucesso fecha, falha reabre
README.mdpattern/resilience/circuit-breaker
thiagoeti/pattern/circuit-breakerMáquina de estados na chamada a uma dependência instável: N falhas abrem o circuito (fast-fail); após o tempo de abertura, uma sonda fecha ou reabre. Evita cascata e esgotamento de conexões.
Antifraude cai (503): três falhas abrem o circuito, os PIX seguintes falham em 0 ms; ao voltar, a sonda fecha.
AbortSignal de CALL_TIMEOUT_MS por chamadaCLOSED: terceira falha seguida abre e grava openedAtOPEN: ErrorCircuitOpen sem chamar até OPEN_TIMEOUT_MSHALF_OPEN: uma sonda; sucesso fecha, falha reabresrc/demo.ts// Demo: PIX checks against the antifraud service through a circuit breaker — the service goes down, the circuit opens
// and fails fast, and after the open timeout a single probe closes it again.
import { Elysia } from "elysia";
type CircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
const ANTIFRAUD_URL = Bun.env.CIRCUIT_BREAKER_ANTIFRAUD_URL ?? "http://localhost:4201";
const FAILURE_THRESHOLD = 3;
const OPEN_TIMEOUT_MS = 1_000;
const CALL_TIMEOUT_MS = 300;
class ErrorCircuitOpen extends Error {
override name = "ErrorCircuitOpen";
}
// CLOSED counts consecutive failures; OPEN rejects at once; after the open timeout one probe goes through in HALF_OPEN.
class CircuitBreaker {
state: CircuitState = "CLOSED";
private failureCount = 0;
private openedAt = 0;
async execute<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T> {
if (this.state === "HALF_OPEN") throw new ErrorCircuitOpen("probe in flight");
if (this.state === "OPEN") {
if (Date.now() - this.openedAt < OPEN_TIMEOUT_MS) throw new ErrorCircuitOpen("fast-fail");
this.state = "HALF_OPEN";
}
try {
// The call timeout lives inside: without it a hung dependency is never an error and the breaker never sees it.
const result = await operation(AbortSignal.timeout(CALL_TIMEOUT_MS));
Object.assign(this, { state: "CLOSED", failureCount: 0 });
return result;
} catch (error) {
this.failureCount++;
if (this.state === "HALF_OPEN" || this.failureCount >= FAILURE_THRESHOLD) Object.assign(this, { state: "OPEN", openedAt: Date.now() });
throw error;
}
}
}
// The antifraud service, its health switched at runtime so the breaker meets real HTTP failures.
let antifraudIsHealthy = true;
const antifraud = new Elysia().post("/checks", ({ status }) => (antifraudIsHealthy ? { verdict: "approved" } : status(503, { error: "antifraud unavailable" }))).listen(new URL(ANTIFRAUD_URL).port);
const breaker = new CircuitBreaker();
async function pixCheck(pixId: string): Promise<void> {
const started = performance.now();
const outcome = await breaker.execute(async (signal) => {
const response = await fetch(`${ANTIFRAUD_URL}/checks`, { method: "POST", signal });
if (response.status >= 500) throw new Error(`antifraud answered ${response.status}`);
return ((await response.json()) as { verdict: string }).verdict;
}).catch((error: Error) => `${error.name}: ${error.message}`);
console.log(` ${pixId} | ${breaker.state.padEnd(9)} | ${String(Math.round(performance.now() - started)).padStart(3)} ms | ${outcome}`);
}
await pixCheck("PIX-1");
antifraudIsHealthy = false;
for (const pixId of ["PIX-2", "PIX-3", "PIX-4", "PIX-5", "PIX-6"]) await pixCheck(pixId);
antifraudIsHealthy = true;
await Bun.sleep(OPEN_TIMEOUT_MS);
await pixCheck("PIX-7");
await antifraud.stop(true);
bun install
bun run demo
Saída: PIX-1 aprovado; PIX-2 a PIX-4 recebem 503 e o terceiro abre o circuito; PIX-5 e PIX-6 em ErrorCircuitOpen com 0 ms; PIX-7, após o tempo de abertura, é a sonda que fecha (CLOSED, approved).
| Vantagem | Desvantagem |
|---|---|
| Sem esgotar conexões nem cascata | Rejeita chamadas válidas enquanto aberto |
| Fast-fail aciona fallback na hora | Limiar e tempo exigem calibração |