JAVASCRIPT
Implement Robust API Calls with Exponential Backoff and Retries in JavaScript
Learn to build resilient API integrations in JavaScript using an exponential backoff strategy with retries to gracefully handle temporary network issues or rate limits.
async function fetchDataWithRetry(url, options = {}, maxRetries = 5) {
let retries = 0;
while (retries < maxRetries) {
try {
const response = await fetch(url, options);
if (!response.ok) {
// Handle HTTP errors, e.g., 429 Too Many Requests, 5xx server errors
if (response.status === 429 || response.status >= 500) {
throw new Error(`API error: ${response.status} ${response.statusText}`);
} else {
// For other client errors (e.g., 400, 401, 403, 404), don't retry
const errorData = await response.json().catch(() => ({ message: response.statusText }));
console.error(`Non-retryable API error: ${response.status} ${errorData.message}`);
throw new Error(`Non-retryable API error: ${response.status} ${errorData.message}`);
}
}
return await response.json();
} catch (error) {
console.warn(`Attempt ${retries + 1} failed: ${error.message}`);
retries++;
if (retries < maxRetries) {
const delay = Math.pow(2, retries) * 1000 + Math.random() * 1000; // Exponential backoff + jitter
console.log(`Retrying in ${delay / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
console.error(`Max retries (${maxRetries}) reached. Failing request.`);
throw error;
}
}
}
}
// Example usage:
// fetchDataWithRetry('https://api.example.com/data', { method: 'GET' })
// .then(data => console.log('Data fetched:', data))
// .catch(err => console.error('Failed to fetch data after retries:', err));
// Example with a POST request
// fetchDataWithRetry('https://api.example.com/post-data', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ key: 'value' })
// })
// .then(result => console.log('POST result:', result))
// .catch(err => console.error('Failed to post data after retries:', err));
How it works: This JavaScript snippet demonstrates how to make robust API requests using `fetch` with an exponential backoff and retry mechanism. It attempts to fetch data multiple times, increasing the delay between retries exponentially (with added jitter for randomness) if a temporary error (like 429 or 5xx) occurs. This approach prevents overwhelming the API server during transient issues and improves the resilience of your application's network requests.