AbortSignal.any() and timeout(): Real Request Cancellation

Replace leaky Promise.race wrappers with AbortSignal.timeout() and AbortSignal.any() in TypeScript, separate TimeoutError, and avoid listener leaks.

AbortSignal.any() and timeout(): Real Request Cancellation
In this essay

Wrapping fetch() in Promise.race() with a timer only abandons the JavaScript promise while leaving the underlying HTTP request running in the background. Pairing AbortSignal.timeout() with AbortSignal.any() cancels the actual network transport, preserves distinct failure reasons for deadlines versus manual aborts, and removes error-prone signal-forwarding code—provided you still clean up custom listeners on non-native wrappers.

Why Promise.race Timers Leak Work

A hand-rolled timeout built from Promise.race([fetch(url), rejectAfter(2_000)]) stops waiting, not working. When the timer wins the race, your caller catches an error and moves on, yet fetch() never receives a cancellation signal. On the client or inside a Node.js backend, the socket stays occupied, unread response chunks accumulate in buffers, and upstream streaming endpoints—such as file exports or LLM token streams—continue spending compute for a consumer that already left.

Passing AbortSignal.timeout(ms) directly to fetch() closes that gap at the transport layer. Supported across major browsers since April 2024 and in Node.js since v17.3.0 and v16.14.0, the static method returns a signal that automatically aborts with a "TimeoutError" DOMException once the deadline expires. Note that in browsers, this timer measures active time rather than wall-clock elapsed time, pausing while a document sits in the back-forward cache or inside a suspended worker.

Crucially, fetch() keeps observing that same signal while streaming the response body. If an upstream server flushes HTTP 200 headers in 50 milliseconds and then stalls halfway through the JSON payload, awaiting response.json() under the same AbortSignal still aborts cleanly instead of hanging indefinitely.

Composing Signals with AbortSignal.any()

Precision mechanical escapement gear beside an unplugged optical glass fiber connector on warm walnut wood

Production code rarely relies on a timeout alone. In a Nuxt page transition, a search-as-you-type input, or a Node.js route forwarding client disconnects, the caller already owns an AbortController—and you still want a strict per-request deadline.

Before AbortSignal.any() became widely available across browsers in March 2024 (and in Node.js starting with v20.3.0 and v18.17.0), combining two signals required creating a third AbortController and wiring .addEventListener('abort', ...) onto each parent. Whenever a long-lived parent signal—such as an application shutdown controller—shared listeners with thousands of short-lived HTTP calls without meticulous removeEventListener cleanup, closures piled up in memory.

AbortSignal.any() collapses that plumbing into a single expression:

export async function fetchJson<T>(
  url: string,
  options: { signal?: AbortSignal; timeoutMs?: number } = {},
): Promise<T> {
  const { signal: callerSignal, timeoutMs = 5_000 } = options;
  const timeoutSignal = AbortSignal.timeout(timeoutMs);

  const signal = callerSignal
    ? AbortSignal.any([callerSignal, timeoutSignal])
    : timeoutSignal;

  const response = await fetch(url, { signal });
  if (!response.ok) {
    throw new Error(`HTTP ${response.status} for ${url}`);
  }
  return (await response.json()) as T;
}

Two details make AbortSignal.any() safer than manual forwarding:

  • Pre-aborted short-circuiting: If callerSignal is already aborted before AbortSignal.any() runs, the composite signal starts in an aborted state carrying that first aborted input's reason, and fetch() rejects immediately without opening a connection.
  • Weak internal linkage: Runtimes link source signals to the composite signal using weak references. Once fetchJson() settles and drops its local reference to the composite signal, a long-lived callerSignal does not pin the completed request in memory.

Separating TimeoutError From Intentional Cancellation

Because AbortSignal.any() copies signal.reason from whichever input aborts first, your error boundary no longer has to guess why a request stopped. Calling controller.abort() without arguments produces a DOMException named "AbortError", whereas AbortSignal.timeout() produces "TimeoutError".

Conflating those two states degrades both user experience and observability. When a user types the next letter in an autocomplete box or clicks another tab, "AbortError" represents normal control flow; reporting it to an error tracker or flashing a failure banner creates noise. A "TimeoutError", by contrast, signals a slow dependency that deserves latency metrics, fallback cache reads, or a retry prompt:

try {
  const results = await fetchJson<Item[]>('/api/search?q=nuxt', {
    signal: searchController.signal,
    timeoutMs: 3_000,
  });
  render(results);
} catch (err) {
  if (err instanceof DOMException && err.name === 'AbortError') {
    return; // Superseded by newer input or navigation
  }
  if (err instanceof DOMException && err.name === 'TimeoutError') {
    showRetryBanner('Search timed out. Try again.');
    return;
  }
  throw err;
}

Keep in mind that client-side cancellation is not a server transaction rollback. Once a mutating POST reaches your backend, aborting fetch() only drops the client socket unless the server explicitly listens to request close signals and aborts downstream work.

Avoiding the Custom Listener and Long-Timer Trap

Native signal composition cleans up fetch(), yet two lifecycle traps still bite when you adapt custom APIs or run high-concurrency Node.js services.

First, AbortSignal.timeout() provides no clearTimeout() equivalent. Completing a request in 30 milliseconds—or aborting callerSignal inside AbortSignal.any()—does not cancel the underlying timer early. When only native fetch() consumes the signal, an idle short timer costs very little. However, if you attach your own abort listener to adapt a legacy callback or third-party SDK, an unremoved listener keeps both the pending timeout signal and your callback closure alive until the timer expires.

Whenever you subscribe manually to an AbortSignal, check throwIfAborted() upfront, pass { once: true }, and detach the listener inside finally:

export async function withAbort<T>(
  signal: AbortSignal,
  task: () => Promise<T>,
  cancelTask: () => void,
): Promise<T> {
  signal.throwIfAborted();
  const onAbort = () => cancelTask();
  signal.addEventListener('abort', onAbort, { once: true });

  try {
    return await task();
  } finally {
    signal.removeEventListener('abort', onAbort);
  }
}

Second, consider timer duration on busy backends. If a memory-constrained worker schedules thousands of five-minute timeouts per minute, uncancellable AbortSignal.timeout() timers linger in the runtime heap long after fast jobs finish. For multi-minute budgets under heavy load, pairing a dedicated AbortController with setTimeout() and calling clearTimeout() inside finally remains the right trade-off—and that manual controller still plugs cleanly into AbortSignal.any() alongside your caller's signal.

Sources

  1. developer.mozilla.org
  2. developer.mozilla.org
  3. nodejs.org
  4. dom.spec.whatwg.org

AI-assisted · Reviewed by PKN

0

Responses

Loading comments…