Skip to the page

Reliable requests · core

Timeouts, cancellation and race conditions with AbortController

fetch has no default timeout, so you pass an AbortSignal: AbortSignal.timeout(ms) for a deadline, an AbortController to cancel when the user moves on, and AbortSignal.any() to combine them; cancelling stale requests also fixes 'old search results overwrite new ones' race conditions.

The notes

What you must know

  • fetch(url, { signal }) rejects with an AbortError when controller.abort() is called; AbortSignal.timeout(ms) rejects with a TimeoutError. Check err.name to show the right message.
  • AbortSignal.any([userSignal, AbortSignal.timeout(8000)]) aborts when either fires (Baseline since March 2024).
  • Race condition: typing 'pi' then 'piz' starts two requests; if 'pi' returns last, the UI shows wrong results. Fix: abort the previous request, or ignore responses that are not from the latest request (a request id).
  • In React, abort in the effect cleanup: useEffect(() => { const c = new AbortController(); fetch(url, { signal: c.signal }); return () => c.abort(); }, [url]). Data libraries (TanStack Query, SWR, RTK Query) pass a signal for you.
  • Your own async functions should accept a signal too: check signal.aborted at the start and listen for 'abort'. Remove listeners when done.
  • Aborting stops the client from waiting; it does not undo work on the server. A POST that was aborted may still have succeeded.

The red pen

Common traps: mistake → fix

  • Mistake: "fetch times out by itself after some seconds"

    Fix: it has no timeout; the browser may wait minutes.

  • Mistake: "Aborting a request cancels the server operation"

    Fix: the server may still finish it; use idempotency for writes.

  • Mistake: "Debounce fixes race conditions"

    Fix: debounce reduces requests, but responses can still arrive out of order.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you add a timeout to fetch?
  2. A search box shows results for an older query. Why, and how do you fix it?
  3. How do you cancel requests when a React component unmounts or its input changes?
  4. How do you combine a user cancel with a timeout, and tell them apart in the UI?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview