JAVASCRIPT
Handle API Rate Limits with Exponential Backoff
Implement a robust retry mechanism with exponential backoff for API requests, making your integrations resilient to temporary 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 failed with status ${response.status}. Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
} else {
throw new Error(`Max retries reached. Request to ${url} failed with status ${response.status}`);
}
}
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
}
// Usage example:
// (async () => {
// try {
// const data = await fetchWithRetry('https://api.example.com/data');
// console.log('Fetched data:', data);
// } catch (error) {
// console.error('Failed to fetch after retries:', error.message);
// }
// })();
How it works: This snippet provides a `fetchWithRetry` function that automatically retries failed API requests, specifically for rate limiting (429 status) or server errors (5xx statuses). It uses an exponential backoff strategy, doubling the delay between retries, to prevent overwhelming the API and allow the server to recover, making integrations more robust.