JAVASCRIPT
Implementing Robust API Request Retries with Exponential Backoff
Learn how to automatically retry failed API requests with exponential backoff in JavaScript, improving application resilience against transient network issues or server errors.
async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) {
try {
const response = await fetch(url, options);
if (!response.ok) {
// If response is not OK (e.g., 5xx, 4xx but not 401/403 which might require re-auth)
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response;
} catch (error) {
if (retries > 0) {
console.warn(`Attempt failed for ${url}. Retrying in ${delay / 1000}s...`, error.message);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
}
throw error; // No more retries, throw the last 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 to fetch data after multiple retries:', error));
// fetchWithRetry('https://api.example.com/unavailable', { method: 'POST', body: JSON.stringify({ key: 'value' }), headers: { 'Content-Type': 'application/json' } }, 5)
// .then(response => response.json())
// .then(data => console.log('Data fetched:', data))
// .catch(error => console.error('Failed to fetch data after multiple retries:', error));
How it works: This JavaScript function `fetchWithRetry` enhances standard `fetch` API calls by automatically retrying failed requests. It employs a recursive approach with exponential backoff, meaning the delay between retries increases with each attempt, preventing immediate re-bombardment of a potentially overloaded server. The function takes the URL, `fetch` options, number of retries, and an initial delay as arguments, providing a robust solution for handling transient network or API issues.