Pattern Resilience Advanced
Retry
If a request fails because of a temporary network problem, your app can try it again with exponential backoff, so users don’t see an error for a problem that fixes itself.
The problem
Your user’s WiFi dropped out for 200 milliseconds, and now they’re looking at an error message for a request that would have worked fine if the app had just tried again automatically.
The pattern
With automatic retry logic, a request that fails with a temporary error, such as a 5xx response or a network failure, is tried again before any error is shown. For a brief glitch, the retry usually succeeds and users never find out that anything went wrong.
Problem
Many applications treat temporary failures, such as network blips, server timeouts, deployment rollouts, and container restarts, exactly the same way as permanent ones. A problem that clears up after two seconds gets the same error message as a resource that doesn’t exist.
It’s worst for mobile users. Cellular connections often drop packets, and switching from WiFi to mobile data can cause brief outages. If every failure triggers an error dialog, mobile users might see error messages over and over on a normal connection.
Solution
Exponential backoff spaces the retries out, with a delay of 1 second before the first retry, 2 seconds before the second, and 4 seconds before the third. That way, your app doesn’t flood a busy server with requests, but the first retry still happens quickly. Adding a random amount of time to each delay, called jitter, stops thousands of clients from retrying at the same moment and overloading a server that’s just recovering.
Some errors aren’t worth retrying at all. A 404 means the resource doesn’t exist, so retrying won’t help, and after a 401, the user has to log in before a retry can work. You should only retry temporary errors, and only up to a maximum number of retries, because a request that fails five times in a row probably has a permanent problem.
The request also has to be safe to send twice. If a POST succeeded on the server but the response was lost, the client can’t tell that apart from a failure, and sending it again might create a second order or take a second payment. A GET only fetches data, so it’s safe to repeat. Anything else should only be retried automatically when the server can recognize a repeated request, for example from an idempotency key that the client sends with each attempt.
Example
These examples build up one function, fetchWithRetry. It starts with backoff and jitter, then gets support for the Retry-After header, and then a React hook and a circuit breaker are built around it.
Exponential Backoff with Jitter
The wrapper passes method, headers, body, and any other fetch options through to fetch. It retries network failures and temporary server errors, but only for GET and HEAD requests, unless the caller sets idempotent: true to say that the request is safe to send twice.
async function fetchWithRetry(url, options = {}) {
const {
maxRetries = 3,
baseDelay = 1000,
maxDelay = 30000,
retryableStatuses = [408, 429, 500, 502, 503, 504],
idempotent = false,
onRetry,
...fetchOptions
} = options;
const method = (fetchOptions.method ?? 'GET').toUpperCase();
const safeToRepeat = idempotent || method === 'GET' || method === 'HEAD';
// One initial attempt plus up to maxRetries retries
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url, fetchOptions);
if (response.ok) return await response.json();
const error = new Error(`Request failed: ${response.status}`);
error.retryable = retryableStatuses.includes(response.status);
throw error;
} catch (error) {
// fetch() rejects with a TypeError on network failure, which is worth retrying
const retryable = error.retryable ?? error instanceof TypeError;
if (!safeToRepeat || !retryable || attempt === maxRetries) throw error;
// Exponential backoff with ±25% jitter
const exponentialDelay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
const jitter = exponentialDelay * 0.5 * (Math.random() - 0.5);
const delay = exponentialDelay + jitter;
onRetry?.(attempt + 1);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// A GET is retried by default
const products = await fetchWithRetry('/api/products');
// A POST is only retried because the server uses the key to ignore duplicates
await fetchWithRetry('/api/orders', {
method: 'POST',
headers: { 'Idempotency-Key': orderId },
body: JSON.stringify(order),
idempotent: true
});
Retry-After Header Support
If the server rate-limits a request, its Retry-After header tells the client when it can send the request again, and it’s better to follow that header than to use your own backoff timing. To support it, you can make two changes to fetchWithRetry, so that the error records the header’s value and the delay uses that value when there is one.
// Where the response wasn't ok
const error = new Error(`Request failed: ${response.status}`);
error.retryable = retryableStatuses.includes(response.status);
error.retryAfter = parseRetryAfter(response.headers.get('Retry-After'));
throw error;
// In the catch block, the server's delay replaces the backoff delay
const delay = error.retryAfter ?? exponentialDelay + jitter;
// Retry-After is either a number of seconds or an HTTP date
function parseRetryAfter(value) {
if (!value) return undefined;
const seconds = Number(value);
const ms = Number.isNaN(seconds) ? new Date(value) - Date.now() : seconds * 1000;
return Number.isFinite(ms) ? Math.max(0, ms) : undefined;
}
React Hook with Retry Feedback
If you wrap fetchWithRetry in a hook, any component can fetch data with automatic retries. The hook passes onRetry to the wrapper so that the hook can return the current attempt, and it returns a retry function for a manual “Try again” button. With the attempt count on screen, users know the app is still working and hasn’t locked up.
function useDataWithRetry(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [attempt, setAttempt] = useState(0);
const [reloadCount, setReloadCount] = useState(0);
useEffect(() => {
let cancelled = false;
async function fetchData() {
setLoading(true);
setError(null);
setAttempt(0);
try {
const result = await fetchWithRetry(url, {
onRetry: (n) => { if (!cancelled) setAttempt(n); }
});
if (!cancelled) setData(result);
} catch (err) {
if (!cancelled) setError(err);
} finally {
if (!cancelled) setLoading(false);
}
}
fetchData();
return () => { cancelled = true; };
}, [url, reloadCount]);
return { data, loading, error, attempt, retry: () => setReloadCount(c => c + 1) };
}
function DataLoader({ url }) {
const { data, loading, error, attempt, retry } = useDataWithRetry(url);
if (loading) {
return (
<div>
Loading...
{attempt > 0 && <p>Connection issue, retrying (attempt {attempt})...</p>}
</div>
);
}
if (error) {
return (
<div>
<p>Couldn't load this content.</p>
<button onClick={retry}>Try again</button>
</div>
);
}
return <div>{data.content}</div>;
}
Retry with Circuit Breaker
Retries help with one request, but when a service is down, all the requests to it fail, and each one goes through its full set of retries. A circuit breaker counts failures across requests and has three states. It starts CLOSED, where requests go through as normal. After threshold failures in a row it becomes OPEN, and for the next timeout milliseconds it rejects every call right away without sending a request. After that it’s HALF_OPEN, where it lets the next request through as a test. If that request succeeds, the breaker closes again, and if it fails, the breaker goes back to OPEN.
class CircuitBreaker {
constructor(threshold = 5, timeout = 60000) {
this.failureCount = 0;
this.threshold = threshold;
this.timeout = timeout;
this.state = 'CLOSED';
this.nextAttempt = Date.now();
}
async execute(fn) {
if (this.state === 'OPEN') {
if (Date.now() < this.nextAttempt) throw new Error('Circuit breaker is OPEN');
this.state = 'HALF_OPEN';
}
try {
const result = await fn();
this.failureCount = 0;
this.state = 'CLOSED';
return result;
} catch (error) {
this.failureCount++;
if (this.failureCount >= this.threshold) {
this.state = 'OPEN';
this.nextAttempt = Date.now() + this.timeout;
}
throw error;
}
}
}
// One breaker per service, shared by every request to it
const ordersBreaker = new CircuitBreaker();
const orders = await ordersBreaker.execute(() => fetchWithRetry('/api/orders'));
The breaker wraps the whole retry loop instead of each attempt. A request only counts as a failure after its retries have run out, and once the breaker is open, new requests fail right away without going through any retries or backoff delays.
Benefits
- Users don’t see errors for network glitches that resolve within seconds.
- Mobile users stop seeing constant error messages, because when a cellular connection drops briefly, the request gets retried instead of showing an error.
- Users don’t notice when a server is briefly unavailable during a deployment or an infrastructure change.
- Rate limits are easier to work with when you follow the server’s
Retry-Afterheader. - Read operations are easy to make reliable, because GET requests are safe to retry as many times as you need.
- For temporary problems, users no longer have to click “Try Again” themselves.
Tradeoffs
- If there’s a real problem, the error message is delayed, because users have to wait through all the retries before they find out something is broken.
- Without jitter, you can get a “thundering herd” problem, where thousands of clients retry at the same moment and overload a server that’s trying to recover.
- It’s tricky to tune the retry settings. Retrying too often adds load to a server that’s already overloaded, and long delays between retries leave users looking at a spinner.
- If an endpoint is flaky but the retries eventually succeed, your team might never notice the problem, unless you log each retry.
- Delays grow quickly with exponential backoff. With the default of three retries, a request that keeps failing goes through delays of about 1s, 2s and 4s before users see an error, and each extra retry doubles the delay again, so with five retries users might think the app has locked up.
- Requests that change data, such as a POST, can’t be retried automatically unless the server can detect a repeated request, so a failed form submission still shows an error.
- A circuit breaker adds more state to keep track of, such as the failure count and when to try the service again.
- On metered mobile connections, failed retries still use data the user pays for.
Summary
Retry logic tries a failed request again when it might succeed on a second attempt, so users don’t see errors for temporary network problems. Exponential backoff with jitter keeps the retries from overloading a server that’s recovering, and you should only retry operations that are safe to repeat. Permanent errors, such as a 404, should still fail right away, so users find out about them quickly.
See also
- Error Handling — Resilience
- Retry Pattern
- Exponential Backoff - Wikipedia