JAVASCRIPT
Implement Exponential Backoff for Robust API Rate Limit Handling
Improve API integration reliability by implementing an exponential backoff strategy with retries to gracefully handle rate limiting and temporary errors in Node.js or browser.
async function fetchWithExponentialBackoff(
url,
options = {},
retries = 5,
delay = 1000 // Initial delay in ms
) {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (response.status === 429 || response.status >= 500) {
// Too Many Requests or Server Error
const retryAfter = response.headers.get('Retry-After');
const actualDelay = retryAfter ? parseInt(retryAfter, 10) * 1000 : delay * Math.pow(2, i);
console.warn(`API rate limit hit or server error. Retrying in ${actualDelay / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, actualDelay));
continue; // Retry the request
}
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API request failed: ${response.status} - ${errorText}`);
}
return response; // Success
} catch (error) {
console.error(`Attempt ${i + 1} failed for ${url}:`, error.message);
if (i === retries - 1) throw error; // Re-throw if it's the last retry
const actualDelay = delay * Math.pow(2, i);
console.log(`Retrying in ${actualDelay / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, actualDelay));
}
}
throw new Error('Max retries exceeded.');
}
// Usage example:
// (async () => {
// try {
// const response = await fetchWithExponentialBackoff('https://api.example.com/data');
// const data = await response.json();
// console.log('Fetched data:', data);
// } catch (error) {
// console.error('Failed to fetch data after multiple retries:', error);
// }
// })();
How it works: This snippet provides a robust `fetch` wrapper that implements an exponential backoff strategy. When an API returns a `429 Too Many Requests` or `5xx` error, it automatically retries the request after an increasing delay, respecting a `Retry-After` header if present. This helps your application gracefully handle temporary API issues and rate limits, improving overall integration stability and user experience.