JAVASCRIPT
Implement API Request Retries with Exponential Backoff
Build resilient web applications by adding an exponential backoff retry mechanism to API calls, gracefully handling transient network issues or rate limits.
async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) {
try {
const response = await fetch(url, options);
if (!response.ok) {
if (response.status === 429 || response.status >= 500) { // Rate limit or server error
if (retries > 0) {
console.warn(`Request to ${url} failed with status ${response.status}. Retrying in ${delay / 1000}s...`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
}
}
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorData.message}`);
}
return await response.json();
} catch (error) {
if (retries > 0 && error.message.includes('Failed to fetch')) { // Network error
console.warn(`Network error for ${url}. Retrying in ${delay / 1000}s...`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
}
console.error('Final API request failed:', error.message);
throw error;
}
}
// Example usage:
// const API_ENDPOINT = 'https://api.example.com/sensitive_data';
// const token = 'your_auth_token';
// fetchWithRetry(API_ENDPOINT, {
// headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }
// })
// .then(data => console.log('Data fetched after retries:', data))
// .catch(err => console.error('All retries failed:', err.message));
How it works: This snippet provides a robust `fetchWithRetry` function that automatically retries failed API requests using an exponential backoff strategy. This is crucial for handling transient network issues, server-side glitches (5xx errors), or API rate limits (429 errors).
Key features:
1. **Retry Logic:** If an initial request fails due to specific HTTP statuses (429, 5xx) or a network error, the function attempts to retry the request.
2. **Exponential Backoff:** The `delay` between retries doubles with each attempt (`delay * 2`), preventing immediate re-saturation of a busy server.
3. **Max Retries:** The `retries` parameter limits the total number of attempts to prevent infinite loops.
4. **Error Handling:** After exhausting retries, the final error is thrown, providing clear feedback when an API call truly fails.