Cancellation and concurrency control · senior
AbortController, cancellation and race conditions
An AbortController gives you a signal you pass to fetch, event listeners or your own async functions, and calling abort() cancels them; combine it with a latest-request-wins check so that out-of-order responses never overwrite newer data.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- const c = new AbortController(); fetch(url, { signal: c.signal }); c.abort() makes fetch reject with a DOMException named 'AbortError' (or with the reason you pass).
- signal.aborted, signal.reason, signal.throwIfAborted() and the 'abort' event. AbortSignal.timeout(ms) aborts with a 'TimeoutError'. AbortSignal.any([a, b]) aborts when any input aborts.
- addEventListener(type, fn, { signal }) removes the listener when the signal aborts, a clean way to remove many listeners at once.
- Making your own function abortable: check signal.aborted first, listen for 'abort', clear your timers, and reject with signal.reason.
- Race condition: the response for 're' arrives after the one for 'react' and overwrites it. Fixes: abort the previous request, or tag each request with an id and ignore stale responses. Debounce lowers the number of requests but doesn't fix ordering.
- In React, abort in the effect cleanup. Data libraries (RTK Query, TanStack Query) handle this for you.
- Aborting stops the client from waiting; the server may still finish the work, so non-idempotent POSTs need care.
The red pen
Common traps: mistake → fix
Mistake: Debounce fixes race conditions
Fix: it reduces requests; responses can still arrive out of order.
Mistake: abort() cancels the request on the server
Fix: only the client side stops.
Mistake: AbortError should be shown to the user
Fix: ignore it quietly; it is expected.
Easy to hard
Questions interviewers ask, easy to hard
- How do you cancel a fetch?
- A search box shows old results because responses arrive out of order. Fix it.
- What are AbortSignal.timeout and AbortSignal.any for?
- How do you make your own async function cancellable?
- How does this map to React effect cleanup and to RTK Query? What about non-idempotent requests?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.