Skip to content

Cancellation and Recovery

A navigation can make a request unnecessary, while a slow request may need replacing. Cancellation in Query is scoped to a key’s shared pending request, not to one caller’s interest in its result. Cancel only when every consumer sharing that request may lose it.

This guide assumes a stable query instance and a fetcher that forwards its supplied signal to the underlying I/O, as in data fetching.

Abort one key, several keys, or all tracked fetches in the instance:

query.abort('/profile.json', new Error('profile request no longer needed'))
query.abort(['/api/profiles/1', '/api/profiles/2'])
query.abort()

abort() returns void. It signals the selected controllers, removes their resolver entries, and emits aborted with the supplied reason. It does not delete cached values, stop mutation queues, or remove fresh render selections. Use forgetting separately when you also need to discard data or invalidate a selected resource.

The caller’s promise does not necessarily settle when abort() returns. Prompt cancellation depends on the fetcher honoring signal. If a fetcher ignores cancellation and eventually resolves, Query rejects that result with the signal’s abort reason rather than caching it. If the fetcher itself rejects, its rejection remains visible to its caller. If it never settles, existing callers can remain pending even though later requests may start.

Attach rejection handling before you trigger cancellation, especially with shared or fire-and-forget work:

const outcome = query.query('/profile.json').catch((error: unknown) => {
console.info('Profile request ended:', error)
})
query.abort('/profile.json', new Error('navigation changed'))
await outcome

This example intentionally treats failure as a logged outcome. In an interactive view, distinguish cancellation from a genuine load failure according to your application’s error policy.

Replace a request without accepting late writes

Section titled “Replace a request without accepting late writes”

query.query(key, { fresh: true }) performs the abort-and-replace sequence for that key. Only the current request owner may publish to the cache or emit completion events. Late completion of an obsolete request cannot remove the replacement’s resolver or overwrite its result.

Ownership protects shared state, not each caller’s business logic. A caller awaiting an obsolete request can still receive a result or error and must decide whether its own screen or workflow still needs it. A committed mutation or hydration also revokes an older fetch’s publication rights without canceling its transport.

Unmounting a React reader or provider does not automatically abort shared work. That allows other readers and later mounts to reuse it. If you add teardown cancellation yourself, own the instance or otherwise ensure you are not canceling work another consumer still needs.

Retry where the transport knows what failed

Section titled “Retry where the transport knows what failed”

There is no retry, retryDelay, or request-timeout option in Query. An ordinary failed read rejects; a later read can try again. For automatic retries, put a bounded policy inside your fetcher, where it can classify transport and HTTP failures.

This complete fetcher retries an idempotent JSON GET once, immediately, only for HTTP 503. It does not retry other status codes, network failures, malformed JSON, or cancellation:

import { createQuery, type FetcherAdditional } from '@studiolambda/query'
/** Retries one temporary HTTP 503 response without retrying arbitrary failures. */
async function fetchWithOneRetry(key: string, { signal }: FetcherAdditional): Promise<unknown> {
for (let attempt = 0; attempt < 2; attempt += 1) {
signal.throwIfAborted()
const response = await fetch(key, { signal })
if (response.status === 503 && attempt === 0) {
await response.body?.cancel()
continue
}
if (!response.ok) throw new Error(`request failed: ${response.status}`)
return response.json()
}
throw new Error('retry attempts exhausted')
}
/** Deduplicated callers share the whole retrying operation. */
const query = createQuery({ fetcher: fetchWithOneRetry })

There are at most two HTTP attempts: one initial attempt and one retry. Query sees them as one pending operation and emits its completion/error only after that fetcher settles. For production backoff, choose a delay and jitter policy, release unused response bodies, and make waits abortable. Do not retry server writes without an idempotency strategy: a lost response does not prove the first write was rejected.

For a timeout, compose the query signal with an application-owned deadline in the fetcher, using APIs supported by your target runtime. Keep the original query signal in the composition so replacement and explicit abort still reach the I/O. A timeout is a fetcher failure, not a separate built-in Query lifecycle.

once(key, event, signal) and next(keys, signal) accept a caller-owned AbortSignal. That signal cleans up their event-listener wait and rejects with signal.reason; it does not call query.abort().

Once next() has received a refetching event, it awaits the promise in that event. Aborting its listener signal then does not cancel that already-received fetch promise. Use event subscriptions when you need to coordinate observations without taking ownership of the underlying request.