Pular para o conteúdo
  1. Padrões
  2. Resiliência

circuit-breaker

Interrompe chamadas a um serviço com falha e libera aos poucos após recuperação.
Status
Em breve
Categoria
Resiliência
Implementação em Resiliênciapattern/resilience/circuit-breakerintrodutório4 passos≈ 3 min

Órbita

  1. Código
  2. Arquitetura
  3. Dados
  4. Integração
  5. Resiliência

Quando usar

Chamadas a dependências externas instáveis

Planta de estados

Reproduzir passo a passo
chamada antes doopenTimeoutMs, fast-failCLOSEDOPENHALF_OPEN3 falhas seguidas(5xx, timeout,conexão recusada)primeira chamadaapós openTimeoutMssonda aprovadasonda falha

Como funciona

  1. 1

    AbortSignal de CALL_TIMEOUT_MS por chamada

  2. 2

    CLOSED: terceira falha seguida abre e grava openedAt

  3. 3

    OPEN: ErrorCircuitOpen sem chamar até OPEN_TIMEOUT_MS

  4. 4

    HALF_OPEN: uma sonda; sucesso fecha, falha reabre

Nível
introdutório
Infraestrutura
A — código puro
Domínio financeiro
PIXAntifraude
Abrir a implementação completa

README.mdpattern/resilience/circuit-breaker

thiagoeti/pattern/circuit-breaker

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.

Cenário

Antifraude cai (503): três falhas abrem o circuito, os PIX seguintes falham em 0 ms; ao voltar, a sonda fecha.

Como funciona

  1. AbortSignal de CALL_TIMEOUT_MS por chamada
  2. CLOSED: terceira falha seguida abre e grava openedAt
  3. OPEN: ErrorCircuitOpen sem chamar até OPEN_TIMEOUT_MS
  4. HALF_OPEN: uma sonda; sucesso fecha, falha reabre

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);

Executar

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).

Trade-offs

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
Esc

↑ ↓ navegarEnter abrir239 resultados