JAVASCRIPT
Retrying Failed API Calls with Exponential Backoff
Build more resilient web applications by implementing an exponential backoff strategy to automatically retry failed API requests gracefully after transient network issues.
async function fetchDataWithRetry(url, options = {}, retries = 3, delay = 1000) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
if (retries > 0) {
console.warn(`Fetch failed, retrying in ${delay / 1000}s... (retries left: ${retries})`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchDataWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
} else {
console.error('All retries failed:', error);
throw error;
}
}
}
// Usage example:
// fetchDataWithRetry('https://api.example.com/unreliable-data', {}, 3, 500) // 3 retries, starting with 500ms delay
// .then(data => console.log('Successfully fetched data after retries:', data))
// .catch(error => console.error('Failed to fetch data after all retries:', error));
How it works: This snippet provides a robust way to handle transient API failures by implementing an exponential backoff retry mechanism. If a `fetch` request fails (either due to a network error or a non-OK HTTP status), the function will wait for a specified `delay` and then retry the request. The `delay` is doubled with each subsequent retry, preventing overwhelming the server and giving it time to recover. This pattern makes API integrations more resilient to temporary network issues or server load.