-
Notifications
You must be signed in to change notification settings - Fork 1
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 { CircuitBreaker } from "bytekit/retry-policy";
// or | o también:
import { CircuitBreaker } from "bytekit";const breaker = new CircuitBreaker(config?: 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 |
| 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 |
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.
┌─────────────────────────────────────┐
│ │
▼ │
┌──────────┐ failures ≥ threshold ┌────────┐
│ CLOSED │ ─────────────────────────▶ │ OPEN │
│ (normal) │ │ (fail) │
└──────────┘ └────────┘
▲ │
│ │
│ successes ≥ threshold timeout expired
│ │
│ ┌─────────────┐ │
└──────── │ HALF-OPEN │ ◀──────────┘
│ (testing) │
└─────────────┘
│
│ failure
▼
┌────────┐
│ OPEN │
└────────┘
| 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 |
-
closed → open: When
failureCount ≥ failureThreshold(default: 5 failures). -
open → half-open: When
timeoutMshas elapsed since the last failure (default: 60s). -
half-open → closed: When
successCount ≥ successThresholdconsecutive successes (default: 2). - half-open → open: On any single failure during the half-open probe.
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"
}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`,
});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();
}// 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"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");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 },
});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.
- 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