Exponential Backoff Algorithm
What you'll learn: How to implement exponential backoff to intelligently space out retry attempts after failed network requests.
When a network request fails, retrying immediately might hit the same problem repeatedly, especially if a server is temporarily overloaded. Exponential backoff solves this by waiting progressively longer between each retry attempt—first a short delay, then double that, then double again, and so on.
Think of it like knocking on a busy friend's door. If they don't answer, you don't immediately knock again—you wait a bit. If they still don't answer, you wait even longer before trying once more. Each wait period gives them more time to become available.
How It Works
The basic pattern multiplies the delay by a factor (typically 2) after each failed attempt:
- 1st retry: Wait 1 second
- 2nd retry: Wait 2 seconds
- 3rd retry: Wait 4 seconds
- 4th retry: Wait 8 seconds
Most implementations add randomness (jitter) to prevent multiple clients from retrying simultaneously, and set a maximum delay to avoid waiting too long.
Basic Implementation Pattern
async function fetchWithBackoff(url, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(url);
if (response.ok) return response;
} catch (error) {
if (attempt === maxRetries - 1) throw error;
const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s...
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
This approach respects server resources, improves success rates for transient failures, and provides a better user experience than aggressive immediate retries.
Key Takeaway: Exponential backoff progressively increases wait times between retries using a multiplier (typically 2×), preventing server overload and improving the likelihood of eventual success for transient failures.