Retry
Problem
Temporary network blips or server timeouts immediately show error messages to users. Operations that could succeed if retried force users to manually refresh or try again. Transient failures get treated as permanent errors, degrading the user experience during normal internet hiccups.
Solution
Automatically reattempt failed requests with exponential backoff to handle transient errors. This makes applications resilient to temporary network issues without manual intervention.
Example
This example demonstrates automatic retry logic with exponential backoff, waiting progressively longer between each retry attempt to avoid overwhelming struggling servers.
async function fetchWithRetry(url, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
return await fetch(url).then(r => r.json());
} catch (err) {
// If this was the last retry, throw the error
if (i === retries - 1) throw err;
// Wait with exponential backoff: 1s, 2s, 3s
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}
Benefits
- Makes applications resilient to temporary network issues without user action.
- Improves user experience by handling transient failures automatically.
- Reduces error messages from temporary blips that resolve quickly.
- Works particularly well for read operations that are idempotent.
Tradeoffs
- Can delay error feedback if retries keep failing.
- May overwhelm struggling servers with repeated requests.
- Requires careful tuning of retry count and backoff strategy.
- Can hide persistent problems by masking them with retries.