Retries and Cancellation

Purpose and Scope

Retries and cancellation are part of TanStack Query's server-state lifecycle: a query function starts asynchronous work, the cache observes that work, retry policy can decide whether failed work should be attempted again, and cancellation can stop work that is no longer useful. The official product framing describes Query as giving asynchronous data a cache, lifecycle, and declarative APIs for fetching, sharing, refetching, mutating, and observing server state. In practice, this page helps you connect that lifecycle to framework code, especially Angular Query, where query functions are promise-based and are provided through Angular dependency injection.

Sources: docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md, docs/framework/angular/reference/functions/provideTanStackQuery.md

The supplied source evidence for this page is centered on Angular Query rather than the core retry implementation. That means the most concrete repository-backed guidance here is about where retry and cancellation policy attaches: create or provide a QueryClient, define promise-returning queryFn functions, surface active background work through fetching indicators, and inspect query and mutation behavior with devtools. The retry and cancellation concepts apply across TanStack Query adapters, while the examples below use Angular APIs because those are the relevant source files available for this page.

Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md, docs/framework/angular/guides/background-fetching-indicators.md, docs/framework/angular/devtools.md

Relevant Source Files

  • docs/framework/angular/reference/functions/provideTanStackQuery.md - documents provideTanStackQuery(queryClient, ...features): Provider[], showing where an Angular app installs a QueryClient and optional features such as devtools.
  • docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md - explains that TanStack Query fetching is promise-based and can use fetch, graphql-request, Angular HttpClient, or other asynchronous clients; it also shows converting Angular observables with lastValueFrom.
  • docs/framework/angular/guides/background-fetching-indicators.md - shows injectQuery, isPending, isError, isSuccess, isFetching, and injectIsFetching, which are the user-visible signals that expose retrying or refetching work as background activity.
  • docs/framework/angular/devtools.md - documents withDevtools, browser-extension alternatives, and development or production loading behavior for inspecting queries and mutations.
  • docs/community-resources.md - lists external utilities and learning resources, including tools for generated clients, request batching, query-key factories, and related best-practice material.
  • docs/config.json - places framework docs, quick starts, devtools, TypeScript, GraphQL, React Native, and other framework sections in the first-party documentation navigation.

Core Primitives

A retry is a decision to run the same failed query function again according to the query's retry policy. A retry delay is the wait time between those attempts. Cancellation is the act of abandoning in-flight query work when the result is no longer needed, for example because an observer unsubscribed, a component moved on to a different key, or the app intentionally cancelled work. These primitives are not separate data-fetching clients; they are lifecycle behaviors around promise-returning query functions. The actual transport may be browser fetch, Angular HttpClient, GraphQL clients, generated OpenAPI clients, or another promise-producing API.

Sources: docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md, docs/community-resources.md

The central application primitive is the QueryClient. In Angular, provideTanStackQuery accepts either a QueryClient instance or an InjectionToken that provides one, and returns Angular providers. That placement matters because retry defaults and cancellation-capable fetch behavior are normally established at the client or query-option boundary, not inside a global store reducer. The same reference also shows optional feature registration with withDevtools, making the provider layer the place where the app wires Query itself plus observability tools for diagnosing failed, retrying, or cancelled work.

Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md, docs/framework/angular/devtools.md

import { QueryClient, provideTanStackQuery } from '@tanstack/angular-query-experimental'
 
bootstrapApplication(AppComponent, {
  providers: [provideTanStackQuery(new QueryClient())],
})

A query function, or queryFn, is the function TanStack Query invokes to produce data for a query key. The Angular data-fetching guide is explicit that Query's fetching mechanisms are built agnostically on promises, so any asynchronous data-fetching client can participate. When the client is Angular HttpClient, its observables must be converted to promises with lastValueFrom or firstValueFrom. That conversion boundary is important for cancellation design: the query function is where you choose a client that can stop or ignore obsolete requests and where you adapt framework-native async types to Query's promise contract.

Sources: docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md

Execution Flow

A typical retryable query starts when a component creates an observer with injectQuery. The example background-fetching guide defines a todosQuery with queryKey: ['todos'] and queryFn: fetchTodos, then renders separate UI for pending, error, success, and fetching states. This is the reader-facing lifecycle: pending means no successful data is available yet, error means the query reached an error state, success means data is available, and isFetching can still become true while data remains on screen during a background attempt. Retries and refetches are therefore observable without replacing the whole UI with a loading state.

Sources: docs/framework/angular/guides/background-fetching-indicators.md

readonly query = injectQuery(() => ({
  queryKey: ['repoData'],
  queryFn: () =>
    lastValueFrom(
      this.http.get('https://api.github.com/repos/tanstack/query'),
    ),
}))

When a request fails, TanStack Query can retry according to the policy configured for that query or client. From the component's point of view, that retry is still part of the same query lifecycle. If previous data exists, a background retry or refetch can leave successful data rendered while isFetching indicates that more network work is happening. If no data exists and attempts are still pending, the component can render a pending state. This separation is why the Angular background-fetching example checks isPending, isError, isSuccess, and then isFetching inside the success branch.

Sources: docs/framework/angular/guides/background-fetching-indicators.md

Cancellation belongs in the same flow because obsolete work should not always be allowed to update the cache. A cancellation-aware query function should pass along whatever cancellation mechanism its transport understands. With browser fetch, that usually means using the query function's abort signal. With Angular HttpClient, the available source page focuses on converting observables to promises and does not document a Query-specific observable cancellation adapter, so Angular users should be deliberate about how their chosen conversion and client handle teardown. The practical rule is to keep cancellation at the query-function boundary, where transport-specific behavior is visible.

