JAVASCRIPT
Implementing API Call Retries with Exponential Backoff in JavaScript
Enhance API integration robustness by implementing automatic retries with exponential backoff for transient network errors using async/await in JavaScript.
async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) {
try {
const response = await fetch(url, options);
if (!response.ok) {
// Consider status codes like 429 (Too Many Requests), 5xx (Server Errors) as retryable
if ((response.status === 429 || response.status >= 500) && retries > 0) {
console.warn(`Retrying ${url} due to status ${response.status}. Retries left: ${retries}`);
await new Promise(resolve => setTimeout(resolve, backoff));
return fetchWithRetry(url, options, retries - 1, backoff * 2); // Exponential backoff
}
throw new Error(`HTTP error! Status: ${response.status} - ${await response.text()}`);
}
return response.json();
} catch (error) {
if (retries > 0 && (error.name === 'AbortError' || error.name === 'TypeError' || error.code === 'ENOTFOUND')) { // Network/fetch errors
console.warn(`Retrying ${url} due to network error: ${error.message}. Retries left: ${retries}`);
await new Promise(resolve => setTimeout(resolve, backoff));
return fetchWithRetry(url, options, retries - 1, backoff * 2); // Exponential backoff
}
throw error; // Re-throw if no retries left or non-retryable error
}
}
// Example usage:
// (async () => {
// try {
// const data = await fetchWithRetry('https://api.example.com/data', { method: 'GET' });
// console.log('Fetched data:', data);
// } catch (err) {
// console.error('Failed to fetch data after multiple retries:', err.message);
// }
// })();
How it works: This function makes API calls more resilient by automatically retrying failed requests. It's designed to handle transient network issues or temporary server unavailability (like 5xx errors or rate limiting responses). It implements exponential backoff, meaning the delay between retries increases with each attempt, preventing immediate re-bombardment of a struggling server and allowing it time to recover. The `retries` parameter controls the maximum number of attempts, and `backoff` sets the initial delay in milliseconds.