Implement Retry Logic with Exponential Backoff in JavaScript
Learn to build a robust retry mechanism for failed API calls, handling transient network errors gracefully.
intermediateAsync and promisesjavascriptpromisesretryapiexponential backoff
Published: 11/12/2025
Updated: 11/12/2025
Advertisement
Question
Implement a fetchWithRetry(url, retries) function that:
- Retries failed requests up to N times
- Waits exponentially longer each time (100ms → 200ms → 400ms …)
- Skips retry for 4xx errors
Implementation
async function fetchWithRetry(url, retries = 3, delay = 100) {
try {
const res = await fetch(url);
if (!res.ok) {
if (res.status >= 400 && res.status < 500)
throw new Error('Client Error');
throw new Error('Server Error');
}
return res.json();
} catch (err) {
if (retries > 0) {
console.log(`Retrying... (${retries})`);
await new Promise((r) => setTimeout(r, delay));
return fetchWithRetry(url, retries - 1, delay * 2);
}
throw err;
}
}
Visualization
graph TD A[Initial Fetch] -->|Fail| B[Wait 100ms] B -->|Retry| C[Fail Again] C -->|Wait 200ms| D[Retry 2] D -->|Wait 400ms| E[Success ✅]
Summary
- Simple but powerful retry pattern for resilience
- Use exponential backoff to avoid hammering servers
- Avoid retrying client errors (4xx)
- Commonly used in real-world fetch, Axios, and GraphQL clients
Frequently Asked Questions
Should we retry 4xx errors?
No. Retry is meant for transient (5xx, network) errors.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement