Network failures happen. Retry with exponential backoff prevents overwhelming server while ensuring request eventually succeeds.
Simple Retry Function:
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
for (let i = 0; i <= maxRetries; i++) {
try {
const response = await fetch(url, options);
if (response.ok) return response;
// If not ok and no retries left, throw
if (i === maxRetries) throw new Error(`HTTP ${response.status}`);
} catch (error) {
if (i === maxRetries) throw error;
// Exponential backoff: 1s, 2s, 4s, 8s...
const delay = Math.pow(2, i) * 1000;
console.log(`Retry ${i + 1}/${maxRetries} after ${delay}ms`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// Usage
try {
const data = await fetchWithRetry('/api/data');
console.log(await data.json());
} catch (error) {
console.error('Failed after retries:', error);
}
With Jitter (Random Delay):
const delay = Math.pow(2, i) * 1000 + Math.random() * 1000; // Prevents thundering herd if many clients retry simultaneously
