Skip to content
HTTP-02Intermediate5 min read

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.

JavaScript
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.

use-search.ts
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.

Retry?Status or error
YesNetwork errors, timeouts, 408, 429, 502, 503 and 504
No400, 401, 403, 404, 422 and other client errors
Only with careAny POST, unless the server supports an idempotency key
fetch-with-retry.js
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.

retry.js

Press Control or Command with Enter to run the code. Tab inserts spaces; press Escape and then Tab to leave the editor.

Console

Run the code to see its output here.

Change 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.

What happenedWhat to tell people
Timeout or network errorWe could not reach the server. Check your connection and try again.
401Your session expired. Sign in again to continue.
403You do not have access to this lesson.
404This lesson no longer exists.
429You are going a bit fast. Try again in a few seconds.
5xxSomething went wrong on our side. Please try again.
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.