javascript
44 lines · 8 steps
Retrying fetch with exponential backoff
A resilient fetch wrapper that retries transient failures with exponential backoff, jitter, and abort support.
Explained by
highlit
1const RETRIABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);
2
3function sleep(ms, signal) {
4 return new Promise((resolve, reject) => {
5 const id = setTimeout(resolve, ms);
6 signal?.addEventListener('abort', () => {
7 clearTimeout(id);
8 reject(new DOMException('Aborted', 'AbortError'));
9 }, { once: true });
10 });
11}
12
13export async function fetchWithRetry(url, options = {}, config = {}) {
14 const {
15 retries = 4,
16 baseDelay = 300,
17 maxDelay = 8000,
18 signal,
19 } = config;
20
21 let attempt = 0;
22
23 while (true) {
24 try {
25 const response = await fetch(url, { ...options, signal });
26
27 if (!RETRIABLE_STATUS.has(response.status) || attempt >= retries) {
28 return response;
29 }
30
31 const retryAfter = Number(response.headers.get('retry-after'));
32 var waitBase = Number.isFinite(retryAfter) && retryAfter > 0
33 ? retryAfter * 1000
34 : Math.min(baseDelay * 2 ** attempt, maxDelay);
35 } catch (err) {
36 if (err.name === 'AbortError' || attempt >= retries) throw err;
37 waitBase = Math.min(baseDelay * 2 ** attempt, maxDelay);
38 }
39
40 const jitter = Math.random() * waitBase * 0.3;
41 await sleep(waitBase + jitter, signal);
42 attempt++;
43 }
44}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Only retry on status codes and errors that are genuinely transient, and always cap the total number of attempts.
- 2Exponential backoff plus random jitter spreads retries out and prevents synchronized retry storms against a struggling server.
- 3Honoring both a server's Retry-After header and a caller's AbortSignal makes a retry loop cooperative rather than blindly aggressive.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/retrying-fetch-with-exponential-backoff-explained-javascript-28bb/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.