Pular para o conteúdo

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.

passos
4
arquivos
5
testes
0
tecnologias
4

Cenário

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

Planta

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

6 passos — reproduza para seguir o fluxo

  • chamada
  • resposta ou assíncrono
  • falha
  • passo
  • toque num nó para focar
  • repouso ou sucesso
  • transição
  • falha ou recusa
  • Outras plantas de estados

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+1
HALF_OPEN+1
  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

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

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

src/

  • demo.tsdemo

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

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

Requisitos
Bun

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

↑ ↓ navegarEnter abrir239 resultados