Skip to content

CircuitBreaker

Sebastian Martinez edited this page Mar 28, 2026 · 3 revisions

⚡ CircuitBreaker

EN: Prevents cascading failures by stopping requests to unhealthy services and auto-recovering after a cooldown.

ES: Previene fallos en cascada deteniendo solicitudes a servicios no saludables y recuperándose automáticamente tras un período de enfriamiento.


📦 Import

import { CircuitBreaker } from "bytekit/retry-policy";
// or | o también:
import { CircuitBreaker } from "bytekit";

⚙️ Constructor

const breaker = new CircuitBreaker(config?: CircuitBreakerConfig);

CircuitBreakerConfig

Property / Propiedad Type / Tipo Default Description (EN) Descripción (ES)
failureThreshold number 5 Failures before opening the circuit Fallos antes de abrir el circuito
successThreshold number 2 Successes in half-open to close the circuit Éxitos en half-open para cerrar el circuito
timeoutMs number 60000 Time (ms) before attempting recovery Tiempo (ms) antes de intentar recuperación
errorMessageFormatter (ms: number) => string undefined Custom error message when circuit is open Mensaje de error personalizado cuando el circuito está abierto

📋 Methods / Métodos

Method / Método Signature / Firma Description (EN) Descripción (ES)
execute execute<T>(fn: () => Promise<T>): Promise<T> Executes fn with circuit breaker protection Ejecuta fn con protección del circuit breaker
getState getState(): CircuitBreakerState Returns current state: "closed" | "open" | "half-open" Devuelve el estado actual
reset reset(): void Manually resets to closed state Reinicia manualmente al estado cerrado

🧠 How It Works / Cómo Funciona

EN: The Circuit Breaker pattern is inspired by electrical circuit breakers. It monitors failures and "trips" (opens) when too many occur, preventing further damage. After a cooldown, it allows a few trial requests to see if the service has recovered.

ES: El patrón Circuit Breaker se inspira en los interruptores eléctricos. Monitorea fallos y se "dispara" (abre) cuando ocurren demasiados, previniendo más daño. Tras un enfriamiento, permite unas pocas solicitudes de prueba para verificar si el servicio se ha recuperado.

State Diagram / Diagrama de Estados

                    ┌─────────────────────────────────────┐
                    │                                     │
                    ▼                                     │
             ┌──────────┐     failures ≥ threshold   ┌────────┐
             │  CLOSED   │ ─────────────────────────▶ │  OPEN  │
             │ (normal)  │                            │ (fail) │
             └──────────┘                            └────────┘
                    ▲                                     │
                    │                                     │
                    │  successes ≥ threshold         timeout expired
                    │                                     │
                    │         ┌─────────────┐             │
                    └──────── │  HALF-OPEN   │ ◀──────────┘
                              │  (testing)   │
                              └─────────────┘
                                     │
                                     │ failure
                                     ▼
                                ┌────────┐
                                │  OPEN  │
                                └────────┘

States / Estados

State / Estado Description (EN) Descripción (ES)
closed Normal operation — requests pass through Operación normal — las solicitudes pasan
open Circuit tripped — all requests are rejected immediately Circuito disparado — todas las solicitudes se rechazan de inmediato
half-open Recovery testing — limited requests allowed to probe the service Prueba de recuperación — solicitudes limitadas para sondear el servicio

Transition Rules / Reglas de Transición

  1. closed → open: When failureCount ≥ failureThreshold (default: 5 failures).
  2. open → half-open: When timeoutMs has elapsed since the last failure (default: 60s).
  3. half-open → closed: When successCount ≥ successThreshold consecutive successes (default: 2).
  4. half-open → open: On any single failure during the half-open probe.

💡 Examples / Ejemplos

Basic Usage / Uso Básico

import { CircuitBreaker } from "bytekit/retry-policy";

const breaker = new CircuitBreaker();

try {
  const data = await breaker.execute(async () => {
    const res = await fetch("https://api.example.com/data");
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return res.json();
  });
  console.log(data);
} catch (error) {
  console.error("Request failed:", error.message);
  // EN: If circuit is open → "Circuit breaker is open. Retry after Xms"
  // ES: Si el circuito está abierto → "Circuit breaker is open. Retry after Xms"
}

Custom Configuration / Configuración Personalizada

const breaker = new CircuitBreaker({
  failureThreshold: 3,
  successThreshold: 1,
  timeoutMs: 30000, // 30 seconds cooldown
  errorMessageFormatter: (ms) =>
    `🚫 Service unavailable. Try again in ${Math.ceil(ms / 1000)}s`,
});

Checking State / Verificar Estado

console.log(breaker.getState()); // "closed" | "open" | "half-open"

if (breaker.getState() === "open") {
  // EN: Show fallback UI or cached data
  // ES: Mostrar UI de respaldo o datos en caché
  showCachedData();
}

Manual Reset / Reinicio Manual

// EN: Force the circuit breaker back to closed state (e.g., after deployment)
// ES: Forzar el circuit breaker de vuelta al estado cerrado (ej: tras un despliegue)
breaker.reset();
console.log(breaker.getState()); // "closed"

With ApiClient / Con ApiClient

import { ApiClient } from "bytekit/api-client";

const client = new ApiClient({
  baseUrl: "https://api.example.com",
  circuitBreaker: {
    failureThreshold: 3,
    timeoutMs: 30000,
  },
});

// EN: Circuit breaker protects all requests through this client
// ES: El circuit breaker protege todas las solicitudes a través de este cliente
const users = await client.get("/users");

Combined with RetryPolicy / Combinado con RetryPolicy

import { ApiClient } from "bytekit/api-client";

// EN: Retries first, then circuit breaker tracks overall failures
// ES: Primero reintenta, luego el circuit breaker rastrea los fallos generales
const client = new ApiClient({
  baseUrl: "https://api.example.com",
  retryPolicy: { maxAttempts: 3 },
  circuitBreaker: { failureThreshold: 5, timeoutMs: 60000 },
});

⚠️ Important Notes / Notas Importantes

EN: When the circuit is open, execute() throws immediately without calling your function. This protects the downstream service from being overwhelmed and saves network resources.

ES: Cuando el circuito está abierto, execute() lanza un error inmediatamente sin llamar a tu función. Esto protege al servicio downstream de ser sobrecargado y ahorra recursos de red.


🔗 See Also / Véase También

  • RetryPolicy — Automatic retry with exponential backoff / Reintentos automáticos con retroceso exponencial
  • ApiClient — HTTP client with built-in circuit breaker / Cliente HTTP con circuit breaker integrado

Clone this wiki locally