@nodezor/smart-retry-ts
v0.0.1
Published
Zero-dependency type-safe retry utility with exponential backoff, jitter, timeouts, and circuit breaking
Maintainers
Readme
@nodezor/smart-retry-ts
Resilient async retry engine combining exponential backoff, randomized full jitter, per-attempt timeouts, and stateful circuit breaking.
The Problem
Basic retry logic (such as simple for loops with setTimeout) frequently causes "thundering herd" issues, overloads recovering downstream services, and lacks resilience features. Developers lack a zero-dependency, type-safe utility that combines exponential backoff with randomized jitter, configurable request timeouts, and automatic circuit breaking to fail fast during total outages.
Features
- 🎲 Exponential Backoff + Full Jitter: Prevents thundering herd problems during downstream recoveries.
- ⚡ Zero External Dependencies: Pure TypeScript native implementation.
- ⏱️ Per-Attempt Timeout: Prevents hung Promises from blocking application execution.
- 🔌 Stateful Circuit Breaker: Short-circuits requests during persistent downstream outages (
CLOSED,OPEN,HALF_OPEN). - 🛡️ Configuration Guard: Includes built-in
createEnvGuardrule validation.
Installation
# pnpm
pnpm add @nodezor/smart-retry-ts
# npm
npm install @nodezor/smart-retry-ts
# yarn
yarn add @nodezor/smart-retry-tsQuick Start / Usage Example
import { retryAsync, createCircuitBreaker } from '@nodezor/smart-retry-ts';
// Shared stateful circuit breaker
const circuitBreaker = createCircuitBreaker({ failureThreshold: 3, resetTimeoutMs: 15000 });
async function fetchExternalData() {
return retryAsync(
async (attempt) => {
console.log(`Attempt #${attempt}...`);
const response = await fetch('https://api.external.com/data');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
},
{
maxRetries: 3,
initialDelayMs: 200,
maxDelayMs: 2000,
jitter: true,
timeoutMs: 3000,
circuitBreaker,
fallback: { data: 'fallback_cached_data' },
}
);
}API Reference
retryAsync<T>(fn: (attempt: number) => Promise<T>, options?: RetryOptions<T>): Promise<T>
Executes an asynchronous function with backoff retries.
RetryOptions
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| maxRetries | number | 3 | Maximum retry attempts |
| initialDelayMs | number | 100 | Initial delay in ms |
| maxDelayMs | number | 3000 | Maximum delay cap in ms |
| backoffFactor | number | 2 | Exponential backoff multiplier |
| jitter | boolean | true | Enables randomized full jitter |
| timeoutMs | number | undefined | Per-attempt timeout in ms |
| fallback | T \| () => T \| Promise<T> | undefined | Fallback value when retries fail |
| circuitBreaker | CircuitBreaker \| CircuitBreakerOptions | undefined | Circuit breaker configuration |
createCircuitBreaker(options?: CircuitBreakerOptions): CircuitBreaker
Creates a stateful circuit breaker with .state (CLOSED, OPEN, HALF_OPEN), .execute(fn), and .reset().
License
MIT © PRX2112
