JAVASCRIPT
Implementing Exponential Backoff for API Retries
Learn to build a robust API integration with exponential backoff and jitter, ensuring resilience against transient network or server errors for more reliable data fetching.
async function fetchDataWithRetry(url, options = {}, maxRetries = 5) {
let retries = 0;
while (retries < maxRetries) {
try {
const response = await fetch(url, options);
if (response.ok) {
return await response.json();
} else if ([408, 429, 500, 502, 503, 504].includes(response.status)) {
// Retry on transient errors: Request Timeout, Too Many Requests, Server Errors
const delay = Math.pow(2, retries) * 1000 + Math.random() * 1000; // Exponential backoff + jitter
console.warn(`Attempt ${retries + 1} failed with status ${response.status}. Retrying in ${delay / 1000}s...`);
await new Promise(res => setTimeout(res, delay));
retries++;
} else {
// Non-retryable error
const errorData = await response.text();
throw new Error(`API error: ${response.status} - ${errorData}`);
}
} catch (error) {
if (retries === maxRetries - 1) {
console.error(`Max retries (${maxRetries}) reached. Failed to fetch from ${url}.`, error);
throw error;
}
// Network error, also retry
const delay = Math.pow(2, retries) * 1000 + Math.random() * 1000;
console.warn(`Network error during attempt ${retries + 1}. Retrying in ${delay / 1000}s...`, error.message);
await new Promise(res => setTimeout(res, delay));
retries++;
}
}
throw new Error(`Failed to fetch from ${url} after ${maxRetries} attempts.`);
}
// Usage example:
// fetchDataWithRetry('https://api.example.com/data')
// .then(data => console.log('Fetched data:', data))
// .catch(error => console.error('Failed to fetch:', error));
How it works: This JavaScript snippet demonstrates a robust retry mechanism for API calls using an exponential backoff strategy with added jitter. It wraps the standard `fetch` API, automatically re-attempting requests that fail due to specific transient HTTP status codes (like 408, 429, 5xx series) or network issues. The delay between retries increases exponentially to avoid overwhelming the server, and a random jitter component is added to prevent synchronized retries from multiple clients, improving overall system stability.