Skip to content
Source
Sign inSign up
TanStack/pacer
Open History to see the last commit

async-retrying.md

257 lines10.2 KB

1---
2title: React Async Retrying Guide
3id: async-retrying
4---
5​
6Retrying runs an async operation again after it fails. It can make transient failures less visible to users, but it can also repeat side effects and increase load on an unhealthy service.
7​
8> [!NOTE]
9> `AsyncRetryer` is an alpha API and may change before 1.0. Its current design also supports the retry behavior inside Pacer's other async utilities.
10​
11Retrying is the exception among these framework guides: TanStack Pacer does not provide a React-specific retry primitive. The adapter re-exports the public `asyncRetry` function and `AsyncRetryer` class, so this guide uses those APIs and connects long-lived instances to the React lifecycle.
12​
13If TanStack Query already owns the request, use its retry support so one system controls request state and cancellation.
14​
15## Decide whether retrying is safe
16​
17Retry only errors that are likely to succeed later, such as a temporary network failure, a rate-limit response, or some server errors. Validation, authentication, permission, and most other client errors usually need a code or user-input change instead.
18​
19`AsyncRetryer` retries every thrown error. It does not provide a `shouldRetry` predicate. Make the wrapped function throw only for retriable outcomes:
20​
21```ts
22async function loadUser(id: string) {
23 const response = await fetch(`/api/users/${id}`)
24​
25 if (response.status === 429 || response.status >= 500) {
26 throw new Error(`Temporary failure: ${response.status}`)
27 }
28​
29 if (!response.ok) {
30 return { ok: false as const, status: response.status }
31 }
32​
33 return { ok: true as const, user: await response.json() }
35```
36​
37Also consider whether repeating the operation is idempotent. Reads are commonly safe. Writes may create duplicate records, charges, messages, or other side effects when the first response is lost after the server completes the operation. Use idempotency keys or server-side deduplication before retrying such writes.
38​
39## Quick start
40​
41`asyncRetry` creates one retryer and returns its bound execution function:
42​
43```ts
44import { asyncRetry } from '@tanstack/react-pacer'
45​
46const loadUserWithRetry = asyncRetry(loadUser, {
47 maxAttempts: 3,
48 baseWait: 1000,
49 jitter: 0.2,
50})
51​
52try {
53 const result = await loadUserWithRetry('123')
54 console.log(result)
55} catch (error) {
56 console.error('All attempts failed:', error)
58```
59​
60The defaults are three total attempts, exponential backoff from 1000 milliseconds, no maximum delay, no jitter, and `throwOnError: 'last'`.
61​
62The returned function can be reused sequentially. It owns one `AsyncRetryer`, so starting a new call while an earlier call is active aborts the earlier retry flow. When calls may overlap, create a retryer per call or use another utility that manages concurrency:
63​
64```ts
65import { AsyncRetryer } from '@tanstack/react-pacer'
66​
67async function loadOneUser(id: string) {
68 const retryer = new AsyncRetryer(loadUser, { maxAttempts: 3 })
69 return retryer.execute(id)
71```
72​
73## Create one retryer per component
74​
75```tsx
76import { useEffect, useMemo } from 'react'
77import { AsyncRetryer } from '@tanstack/react-pacer'
78​
79function UserPanel({ id }: { id: string }) {
80 const retryer = useMemo(
81 () =>
82 new AsyncRetryer(loadUser, {
83 maxAttempts: 3,
84 baseWait: 1000,
85 jitter: 0.2,
86 backoff: 'exponential',
87 maxWait: 5000,
88 onRetry: (attempt, error) => {
89 console.log(`Attempt ${attempt} failed; retrying`, error)
90 },
91 onLastError: (error) => {
92 console.error('Attempts exhausted:', error)
93 },
94 }),
95 [],
96 )
97​
98 useEffect(() => () => retryer.abort(), [retryer])
99​
100 return <button onClick={() => void retryer.execute(id)}>Reload</button>
102```
103​
104Update `retryer.fn` when the function closes over changing props or state. Starting a second `execute()` on the same instance aborts its earlier retry flow. Create separate instances when executions may overlap.
105​
106Use a long-lived `AsyncRetryer` when you need callbacks, state, changing options, or manual abort control. `maxAttempts` includes the first call. A value of `1` disables retries while retaining result, error, timeout, callback, and abort behavior.
107​
108## Attempts and backoff
109​
110The first attempt starts immediately. A delay is calculated only after a failed attempt that has another attempt available.
111​
112With `baseWait: 1000`, the nominal delays are:
113​
114| Failed attempt | Exponential | Linear | Fixed |
115| -------------- | ----------: | ------: | ------: |
116| 1 | 1000 ms | 1000 ms | 1000 ms |
117| 2 | 2000 ms | 2000 ms | 1000 ms |
118| 3 | 4000 ms | 3000 ms | 1000 ms |
119| 4 | 8000 ms | 4000 ms | 1000 ms |
120​
121`maxWait` caps the nominal delay before jitter. `baseWait`, `maxWait`, and `maxAttempts` can also be functions that receive the retryer instance.
122​
123### Add jitter for shared services
124​
125Many clients can fail at the same time and otherwise retry in synchronized waves. `jitter` adds random variation above or below each nominal delay:
126​
127```ts
128const retryer = new AsyncRetryer(loadUser, {
129 maxAttempts: 4,
130 baseWait: 1000,
131 maxWait: 10_000,
132 jitter: 0.25,
133})
134```
135​
136Use a value from `0` to `1`, where `0.25` allows up to 25 percent variation. Because jitter is applied after `maxWait`, the final randomized delay can be slightly greater than `maxWait`.
137​
138## Errors and callbacks
139​
140The error callbacks serve different levels of the retry lifecycle:
141​
142- `onError(error, args, retryer)` runs for every failed attempt.
143- `onRetry(attempt, error, retryer)` runs after a failed attempt when another attempt remains. `attempt` is the number that just failed.
144- `onLastError(error, retryer)` runs after all attempts fail.
145- `onSuccess(result, args, retryer)` runs once after a successful attempt.
146- `onSettled(args, retryer)` runs as attempts settle.
147​
148`throwOnError` controls the final failed result:
149​
150- `'last'`, the default, rejects with the final error after all attempts fail.
151- `true` also runs the configured attempts, then rejects with the final error.
152- `false` resolves with `undefined` after all attempts fail.
153​
154Providing `onError` changes the default `throwOnError` value to `false`. Set it explicitly if you want both observation and rejection:
155​
156```ts
157const retryer = new AsyncRetryer(loadUser, {
158 onError: (error) => reportError(error),
159 throwOnError: 'last',
160})
161```
162​
163An `AbortError` thrown by the wrapped function is treated as cancellation. It resolves with `undefined` without consuming further attempts or calling `onAbort` automatically.
164​
165## Timeouts
166​
167Two independent options limit retry work:
168​
169- `maxExecutionTime` sets a deadline for one attempt.
170- `maxTotalExecutionTime` sets a deadline for the complete call, including attempts and backoff waits.
171​
172```ts
173const retryer = new AsyncRetryer(loadUser, {
174 maxAttempts: 4,
175 maxExecutionTime: 5000,
176 maxTotalExecutionTime: 15_000,
177 onExecutionTimeout: () => console.warn('Attempt timed out'),
178 onTotalExecutionTimeout: () => console.warn('Retry operation timed out'),
179})
180```
181​
182A timeout aborts the retry flow. `onAbort` receives either `'execution-timeout'` or `'total-timeout'`. A total timeout normally resolves with `undefined`. A per-attempt timeout can reject with its final timeout or abort error when `throwOnError` is enabled, and resolves with `undefined` when error throwing is disabled.
183​
184JavaScript cannot forcibly stop an arbitrary Promise. A timeout prevents Pacer from continuing the retry flow, but the underlying operation stops only if it cooperates with the abort signal.
185​
186## Aborting the underlying operation
187​
188Call `getAbortSignal()` from the wrapped function and pass the signal to an API that supports it:
189​
190```ts
191const retryer = new AsyncRetryer(
192 async (url: string) => {
193 const response = await fetch(url, {
194 signal: retryer.getAbortSignal() ?? undefined,
195 })
196 if (!response.ok) throw new Error(`Request failed: ${response.status}`)
197 return response.json()
198 },
199 { maxAttempts: 3 },
201​
202const request = retryer.execute('/api/data')
203retryer.abort()
204await request // undefined
205```
206​
207`abort()` stops the active retry flow and pending backoff. `onAbort` receives `'manual'`. Starting another `execute()` on the same instance aborts the earlier flow with `'new-execution'`.
208​
209Without passing the signal to the operation, `abort()` prevents later retry work but the active Promise may continue running in the background.
210​
211## Resetting and changing options
212​
213`setOptions()` merges new options into the current configuration. It does not restart an active execution.
214​
215`reset()` restores default state only. It does not abort active work:
216​
217```ts
218retryer.abort()
219retryer.reset()
220```
221​
222Use `asyncRetryerOptions()` to define reusable, type-checked option objects:
223​
224```ts
225const networkRetryOptions = asyncRetryerOptions({
226 maxAttempts: 3,
227 backoff: 'exponential',
228 baseWait: 1000,
229 jitter: 0.2,
230})
231```
232​
233## State
234​
235The retryer stores state at `retryer.store`.
236​
237To restore selected state that your app has persisted, pass a partial snapshot through `initialState`. It is merged with the defaults. Restore only durable fields. Pending timers and active executions are not restored.
238​
239Commonly useful properties include:
240​
241- `currentAttempt`: The current or most recently started attempt number. It returns to `0` after success or reset.
242- `isExecuting`: Whether a retry flow is active.
243- `lastError`: The most recent failed attempt's error.
244- `lastResult`: The most recent successful result.
245- `executionCount`: Successful top-level executions, not individual attempts.
246- `lastExecutionTime` and `totalExecutionTime`: Timing recorded for the most recent success.
247- `status`: `'disabled'`, `'idle'`, `'executing'`, or `'retrying'`.
248​
249`AsyncRetryer` does not expose a React state selector. Use its callbacks to copy the fields needed by the view into React state. If you subscribe to `retryer.store` directly, register the unsubscribe function with the same component or owner cleanup that aborts the retryer.
250​
251For exact signatures, see the [`asyncRetry` function reference](../../../reference/functions/asyncRetry.md), [`AsyncRetryer` class reference](../../../reference/classes/AsyncRetryer.md), and [`AsyncRetryerOptions` reference](../../../reference/interfaces/AsyncRetryerOptions.md).
252​
253## Related docs
254​
255- [React quick start](../quick-start.md)
256- [Choose a Pacer utility](../../../guides/which-pacer-utility-should-i-choose.md)
257- [Select another framework](../../../guides/async-retrying.md)