Back to Digest
SnippetsResilient Fetch Wrapper with Jittered Exponential Backoff
typescriptEssentialCopied 163 times

Resilient Fetch Wrapper with Jittered Exponential Backoff

Production-grade HTTP client with automated retries, status code filtering, exponential delay, and random jitter.

typescript•
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
interface RetryOptions { maxRetries?: number; baseDelayMs?: number; retryOn?: number[]; } export async function fetchWithRetry(url: string, options: RequestInit = {}, retryConfig: RetryOptions = {}): Promise<Response> { const { maxRetries = 3, baseDelayMs = 300, retryOn = [408, 429, 500, 502, 503, 504] } = retryConfig; for (let attempt = 0; attempt <= maxRetries; attempt++) { try { const res = await fetch(url, options); if (!retryOn.includes(res.status) || attempt === maxRetries) { return res; } } catch (err) { if (attempt === maxRetries) throw err; } const jitter = Math.random() * 0.3 + 0.85; // ±15% variation const delay = Math.min(baseDelayMs * Math.pow(2, attempt) * jitter, 10000); await new Promise((r) => setTimeout(r, delay)); } throw new Error("Maximum retry attempts exceeded"); }
25 lines • 871 charactersUsed by 163 developers

Usage & Production Best Practices

This implementation is specifically optimized for high-throughput production environments. When integrating this pattern into your codebase:

  • Ensure all asynchronous handles or listeners are cleaned up within the parent lifecycle.
  • Avoid unbounded memory allocation by pinning cache buffers and queue capacities.
  • Pair with automated unit tests to guarantee zero regressions under edge-case concurrency.
Featured Resourcein JavaScript / Web
Curated Tool