Tutorial

How to Fetch with Timeout and Cancellation

Wrap fetch in an AbortController with a timeout so a hanging request is cancelled and the caller gets a predictable error not an infinite wait.

On this page

  1. Introduction
  2. Define the request and its cancellation
  3. Deduplicate concurrent requests
  4. Cache with explicit invalidation
  5. Handle race conditions in the UI
  6. Retry with jitter and a cap
  7. Test the loading and error states
  8. Common pitfalls
  9. Conclusion

Introduction

How to Fetch with Timeout and Cancellation has a half-life. The fetch that was correct when the service ran on one box is wrong when it runs on fifty, and the timeout that was safe at one hundred requests per second is dangerous at ten thousand. Review the assumptions on a schedule, not just when they break, because breaking is the expensive way to learn the assumption expired. A quarterly read of the load-bearing cancellation is cheaper than the incident that teaches the same lesson.

Most teams reach for fetch when the real lever is timeout. The difference is where the cost lands: fetch pushes the cost onto every call, while timeout pays once at the boundary and lets the fast path run unguarded. For the overall approach, the second shape wins because the check is amortized and the hot loop stays tight. Reaching for the first shape is the reflex; resisting it is the engineering.

Define the request and its cancellation

The interface for Define the request and its cancellation is the contract the rest of the system relies on. If fetch returns a different shape on error than on success, every caller branches twice and one of the branches is wrong. Return one shape, with the error as data, and the callers handle it with a switch instead of a try. The shape is the API, and a good shape makes the wrong code hard to write, which is the most a timeout can do for the team that comes after.

Most teams reach for fetch when the real lever is timeout. The difference is where the cost lands: fetch pushes the cost onto every call, while timeout pays once at the boundary and lets the fast path run unguarded. For Define the request and its cancellation, the second shape wins because the check is amortized and the hot loop stays tight. Reaching for the first shape is the reflex; resisting it is the engineering.

async function fetchfetch(url: string, signal?: AbortSignal): Promise<unknown> {
  const res = await fetch(url, { signal, headers: { Accept: 'application/json' } });
  if (!res.ok) throw new Error(`http_${res.status}`);
  return res.json();
}

const inflight = new Map<string, Promise<unknown>>();
function dedupefetch(url: string): Promise<unknown> {
  const existing = inflight.get(url);
  if (existing) return existing;
  const p = fetchfetch(url).finally(() => inflight.delete(url));
  inflight.set(url, p);
  return p;
}
test('fetch dedupes concurrent calls', async () => {
  const a = dedupefetch(url);
  const b = dedupefetch(url);
  expect(a).toBe(b); // same promise
  await a;
});

The test pins the behavior. A how to fetch with timeout and cancellation that passes this test degrades on purpose instead of by accident.

Deduplicate concurrent requests

The simplest version of Deduplicate concurrent requests is the one to ship first. A fetch that handles the three cases the system actually sees is better than a timeout that handles the seven cases it might see someday, because the three-case version is testable and the seven-case version is speculative. Add the cases when the traffic proves they exist, and until then let the unknown case fail loudly. Speculative generality is the bug you write on purpose.

Deduplicate concurrent requests pays off when fetch is the constraint. Before that, it is overhead that makes the code harder to read and the path harder to follow. The discipline is to add it when the metric says timeout is the bottleneck, and to remove it when the metric says it no longer is. Code that carries cancellation for a problem it no longer has is debt, and debt compounds until nobody remembers why the guard exists.

Cache with explicit invalidation

Start with the boundary. Cache with explicit invalidation only works if every entry point passes through the same check, because a single bypass becomes the hole that an attacker or a bug finds. Wrap fetch so the check is structural rather than convention: a function, a middleware, a decorator, something the compiler or the framework enforces. Convention-based timeout rots the moment a new endpoint is added without the team remembering the rule.

Keep Cache with explicit invalidation small enough to audit. A fetch that spans three files and twenty branches is a fetch nobody understands, and the next change breaks it in a way the tests do not catch because the tests were written for the old shape. Extract the decision into one function, test that function exhaustively, and let the callers stay thin. The complexity has to live somewhere; put it where it is visible and tested, not where it is implicit and assumed.

Handle race conditions in the UI

The pitfall in Handle race conditions in the UI is assuming fetch is enough. In practice, timeout interacts with cancellation in ways that only surface under concurrent failure: a timeout that fires during a retry that fires during a partial deployment. Test the combination, not the pieces in isolation, because the pieces pass and the combination fails. A chaos test that injects the failure you fear is the cheapest way to find the seam before production does.

Do not conflate Handle race conditions in the UI with timeout. They look similar from the outside but the failure modes differ: fetch fails fast and the caller knows, while timeout fails slow and the caller guesses. Choose the one whose failure mode your system can absorb, and document the choice at the call site. A reader who sees cancellation without knowing which failure mode it carries will treat it as the wrong one, and the bug will surface in the path that was not reviewed.

Retry with jitter and a cap

The hard part of Retry with jitter and a cap is not the happy path. The happy path is what you demo. The hard part is what happens when fetch fails halfway, when timeout times out during a cancellation retry, when the network returns a partial body and the parser hangs. Enumerate the failure modes before you write the code, and for each one decide what the user sees. A failure that is decided in advance is a degradation; one that is discovered in production is an incident.

Retry with jitter and a cap composes only if the pieces agree on the failure contract. If fetch throws and timeout returns null, the caller writes two branches and misses a third. Define one error shape at the module boundary, convert everything to it, and let the callers write one branch. The consistency is worth more than the local fidelity, because the caller’s code is where the bugs live and the bugs live in the missed branch.

Test the loading and error states

The test for Test the loading and error states is the one most teams skip. It is the test that drives fetch to the failing condition and asserts the system degrades gracefully rather than crashing. Write it with a fake clock so the time-based logic is deterministic, a stubbed timeout so the failure is injected not waited for, and an assertion on the user-visible outcome not the internal state. A test that passes by timing out is not a test; it is a hope.

The cost of Test the loading and error states is not just the runtime cost of fetch. It is the cognitive cost on the next reader, the testing cost for the new branch, and the operational cost of the new failure mode. A timeout that is free at runtime but adds a branch nobody tests is expensive in the ways that surface later. Weigh the total cost, and prefer the solution that adds the least surface area, because surface area is where the bugs and the maintenance live.

Common pitfalls

Keep the common pitfalls small enough to audit. A fetch that spans three files and twenty branches is a fetch nobody understands, and the next change breaks it in a way the tests do not catch because the tests were written for the old shape. Extract the decision into one function, test that function exhaustively, and let the callers stay thin. The complexity has to live somewhere; put it where it is visible and tested, not where it is implicit and assumed.

  • Skipping the boundary check so fetch enters unvalidated.
  • Assuming timeout is fast without measuring the tail latency.
  • Letting cancellation fail silently instead of failing loudly with a metric.
  • Testing only the happy path so the boundary failure surfaces in production.
  • Sharing state across requests so one bad fetch poisons the next.

Conclusion

The test for the conclusion is the one most teams skip. It is the test that drives fetch to the failing condition and asserts the system degrades gracefully rather than crashing. Write it with a fake clock so the time-based logic is deterministic, a stubbed timeout so the failure is injected not waited for, and an assertion on the user-visible outcome not the internal state. A test that passes by timing out is not a test; it is a hope.

Self-check: write a test that drives fetch to the failing condition and assert the system degrades gracefully. Then how to fetch with timeout and cancellation is a property you maintain, not a feature you hope for.

Sources: SWR, TanStack Query.

FAQ

How is fetch different from timeout?
fetch assumes the condition is persistent and stops trying; timeout assumes it is transient and tries again. They are complementary: timeout inside fetch, so fetch counts the final outcome.
When should I avoid cancellation?
Avoid it when cancellation adds a branch nobody tests for a problem the traffic has not shown. Speculative cancellation is debt; add it when the metric proves the need.

Related Examples