How would you implement request retries with exponential backoff and a total timeout using fetch()?
Short answer
Combine a retry loop around fetch() with AbortController-based per-attempt timeouts, increasing the delay between attempts exponentially, and stop retrying once either the attempt limit or overall elapsed time budget is exceeded.
Advertisement
AModel answer
Combine a retry loop around fetch() with AbortController-based per-attempt timeouts, increasing the delay between attempts exponentially, and stop retrying once either the attempt limit or overall elapsed time budget is exceeded.
async function fetchWithRetry(url, { retries = 3, timeout = 3000 } = {}) {
for (let i = 0; i <= retries; i++) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const res = await fetch(url, { signal: controller.signal });
clearTimeout(timer);
if (res.ok) return res;
} catch (err) {
if (i === retries) throw err;
await new Promise(r => setTimeout(r, 500 * 2 ** i));
} finally {
clearTimeout(timer);
}
}
}Real-world example
Building a resilient API client that gracefully handles flaky mobile network connections.
Likely follow-ups
- How would you avoid retrying on requests that aren't idempotent, like a POST that creates a resource?
Related topics