What you'll learn: By the end of this lesson you will be able to explain what an
AbortSignaldoes and what it cannot undo, combine a user cancel with a timeout, tell aTimeoutErrorfrom anAbortError, propagate one deadline through nested calls, explain when a hedged request is safe, stop an older response from overwriting a newer one, and read a captured trace from a lab that runs all of this on a virtual clock.
Picture ordering a coffee and then changing your mind at the till. If the barista has not started, the cancel works. If the milk is already steaming, your cancel only tells the barista to stop; the coffee exists, and somebody may still pay for it. A cancel is a message, not an undo.
A browser tab is in the same position with every request. It can stop waiting, and it can tell the network stack to stop, but it cannot reach into a server and rewind what the server already did. This lesson covers the tool for sending that message (AbortController), the clock that sends it automatically (a timeout), the budget that spans several calls (a deadline), the trick of asking twice (a hedge), and the bug that appears when answers come back in the wrong order (a race).
The running example is a grocery product page. Loading it needs four calls in a row: session, inventory, price and reviews. A category filter reloads the list, and a "Place order" button sends a POST. All times and sizes below are illustrative unless a source is named.
The core idea
Keep three statements in mind.
- A signal is a one-way, cooperative stop request. The caller aborts; the operation notices and rejects. Nothing already done on the server is reversed, and code that ignores the signal keeps running.
- A timeout is a cancel scheduled on a clock, and a deadline is a timeout shared by a whole call tree. A single timeout bounds one step. A deadline is an absolute point in time, so a nested call can shorten the time left but never extend it.
- A race is two requests competing for the same place on the screen. Whichever answer arrives last wins unless you make the newest request the only one allowed to write. Cancelling the old request and ignoring its answer are two guards for the same moment.
Retrying is the next step after a timeout, and it has its own rules about which requests may be repeated. That is the next lesson, Client Retries, Exponential Backoff and Jitter. Here the focus is what happens up to the moment the client gives up.
AbortController and AbortSignal
MDN describes AbortController as an object that lets you abort one or more web requests when you want, and you pass its signal to the operation. Calling abort() can abort fetch requests, the consumption of response bodies, and streams. The signal has an aborted flag, a reason and an abort event.
Illustration 1: a minimal example. One request, with a cancel button and a timeout, told apart by the error name.
const user = new AbortController();
const signal = AbortSignal.any([user.signal, AbortSignal.timeout(200)]);
try {
const res = await fetch("/api/inventory/1234", { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
render(await res.json());
} catch (err) {
if (err.name === "TimeoutError") showMessage("This is taking too long.");
else if (err.name === "AbortError") { /* the user pressed Cancel: say nothing */ }
else throw err;
}
Three facts make this work, each from MDN.
fetch()rejects only when the request fails, for example on a network error or an abort. It does not reject on HTTP error statuses such as 404 or 504, so you must checkresponse.ok.AbortSignal.timeout(ms)returns a signal that aborts after the given time with aTimeoutError. That is how a timeout differs from a user cancel, which rejects with anAbortErrorunless you passed another reason toabort().AbortSignal.any([...])returns a signal that aborts when any input aborts, with the reason of the first one that did. If an input is already aborted, so is the result.
A signal you build yourself can be checked at safe points with signal.throwIfAborted(), which throws the abort reason if the signal is aborted and does nothing otherwise. MDN lists it as widely available since April 2022; check its table for the other methods before you rely on them in a browser you must support.
Figure 1. One call, three ways to stop
How to read this: the operation holds one signal. Which of the three inputs aborted decides the reason it rejects with, and therefore what the user sees.
Timeouts have gaps worth knowing
- A timeout signal cannot be cancelled early. MDN says
AbortSignal.timeout()has no way to cancel its timeout, and finishing early does not cancel it. If you need a timer you can clear, use anAbortControllerwithsetTimeout()and callclearTimeout()when the operation finishes. - It counts active time, not elapsed time. MDN says it is effectively paused in a suspended worker or while a document is in the back-forward cache.
- A timeout also bounds the body, if you let it.
abort()can abort the consumption of a response body, so a signal passed tofetchcan cut off a slow download after the headers arrived. The lab below measures a different thing, a timeout until headers, which is a choice, not a rule.
What an abort does not undo
The browser side of an abort is complete: the fetch promise rejects and the response is not delivered. The server side is a separate question.
Figure 2. The client gave up; the server did not
How to read this: the client's state ("failed") and the server's state ("order exists") disagree. That gap is the reason to know which requests may be repeated, and why a timeout on a write must be shown as "unknown", not "failed".
gRPC's deadline guide describes the server half of this: a server cancels a call once the client's deadline has passed, but "the server application is responsible for stopping any activity it has spawned to service the RPC". Over plain HTTP there is no equivalent promise at all. Some servers notice a closed connection, and some finish the work anyway. A client has to assume the second.
This is also why cancelling a read is cheap and cancelling a write is dangerous. Dropping a cancelled GET wastes some server work. Dropping a cancelled POST may leave a created order that the client has forgotten.
Race conditions: the older answer arrives last
Illustration 3: a failure case. The shopper picks category "fruit", then quickly "bakery". Two list requests are in flight. The fruit response is slower and lands after the bakery one. If the page simply renders whatever arrives, the screen says "bakery" in the filter and shows fruit.
React's documentation calls these bugs race conditions: two asynchronous operations are racing and may arrive in an unexpected order. Its guidance is that an effect that fetches should either abort the fetch or ignore its result, and that you cannot undo a network request that already happened, but the cleanup should make sure the no-longer-relevant fetch does not keep affecting your application.
It also adds a warning that matters here: an AbortController alone is not enough, because more asynchronous steps could be chained after the fetch, so an explicit flag is the most reliable fix. So use two guards.
let controller;
let latestId = 0;
async function loadList(category, show) {
controller?.abort(); // guard 1: stop the old request
controller = new AbortController();
const myId = ++latestId;
try {
const items = await getList(category, controller.signal);
if (myId === latestId) show(items); // guard 2: only the newest may write
} catch (err) {
if (err.name !== "AbortError") throw err;
}
}
Figure 3. Two guards for one moment
is its id the newest?"} D -->|"yes"| E["Show it"] D -->|"no"| F["Drop it"]
How to read this: abort saves work; the id check protects correctness. With both, a slow request that ignores its signal still cannot change the screen. The lesson on debouncing and throttling builds the full typeahead version and measures it.
A third option is to avoid the race by design: a query cache keyed by the filter (see the lesson on server state) gives each category its own entry, so an old answer fills the old entry and the screen only reads the current key.
Deadlines: one budget for a whole call tree
Illustration 2: a realistic example. The product page makes four calls in sequence. If each one has its own 500 ms timeout, the page has no bound of its own: four calls, each just under the limit, take almost two seconds, long after the user would have left.
A deadline fixes that. gRPC's guide defines it as a point in time past which a client is unwilling to wait, against a timeout, which is the maximum duration. Pass the deadline down, and each nested call gets only what is left. gRPC also notes that sending the absolute time between machines is risky because clocks may differ, so it sends the remaining time instead. In one browser tab the clock is shared, so an absolute time is safe.
Figure 4. Nested calls inherit the page's deadline
How to read this: all four calls share one signal. When the deadline passes, the call in progress is stopped and the call not yet started never starts, so no work continues for a caller that has given up.
The rule that matters: an inner call may shorten the deadline but never extend it. The effective deadline is the earlier of the parent's and the call's own now + timeout. And if the deadline has already passed, do not start the call.
Cancellation is still cooperative. If a nested function ignores its signal, the caller can still stop waiting, but the work keeps running. The demo below shows exactly that.
Hedged requests: asking twice, carefully
Some requests are slow only now and then: one replica is busy, one connection is bad. A hedged request sends the request, and if no answer arrives after a short delay, sends a copy. The first answer wins and the others are cancelled. gRPC's retry design describes the same policy: after the hedging delay passes without a successful response the next request is issued, up to a maximum number of attempts, and when one succeeds the outstanding ones are cancelled.
Two costs come with it. It adds load (a second request for the slow tail), and it is only safe when sending the request twice is harmless. RFC 9110 defines a method as idempotent when the intended effect of several identical requests is the same as one, and lists PUT, DELETE and the safe methods as idempotent. A hedge on POST /orders would risk two orders, so the lab's hedged() refuses to run unless the caller states the request is idempotent.
Trade-offs
| Choice | Gain | Cost | Wrong when |
|---|---|---|---|
| Per-call timeout only | Simple | No bound on a chain of calls | The page makes several calls in a row |
| Shared deadline | One bound for the whole tree | Every call must take and honour the signal | A library ignores the signal: it keeps running |
| Abort the old request | Saves bandwidth and server work | Needs a signal-aware client | Used alone, with chained async steps after the fetch |
| Ignore stale answers | Always correct | The old request still completes | Used alone on expensive requests |
| Hedging | Cuts the slow tail | Extra load; needs idempotency | The request writes data |
| Abort on unmount | No work for a closed view | A cancelled write may still be applied | The write must finish: let it, and ignore its result |
Build it
Two labs back this lesson. examples/frontend/labs/request-client is a small fetch wrapper with its own per-attempt timeout and AbortController; its retry rules are the subject of the next lesson. examples/frontend/labs/hedged-deadline builds on it and models deadline propagation, hedged requests and a write that outlives its abort. Both run on a virtual clock, so no real time passes.
cd examples/frontend/labs/hedged-deadline
node src/demo.ts
Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/hedged-deadline, copied from examples/frontend/golden/hedged-deadline.txt), in full:
=== no propagation: every nested call has its own 500 ms timeout
t= 0 session start
t= 120 session done
t= 120 inventory start
t= 420 inventory done
t= 420 price start
t= 870 price done
t= 870 reviews start
t=1270 reviews done
page failed at t= 800 (TimeoutError: deadline of t=800 ms exceeded)
work continued 470 ms after the caller gave up
=== deadline propagated: every nested call inherits the 800 ms deadline
t= 0 session start
t= 120 session done
t= 120 inventory start
t= 420 inventory done
t= 420 price start
t= 800 price stopped (TimeoutError: deadline of t=800 ms exceeded)
page failed at t= 800 (TimeoutError: deadline of t=800 ms exceeded)
work continued 0 ms after the caller gave up
=== hedged requests: 10 loads, hedge after 100 ms, at most 2 attempts
load no hedge hedged sent
1 40 ms 40 ms 1
2 45 ms 45 ms 1
3 900 ms 140 ms 2
4 42 ms 42 ms 1
5 38 ms 38 ms 1
6 1200 ms 140 ms 2
7 41 ms 41 ms 1
8 44 ms 44 ms 1
9 39 ms 39 ms 1
10 47 ms 47 ms 1
slowest: 1200 ms without hedging, 140 ms with hedging
mean: 244 ms without hedging, 62 ms with hedging
requests sent: 10 without hedging, 12 with hedging (2 extra)
=== one slow load in detail (load 3): the loser is aborted
t= 0 launch attempt 1
t= 100 launch attempt 2
t= 140 win attempt 2
t= 140 cancel attempt 1
=== a non-idempotent request is refused
TypeError: hedging sends the request more than once: only use it for idempotent requests
=== abort does not un-send: POST /orders, client timeout 300 ms, server needs 500 ms
-- the client times out and sends the request again, no idempotency key
t= 300 client TimeoutError: deadline of t=300 ms exceeded
t= 500 server applied order-1
t= 600 client TimeoutError: deadline of t=600 ms exceeded
t= 800 server applied order-2
orders created: 2
-- the same, but both attempts carry the same idempotency key
t= 300 client TimeoutError: deadline of t=300 ms exceeded
t= 500 server applied order-1
t= 600 client TimeoutError: deadline of t=600 ms exceeded
t= 800 server key key-1 already seen: no second order
orders created: 1
Read it in four parts.
- Without propagation, each nested call has its own 500 ms timeout. The page fails at 800, but the price call runs on to 870 and the reviews call then starts and runs to 1270: the work continued 470 ms after the caller gave up. With propagation, the price call is stopped at 800 and nothing continues (0 ms).
- Hedging takes the two slow loads (900 ms and 1200 ms without it) down to 140 ms each, at the cost of two extra requests out of twelve. The detail trace shows the loser being aborted at t=140.
- A non-idempotent request is refused: hedging a
POSTthrows aTypeErrorbefore anything is sent. - Abort does not un-send. With no idempotency key, the client times out twice, retries, and the server applies both: two orders. With the same key on both attempts, the server recognises the second and creates one. The last block is the point of Figure 2; the key itself is covered in the next lesson.
Verified. The 27 tests in hedged-deadline and the 38 in request-client passed with Node 26.12.1 and Vitest 5.1.0, and the type checks passed. The golden file was re-checked with node examples/frontend/tools/capture-golden.mjs --check.
Break it. In src/deadline.ts of hedged-deadline, replace Math.min(...candidates) with candidates[candidates.length - 1]!. A nested call's own timeout now replaces the parent's deadline. The test "a nested call can shorten the deadline but never extend it" fails (this was run for this lesson: 1 failed, 26 passed). Revert it.
Stretch. Add a hedge budget shared by all calls (for example, at most 5% of recent calls may send a second request), and test that a slow backend does not receive double load.
In practice: the order page that showed "failed" for an order that existed
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A grocery marketplace's order page loads four panels (session, inventory, price, reviews) and has a "Place order" button. During a busy evening the order service slows down. Support receives two kinds of ticket: the page spins for ages, and some customers report "it said failed, so I pressed it again, and now I have two orders".
Starting architecture
Figure 5. Starting point: every call has its own timeout, and a timeout means "failed"
How to read this: the two warning boxes are where the symptoms start. The reads have no shared bound, and the write turns "no answer within 3 s" into "failed".
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Raise every timeout | Fewer "failed" messages | Longer spinners | Hides the problem |
| One deadline for the page's reads | Bounded load time | Plumbing a signal through every call | A helper that ignores the signal |
| Show "unknown" after a write times out, and recheck | Honest state | A new UI state | Needs a way to look the order up |
| Idempotency key on the write | A repeat is safe | Server support | A key reused for a different order |
The decision
| Field | Decision record |
|---|---|
| Context | Reads have no shared bound; a write timeout is shown as failure although the server may still apply it. |
| Decision | Give the page reads one deadline and pass its signal down. Never label a timed-out write "failed": say "we are not sure yet", disable the button, check the order status, and send the same idempotency key on any repeat. |
| Consequences, good | Bounded load time; no duplicate orders from a second press. |
| Consequences, bad | A new "checking your order" state to design and test; server work for the key. |
| Revisit when | The order service can answer a status check cheaply, or its latency no longer reaches the client timeout. |
Rollout and verification
- Reproduce first with a fake server whose commit is slower than the client timeout (the last scenario of the lab).
- Ship the read deadline and check that the longest page load is bounded, and that no read continues after the deadline.
- Ship the "unknown" state and the key together; the state without the key would still allow two orders.
- Test the edges: a second press while the first is pending, leaving the page mid-write, a deadline that has already passed when a call starts.
The 2 a.m. failure
Late at night a handful of customers are charged twice. The new key is generated inside the click handler on every press, so two presses produce two different keys.
First three checks: (1) compare the keys of the duplicate orders in the logs; (2) check whether the key is created once per intended order or once per attempt; (3) confirm the button is disabled while a write is unknown. Mitigation: refund and merge the duplicates. Follow-up: create the key when the cart becomes an order draft, store it with the draft, and add a test that two presses send one key.
Architect's notes
- Make cancellation part of the request helper, not each component. One helper takes a signal, applies a timeout, and normalises the error names.
- Name the outcome "unknown" for writes. A client timeout says nothing about the server state.
- Prefer a deadline over stacked timeouts. The sum of your parts is not a budget.
- Treat a cancelled response as dead data. Even if cancellation fails, an id check keeps it off the screen.
- Verify that libraries honour the signal. A signal that nothing listens to cancels nothing.
Common mistakes
- Treating
abort()as an undo. It stops the wait; the server may still finish. - Using an abort as a failure. An
AbortErroryou caused is not an error to show or log as one. - Checking only
fetchrejections. A 500 resolves the promise; checkresponse.ok. - Giving each nested call a fresh timeout. The chain then has no bound.
- Trusting
AbortControlleralone against races. Add an id orignorecheck. - Hedging or cancelling-and-resending a write without an idempotency key.
- Leaving listeners on a long-lived signal, which keeps it alive longer than needed.
Key takeaways
- A signal asks an operation to stop; it does not undo server work.
AbortSignal.timeout()rejects with aTimeoutError, a user abort with anAbortError;AbortSignal.any()combines them.- A timeout bounds one call; a deadline bounds a call tree, and an inner call can only shorten it.
- A race needs two guards: abort the old request and ignore its answer.
- A timed-out write is unknown, not failed.
- Hedge only idempotent requests, and expect extra load.
- Test with a virtual clock and a server whose latency you control.
Practice exercises
Exercise 1: Starter (30 min). Run the snippet from Illustration 1 against a local server that sleeps. Make it produce a TimeoutError, then an AbortError by pressing a button, and print signal.reason in each case.
Exercise 2: Intermediate (2 hours). Run the lab demo, then write down for each of the first two scenarios how much work happens after the page has failed. Add a fifth call to the handler and predict the output before running.
Exercise 3: Intermediate (2 hours). Write a React hook that loads a list for a filter and applies both guards. Test with a fake server that delays the first request, using Testing Library and fake timers.
Exercise 4: Advanced (half day). Extend withDeadline so a call that crosses a process boundary sends the remaining time instead of an absolute time, and test it with a skewed clock.
Related reading
In this course:
- Debouncing and Throttling: the full typeahead pipeline that uses both race guards.
- Server State: Caching and Revalidation: keys that give each filter its own entry.
- React Effects and Synchronization: effect cleanup, where the cancel belongs.
- The Event Loop and the Main Thread: why timers are minimums.
- Optimistic Updates and Rollback: what to do when a write is in doubt.
- Client Retries, Exponential Backoff and Jitter: which failures to repeat, and how long to wait.
Elsewhere on the site:
- Timeouts, Retries, Exponential Backoff and Jitter: the back-end view of timeouts and deadlines.
Official documentation
- MDN: AbortController and AbortSignal: the signal,
abortedandreason. - MDN: AbortSignal.timeout() and AbortSignal.any(): timeouts and combined signals.
- MDN: AbortSignal.throwIfAborted() and Window.fetch(): checking a signal; when
fetchrejects. - React: Synchronizing with Effects: fetching in effects, the
ignoreflag and race conditions. - gRPC: Deadlines and gRFC A6: Client Retries: deadlines, propagation and the hedging policy.
- RFC 9110: HTTP Semantics: section 9.2.2, idempotent methods.