JAVASCRIPT
Robust API Retries with Exponential Backoff
Implement a resilient API retry mechanism using exponential backoff in JavaScript to handle transient network issues or server-side errors gracefully, improving application stability.
async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) {
try {
const response = await fetch(url, options);
if (!response.ok) {
if (response.status >= 500 && retries > 0) {
console.warn(`Request failed with status ${response.status}. Retrying in ${backoff}ms...`);
await new Promise(resolve => setTimeout(resolve, backoff));
return fetchWithRetry(url, options, retries - 1, backoff * 2);
}
throw new Error(`HTTP error! status: ${response.status}`);
}
return response;
} catch (error) {
if (retries > 0) {
console.warn(`Fetch error: ${error.message}. Retrying in ${backoff}ms...`);
await new Promise(resolve => setTimeout(resolve, backoff));
return fetchWithRetry(url, options, retries - 1, backoff * 2);
}
throw error;
}
}
// Example Usage:
// fetchWithRetry('https://api.example.com/data')
// .then(response => response.json())
// .then(data => console.log('Data fetched:', data))
// .catch(error => console.error('Failed after retries:', error));
How it works: This function wraps `fetch` to automatically retry requests that fail due to server errors (5xx status codes) or network issues. It uses an exponential backoff strategy, doubling the wait time between retries, to prevent overwhelming the API and give it time to recover. The `retries` parameter controls the number of attempts, making API integrations more robust.