Sources: docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md

API Components and Options Reference

The concrete Angular provider entry point is provideTanStackQuery(queryClient, ...features): Provider[]. Its first parameter is a QueryClient instance or an InjectionToken<QueryClient>, and its remaining parameters are optional QueryFeatures. The documented examples cover standalone bootstrapping, NgModule-based applications, and lazy-loaded usage through an injection token. For retry and cancellation work, this gives you a stable integration point: provide the client once, keep query options close to the query or shared option factory, and avoid duplicating retry decisions across unrelated components.

Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md

ComponentSource-backed contractRetry or cancellation relevance
QueryClientPassed to provideTanStackQuery or provided by InjectionTokenOwns application-level Query behavior and is the natural home for shared defaults
injectQueryCreates a query from options including queryKey and queryFnStarts the promise-producing work that may retry, refetch, or be cancelled
queryFnAny promise-returning fetcher; Angular observables need lastValueFrom or firstValueFromBoundary where transport-specific abort or teardown behavior must be implemented
isFetchingQuery-level signal shown in Angular templatesIndicates active work, including background refetches or retry attempts
injectIsFetchingGlobal fetching-count signalPowers app-wide loading indicators during background activity
withDevtoolsOptional feature passed to provideTanStackQueryHelps inspect queries and mutations while diagnosing retries, failures, and stale work

The background-fetching guide also documents injectIsFetching, which returns a signal suitable for global loading indicators. This is useful when retries happen outside the immediate component that started a query. A header, route shell, or status bar can show that queries are fetching in the background without knowing which individual query is active. That pattern is especially helpful when retry delays make failures intermittent: the user can keep interacting with already-rendered data while the app communicates that Query is still attempting to synchronize with the server.

Sources: docs/framework/angular/guides/background-fetching-indicators.md

Debugging and Observability

Devtools are the main first-party debugging surface for seeing how queries and mutations behave at runtime. The Angular devtools page says they help debug and inspect queries and mutations, can be enabled by adding withDevtools to provideTanStackQuery, and are included only in development mode bundles by default. For retry and cancellation issues, that means you should first reproduce the behavior with devtools enabled, inspect the query key and current state, and compare what the component renders against the cache activity visible in the tool.

Sources: docs/framework/angular/devtools.md, docs/framework/angular/reference/functions/provideTanStackQuery.md

The same devtools source documents production and lazy-loading options. The default loadDevtools: 'auto' behavior loads automatically only when Angular runs in development mode, while the production subpath can be used when a staging or production-like environment needs inspection. This matters for retry bugs because they often depend on network conditions, authentication interceptors, SSR behavior, or deployed API gateways. If you must debug outside local development, use the documented production subpath intentionally and gate loading through an environment flag or signal-derived option.

Sources: docs/framework/angular/devtools.md

Community resources can supplement debugging when the issue is not the Query lifecycle itself but the surrounding client architecture. The community page lists utilities such as request batching, GraphQL code generation, OpenAPI client generation, query-key factories, reusable hook kits, and state visualization tools. Those resources are not replacements for Query's retry and cancellation contract, but they can influence where failures originate. For example, a generated client may need to expose abort support, while a batching layer may need to decide what cancellation means for a request shared by multiple callers.

Sources: docs/community-resources.md

Implementation Guidance

Prefer small, deterministic query functions that forward cancellation to the underlying transport when possible and throw meaningful errors when retries should be considered. Keep query keys stable and descriptive so repeated attempts target the same cache entry rather than creating accidental parallel work. Use isFetching for non-blocking background activity, not only for initial page loading. If the transport is Angular HttpClient, document the observable-to-promise conversion in the query function so future maintainers understand where Angular integration ends and Query's promise lifecycle begins.

Sources: docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md, docs/framework/angular/guides/background-fetching-indicators.md

When deciding whether to retry, separate transient failures from deterministic failures. Network interruptions, temporary service errors, and race conditions during focus or reconnect flows are retry candidates; invalid input, authorization failures, and missing resources may be better surfaced immediately. The supplied docs do not include a source-level retry option reference, so treat this as design guidance rather than a file-backed list of defaults. The source-backed action is to centralize shared policy around the provided QueryClient and keep per-query exceptions near the queryFn that understands the API endpoint.

Sources: docs/framework/angular/reference/functions/provideTanStackQuery.md, docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md

Testing Signals and Next Steps

For testing, focus on the same boundaries users experience: the query function returns a promise, the component reacts to pending/error/success/fetching states, and app-level indicators reflect global fetch activity. The Angular HttpClient guide highlights integration benefits such as mock responses in unit tests, interceptors, pending-task awareness, and SSR request caching. Those features can make retry and cancellation tests more realistic because the client participates in Angular's dependency injection, testing, and stability systems instead of hiding network behavior behind unrelated global state.

Sources: docs/framework/angular/angular-httpclient-and-other-data-fetching-clients.md

Next, read the pages on Queries, Background Refetching, Network Mode, QueryClient Reference, and the Angular Functions Reference. Together they fill in the broader lifecycle around observer creation, online/offline execution, cache updates, default options, and framework-specific APIs. If you are working in Angular, start with provideTanStackQuery, add devtools during development, convert HttpClient observables carefully in queryFn, and expose isFetching or injectIsFetching where users need to understand that retry or refetch work is still happening.