Fetching data reliably
Timeouts, cancellation, retries with backoff and error handling that tells users what actually happened.
Updated
A request that always works on your machine will eventually fail for someone else: a slow train connection, a flaky café network, an overloaded server. Reliable apps expect this. In this lesson you will add timeouts, cancellation, retries and error messages that help people instead of confusing them.
Always set a timeout
fetch waits as long as the browser allows, which can be several minutes. AbortSignal.timeout gives every request an upper bound and rejects with a TimeoutError when it is reached.
const response = await fetch('/api/lessons', {
signal: AbortSignal.timeout(8000)
})Cancel requests you no longer need
When someone types a new search query or leaves the page, the previous request is wasted work. Worse, if it finishes last it can overwrite newer results. An AbortController cancels it.
useEffect(() => {
const controller = new AbortController()
fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
.then((response) => response.json())
.then(setResults)
.catch((error) => {
if (error.name !== 'AbortError') setError(error)
})
// Runs when the query changes or the component unmounts
return () => controller.abort()
}, [query])Retry with exponential backoff
Some failures are temporary. Retrying immediately makes an overloaded server even busier, so wait a little longer before each attempt and add random jitter so thousands of clients do not retry in lockstep.
const RETRYABLE = new Set([408, 429, 502, 503, 504])
export async function fetchWithRetry(url, options = {}, { retries = 3, baseDelay = 300 } = {}) {
for (let attempt = 0; ; attempt++) {
try {
const response = await fetch(url, { ...options, signal: AbortSignal.timeout(8000) })
if (!RETRYABLE.has(response.status) || attempt === retries) return response
} catch (error) {
if (attempt === retries) throw error
}
const delay = baseDelay * 2 ** attempt + Math.random() * 100
await new Promise((resolve) => setTimeout(resolve, delay))
}
}You can watch the same idea work against a pretend server that fails twice before it succeeds.
calls < 3 to calls < 6 and run it again to see what happens when the retries run out.Turn errors into useful messages
Nobody can act on TypeError: Failed to fetch. Translate technical failures into messages that say what happened and what to do next, and keep the technical details in your logs where developers can find them.
export function describeError(error, response) {
if (error?.name === 'TimeoutError' || error instanceof TypeError) {
return 'We could not reach the server. Check your connection and try again.'
}
switch (response?.status) {
case 401: return 'Your session expired. Sign in again to continue.'
case 403: return 'You do not have access to this lesson.'
case 404: return 'This lesson no longer exists.'
case 429: return 'You are going a bit fast. Try again in a few seconds.'
default: return 'Something went wrong on our side. Please try again.'
}
}Summary
- Give every request a timeout with
AbortSignal.timeout. - Abort requests whose results you no longer need.
- Retry only temporary failures, with exponential backoff and jitter.
- Show people what happened and what to do next, and log the details.
Finished this lesson?
Mark it complete to track your progress across every track in the curriculum.