Resilient Fetch Wrapper with Jittered Exponential Backoff
Production-grade HTTP client with automated retries, status code filtering, exponential delay, and random jitter.
12345678910111213141516171819202122232425interface 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"); }
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.
TypeScript useDebounce Hook with Immediate Execution
A generic, type-safe debounced value and callback hook with cancel, flush, and immediate trigger capabilities.
Next.js 14 App Router Streaming SSE Endpoint
Native Server-Sent Events (SSE) route handler in Next.js 14 App Router supporting real-time token streaming.
React 19 useOptimistic Form Submission Pattern
Production-ready recipe for react 19 useoptimistic form submission pattern. Engineered for resilience, zero memory leaks, and sub-millisecond execution.
TypeScript Discriminated Union Exhaustiveness Assertion
Production-ready recipe for typescript discriminated union exhaustiveness assertion. Engineered for resilience, zero memory leaks, and sub-millisecond execution.