JAVASCRIPT
Robust API Calling with Exponential Backoff and Retry Logic
Implement a resilient API retry mechanism using exponential backoff to gracefully handle rate limits and transient errors, improving integration stability.
const MAX_RETRIES = 5;
const INITIAL_DELAY_MS = 1000; // 1 second
async function fetchDataWithRetry(url, options = {}, retryCount = 0) {
try {
const response = await fetch(url, options);
if (response.status === 429 || response.status >= 500) { // Rate limit or server error
if (retryCount < MAX_RETRIES) {
const delay = INITIAL_DELAY_MS * Math.pow(2, retryCount) + Math.random() * 1000; // Exponential backoff + jitter
console.warn(`Rate limit or server error (${response.status}). Retrying in ${delay.toFixed(0)}ms... (Attempt ${retryCount + 1}/${MAX_RETRIES})`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchDataWithRetry(url, options, retryCount + 1);
} else {
throw new Error(`Max retries exceeded for ${url} (Status: ${response.status})`);
}
}
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`API error: ${response.status} - ${JSON.stringify(errorData)}`);
}
return await response.json();
} catch (error) {
console.error(`Error fetching ${url}:`, error.message);
throw error;
}
}
// Example usage:
// (async () => {
// try {
// const data = await fetchDataWithRetry('https://jsonplaceholder.typicode.com/posts/1');
// console.log('Fetched data:', data);
// // Example for a URL that might simulate an error (replace with actual failing URL if needed)
// // const failingData = await fetchDataWithRetry('https://httpstat.us/503'); // Simulates a 503 error
// // console.log('Failing data:', failingData);
// } catch (e) {
// console.error('Operation failed after retries:', e);
// }
// })();
How it works: This snippet provides a robust way to interact with APIs by implementing an exponential backoff retry mechanism. When an API returns a 429 (Too Many Requests) or a 5xx server error, the function waits for an increasing amount of time before retrying the request. This prevents overwhelming the API and increases the chance of successful data retrieval when facing transient issues. Jitter (random delay) is added to further avoid "thundering herd" problems.