JAVASCRIPT
Implement an API Retry Mechanism with Exponential Backoff
Enhance API call reliability in web applications by implementing an exponential backoff retry strategy for transient network errors.
async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) {
try {
const response = await fetch(url, options);
if (!response.ok) {
// For server errors, typically 5xx, or network issues
if (response.status >= 500 && retries > 0) {
console.warn(`Attempt failed for ${url}. Retrying in ${backoff}ms...`);
await new Promise(resolve => setTimeout(resolve, backoff));
return fetchWithRetry(url, options, retries - 1, backoff * 2);
}
throw new Error(`API error: ${response.status} ${response.statusText}`);
}
return await response.json();
} catch (error) {
if (retries > 0 && (error instanceof TypeError || error.message.includes('Failed to fetch'))) {
// Network errors (e.g., CORS, no internet) often throw TypeError or "Failed to fetch"
console.warn(`Network error for ${url}. Retrying in ${backoff}ms...`);
await new Promise(resolve => setTimeout(resolve, backoff));
return fetchWithRetry(url, options, retries - 1, backoff * 2);
}
console.error(`Final API call failed after multiple retries for ${url}:`, error);
throw error;
}
}
// Usage example:
// fetchWithRetry('https://api.example.com/data')
// .then(data => console.log('Fetched data:', data))
// .catch(error => console.error('Failed to fetch data:', error));
How it works: This snippet provides a robust `fetchWithRetry` function that automatically retries API calls using an exponential backoff strategy. It specifically handles network errors (e.g., `TypeError` or 'Failed to fetch' messages) and server-side errors (5xx status codes). The `retries` parameter defines the maximum number of attempts, and `backoff` determines the initial delay between retries, which doubles with each subsequent attempt to prevent overwhelming the server.