pattern/resilience/circuit-breaker
- AbortSignal
- Bun
- ElysiaJS
- TypeScript
Má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.
pattern/resilience/circuit-breaker
Cenário
Antifraude cai (503): três falhas abrem o circuito, os PIX seguintes falham em 0 ms; ao voltar, a sonda fecha.
Planta
Estados6 passos — reproduza para seguir o fluxo
Como funciona
4passos
Máquina de estados que abre o circuito após N falhas e testa a dependência com uma sonda depois do tempo de abertura
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
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
Trade-offs
O que se ganha, o que se paga
Vantagens
Sem esgotar conexões nem cascata
Fast-fail aciona fallback na hora
Custos
Rejeita chamadas válidas enquanto aberto
Limiar e tempo exigem calibração
Código
pattern/resilience/circuit-breaker
5 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaí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).
Código
src/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);
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Trilhapasso 3 de 6
Resiliência de ponta a ponta
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Vem antes
Próximo passo
Combina com
Teste rápido
Qual é o próximo passo depois de Circuit Breaker?
Responde algo enquanto o circuito abre. Abrir Fallback
Seu progresso
0/157 estudados
Fica salvo só neste navegador.