JAVASCRIPT
Robust API Client with Rate Limit Handling and Retry
Build a resilient API client in JavaScript that automatically handles rate limiting using retry-after headers for robust third-party integrations.
async function fetchWithRateLimitRetry(url, options = {}, retries = 3) {
try {
const response = await fetch(url, options);
if (response.status === 429) { // Too Many Requests
if (retries > 0) {
const retryAfter = response.headers.get('Retry-After');
const delay = (retryAfter ? parseInt(retryAfter, 10) * 1000 : 2000) + Math.random() * 1000; // Add jitter
console.warn(`Rate limit hit. Retrying in ${delay / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRateLimitRetry(url, options, retries - 1); // Retry with one less retry attempt
} else {
throw new Error('Maximum retries exceeded for rate limit.');
}
}
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`API Error: ${response.status} - ${errorData.message}`);
}
return await response.json();
} catch (error) {
console.error('Fetch error (with retry logic):', error);
throw error;
}
}
// Example Usage:
// fetchWithRateLimitRetry('https://api.example.com/data', { method: 'GET' })
// .then(data => console.log('Data fetched:', data))
// .catch(err => console.error('Failed to fetch after retries:', err));
How it works: This snippet provides a robust `fetch` wrapper that automatically handles API rate limiting by checking for a `429 Too Many Requests` status code. When a rate limit is hit, it looks for the `Retry-After` header to determine how long to wait before retrying the request. If the header is absent, it defaults to a sensible delay. The function incorporates a retry counter to prevent infinite loops and adds a small random jitter to the delay, reducing the chance of multiple clients retrying at the exact same moment. This mechanism significantly improves the reliability of your API integrations, especially with third-party services that enforce strict rate limits.