JAVASCRIPT
Retrying Failed API Requests with Exponential Backoff
Implement a robust retry mechanism with exponential backoff for API calls in JavaScript, enhancing application resilience against transient network or server issues.
async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000, exponentialBase = 2) {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (response.ok) {
return response;
} else if (response.status >= 400 && response.status < 500 && response.status !== 429) {
// Don't retry client-side errors (except 429 Too Many Requests)
console.error(`Client error encountered (Status: ${response.status}). Not retrying.`);
throw new Error(`Client Error: ${response.status} ${response.statusText}`);
} else {
// Retry server errors or 429
console.warn(`Attempt ${i + 1} failed (Status: ${response.status}). Retrying...`);
const backoffDelay = delay * (exponentialBase ** i);
await new Promise(res => setTimeout(res, backoffDelay));
}
} catch (error) {
if (i < retries - 1) {
console.warn(`Network or unknown error on attempt ${i + 1}: ${error.message}. Retrying...`);
const backoffDelay = delay * (exponentialBase ** i);
await new Promise(res => setTimeout(res, backoffDelay));
} else {
console.error(`Max retries reached. Final error: ${error.message}`);
throw error;
}
}
}
throw new Error('Failed to fetch after multiple retries.');
}
// Example usage:
// async function getData() {
// const apiUrl = 'https://api.example.com/unstable-service';
// try {
// const response = await fetchWithRetry(apiUrl, { method: 'GET' }, 5, 500); // 5 retries, starting with 500ms delay
// const data = await response.json();
// console.log('Successfully fetched data:', data);
// } catch (error) {
// console.error('Failed to get data after retries:', error);
// }
// }
// getData();
How it works: This snippet provides a robust `fetchWithRetry` function that enhances the reliability of API integrations by automatically retrying failed requests. It implements an exponential backoff strategy, increasing the delay between retries to prevent overwhelming the server. The function differentiates between client-side errors (which are typically not retried) and server-side or network errors, making it intelligent about when to attempt a retry.