JAVASCRIPT
Robust API Calls with Exponential Backoff Retries
Implement resilient API requests by automatically retrying failed calls with increasing delays, essential for handling transient network issues or temporary server unavailability.
async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (!response.ok) {
// Treat non-OK responses (e.g., 5xx, 429) as potential retriable errors
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json(); // Or response.text(), etc.
} catch (error) {
console.warn(`Attempt ${i + 1} failed: ${error.message}. Retrying in ${backoff}ms...`);
if (i < retries - 1) {
await new Promise(resolve => setTimeout(resolve, backoff));
backoff *= 2; // Exponential backoff
} else {
throw error; // Re-throw after all retries exhausted
}
}
}
}
// Example Usage:
// fetchWithRetry('https://api.example.com/data', { method: 'GET' })
// .then(data => console.log('Data fetched:', data))
// .catch(error => console.error('Failed after multiple retries:', error.message));
How it works: This snippet demonstrates how to make API calls more robust using an exponential backoff retry strategy. It attempts to fetch data a specified number of times. If a request fails, it waits for an increasing duration before the next attempt, preventing continuous hammering of the server and giving transient issues time to resolve. After all retries are exhausted, the error is re-thrown.