JAVASCRIPT
Implement API Rate Limiting Retries with Exponential Backoff
Learn to robustly handle API rate limits (429 Too Many Requests) by implementing an exponential backoff and retry mechanism using JavaScript's Fetch API.
async function fetchDataWithRetry(url, options = {}, retries = 3, delay = 1000) {
try {
const response = await fetch(url, options);
if (response.status === 429 && retries > 0) {
const retryAfter = response.headers.get('Retry-After');
const waitTime = retryAfter ? parseInt(retryAfter) * 1000 : delay * Math.pow(2, 3 - retries);
console.warn(`Rate limit hit. Retrying in ${waitTime / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
return fetchDataWithRetry(url, options, retries - 1, delay);
}
if (!response.ok) {
throw new Error(`API error: ${response.status} ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Fetch operation failed:', error);
throw error;
}
}
// Example usage:
// fetchDataWithRetry('https://api.example.com/data', { method: 'GET' })
// .then(data => console.log('Fetched data:', data))
// .catch(error => console.error('Failed to fetch:', error));
How it works: This JavaScript function `fetchDataWithRetry` demonstrates how to handle API rate limiting using an exponential backoff strategy. When a 429 Too Many Requests status code is received, it checks for a 'Retry-After' header to determine the wait time. If not present, it calculates a delay using exponential backoff (doubling the delay for each subsequent retry). The function then waits for the specified time using `setTimeout` and recursively retries the API call. It includes a maximum number of retries to prevent infinite loops and throws an error for other non-OK responses or network issues.