RetryPolicy - sebamar88/bytekit GitHub Wiki
🔄 RetryPolicy
EN: Automatic retry logic with exponential backoff and jitter for resilient HTTP operations.
ES: Lógica de reintentos automáticos con retroceso exponencial y jitter para operaciones HTTP resilientes.
📦 Import
import { RetryPolicy } from "bytekit/retry-policy";
// or | o también:
import { RetryPolicy } from "bytekit";
⚙️ Constructor
const retry = new RetryPolicy(config?: RetryConfig);
RetryConfig
| Property / Propiedad | Type / Tipo | Default | Description (EN) | Descripción (ES) |
|---|---|---|---|---|
maxAttempts |
number |
3 |
Maximum number of attempts | Número máximo de intentos |
initialDelayMs |
number |
100 |
Initial delay in milliseconds | Retardo inicial en milisegundos |
maxDelayMs |
number |
10000 |
Maximum delay cap in milliseconds | Límite máximo de retardo en milisegundos |
backoffMultiplier |
number |
2 |
Multiplier for exponential backoff | Multiplicador para retroceso exponencial |
shouldRetry |
(error: Error, attempt: number) => boolean |
(built-in) | Custom function to decide if retry is needed | Función personalizada para decidir si reintentar |
📋 Methods / Métodos
| Method / Método | Signature / Firma | Description (EN) | Descripción (ES) |
|---|---|---|---|
execute |
execute<T>(fn: () => Promise<T>): Promise<T> |
Executes fn with automatic retries |
Ejecuta fn con reintentos automáticos |
getConfig |
getConfig(): RetryConfig |
Returns current configuration | Devuelve la configuración actual |
🧠 How It Works / Cómo Funciona
EN: RetryPolicy wraps an async function and automatically retries on failure. Each retry waits longer than the previous one using exponential backoff — the delay doubles each time (multiplied by
backoffMultiplier). A random jitter (±10%) is added to prevent multiple clients from retrying at the exact same moment (thundering herd problem).ES: RetryPolicy envuelve una función asíncrona y reintenta automáticamente ante fallos. Cada reintento espera más que el anterior usando retroceso exponencial — el retardo se duplica cada vez (multiplicado por
backoffMultiplier). Se añade un jitter aleatorio (±10%) para evitar que múltiples clientes reintenten en el mismo instante (problema de estampida).
Delay Formula / Fórmula de Retardo
delay = min(initialDelayMs × backoffMultiplier^(attempt-1) + jitter, maxDelayMs)
Example with defaults / Ejemplo con valores por defecto:
| Attempt / Intento | Base Delay | With Jitter (approx.) |
|---|---|---|
| 1 | 100 ms | ~100–110 ms |
| 2 | 200 ms | ~200–220 ms |
| 3 | 400 ms | ~400–440 ms |
Default Retryable Errors / Errores Reintentables por Defecto
EN: By default, RetryPolicy retries when it encounters these conditions:
ES: Por defecto, RetryPolicy reintenta cuando encuentra estas condiciones:
| Condition / Condición | Description (EN) | Descripción (ES) |
|---|---|---|
Status 408 |
Request Timeout | Tiempo de espera agotado |
Status 429 |
Too Many Requests | Demasiadas solicitudes |
Status ≥ 500 |
Server errors | Errores del servidor |
| Network errors | timeout, network, ECONNREFUSED, ECONNRESET |
Errores de red |
💡 Examples / Ejemplos
Basic Usage / Uso Básico
import { RetryPolicy } from "bytekit/retry-policy";
const retry = new RetryPolicy();
const data = await retry.execute(async () => {
const res = await fetch("https://api.example.com/data");
if (!res.ok) {
const err = new Error(`HTTP ${res.status}`);
(err as any).status = res.status;
throw err;
}
return res.json();
});
Custom Configuration / Configuración Personalizada
const retry = new RetryPolicy({
maxAttempts: 5,
initialDelayMs: 200,
maxDelayMs: 30000,
backoffMultiplier: 3,
});
await retry.execute(() => fetchCriticalData());
Custom shouldRetry / shouldRetry Personalizado
// EN: Only retry on 429 (rate limit) errors
// ES: Solo reintentar en errores 429 (límite de tasa)
const retry = new RetryPolicy({
maxAttempts: 4,
shouldRetry: (error, attempt) => {
const status = (error as any).status;
return status === 429;
},
});
With ApiClient / Con ApiClient
import { ApiClient } from "bytekit/api-client";
const client = new ApiClient({
baseUrl: "https://api.example.com",
retryPolicy: {
maxAttempts: 3,
initialDelayMs: 500,
},
});
// EN: All requests automatically use retry policy
// ES: Todas las solicitudes usan la política de reintentos automáticamente
const users = await client.get("/users");
Inspecting Config / Inspeccionar Configuración
const retry = new RetryPolicy({ maxAttempts: 5 });
const config = retry.getConfig();
console.log(config.maxAttempts); // 5
console.log(config.initialDelayMs); // 100
console.log(config.maxDelayMs); // 10000
console.log(config.backoffMultiplier); // 2
⚠️ Important Notes / Notas Importantes
EN: The
executemethod re-throws the last error if all attempts are exhausted. Always wrap calls in try/catch if you need to handle the final failure.ES: El método
executere-lanza el último error si se agotan todos los intentos. Siempre envuelve las llamadas en try/catch si necesitas manejar el fallo final.
try {
await retry.execute(() => riskyOperation());
} catch (error) {
console.error("All retries failed:", error);
}
🔗 See Also / Véase También
- CircuitBreaker — Prevent cascading failures / Prevenir fallos en cascada
- ApiClient — HTTP client with built-in retry support / Cliente HTTP con reintentos integrados