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

AsyncRetryer.md

315 lines9.2 KB

1---
2id: AsyncRetryer
3title: AsyncRetryer
4---
5​
6Defined in: [async-retryer.ts:298](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L298)
7​
8Provides robust retry functionality for asynchronous functions, supporting configurable backoff strategies,
9attempt limits, timeout controls, and detailed state management. The AsyncRetryer class is designed to help you reliably
10execute async operations that may fail intermittently, such as network requests or database operations,
11by automatically retrying them according to your chosen policy.
12​
13## Retrying Concepts
14​
15- **Retrying**: Automatically re-executes a failed async function up to a specified number of attempts.
16 Useful for handling transient errors (e.g., network flakiness, rate limits, temporary server issues).
17- **Backoff Strategies**: Controls the delay between retry attempts (default: `'exponential'`):
18 - `'exponential'`: Wait time doubles with each attempt (1s, 2s, 4s, ...) - **DEFAULT**
19 - `'linear'`: Wait time increases linearly (1s, 2s, 3s, ...)
20 - `'fixed'`: Waits a constant amount of time (`baseWait`) between each attempt
21- **Jitter**: Adds randomness to retry delays to prevent thundering herd problems (default: `0`).
22 Set to a value between 0-1 to apply that percentage of random variation to each delay.
23- **Max Wait**: Caps the maximum wait time between retries (default: `Infinity`).
24 Useful for preventing exponential backoff from growing too large (e.g., cap at 30s even if exponential would be 64s).
25- **Timeout Controls**: Set limits on execution time to prevent hanging operations:
26 - `maxExecutionTime`: Maximum time for a single function call (default: `Infinity`)
27 - `maxTotalExecutionTime`: Maximum time for the entire retry operation (default: `Infinity`)
28- **Abort & Cancellation**: Supports cancellation via an internal `AbortController`. Call `abort()` to stop retries.
29 Use `getAbortSignal()` to make your async function actually cancellable (e.g., with fetch requests).
30​
31## State Management
32​
33Uses TanStack Store for fine-grained reactivity. State can be accessed via the `store.state` property.
34​
35Available state properties:
36- `currentAttempt`: The current retry attempt number (0 when not executing)
37- `executionCount`: Total number of completed executions (successful or failed)
38- `isExecuting`: Whether the retryer is currently executing the function
39- `lastError`: The most recent error encountered during execution
40- `lastExecutionTime`: Timestamp of the last execution completion in milliseconds
41- `lastResult`: The result from the most recent successful execution
42- `status`: Current execution status ('disabled' | 'idle' | 'executing' | 'retrying')
43- `totalExecutionTime`: Total time spent executing (including retries) in milliseconds
44​
45## Error Handling
46​
47The `throwOnError` option controls when errors are thrown (default: `'last'`):
48- `'last'`: Only throws the final error after all retries are exhausted - **DEFAULT**
49- `true`: Throws every error immediately (disables retrying)
50- `false`: Never throws errors, returns `undefined` instead
51​
52Callbacks for lifecycle management:
53- `onAbort`: Called when execution is aborted (manually or due to timeouts)
54- `onError`: Called for every error (including during retries)
55- `onLastError`: Called only for the final error after all retries fail
56- `onRetry`: Called before each retry attempt
57- `onSettled`: Called after execution completes (success or failure) of each attempt
58- `onSuccess`: Called when execution succeeds
59- `onExecutionTimeout`: Called when a single execution attempt times out
60- `onTotalExecutionTimeout`: Called when the total execution time times out
61​
62## Usage
63​
64- Use for async operations that may fail transiently and benefit from retrying.
65- Configure `maxAttempts`, `backoff`, `baseWait`, `maxWait`, and `jitter` to control retry behavior.
66- Set `maxExecutionTime` and `maxTotalExecutionTime` to prevent hanging operations.
67- Use `onAbort`, `onError`, `onLastError`, `onRetry`, `onSettled`, `onSuccess`, `onExecutionTimeout`, and `onTotalExecutionTimeout` for custom side effects.
68- Call `abort()` to cancel ongoing execution and pending retries.
69- Call `reset()` to reset state and cancel execution.
70- Use `getAbortSignal()` to make your async function cancellable.
71- Use dynamic options (functions) for `maxAttempts`, `baseWait`, and `enabled` based on retryer state.
72​
73**Important:** This class is designed for single-use execution. Calling `execute()` multiple times
74on the same instance will abort previous executions. For multiple calls, create a new instance
75each time.
76​
77## Example
78​
79```typescript
80// Retry a fetch operation up to 5 times with exponential backoff, jitter, and timeouts
81const retryer = new AsyncRetryer(async (url: string) => {
82 const signal = retryer.getAbortSignal()
83 return await fetch(url, { signal })
84}, {
85 maxAttempts: 5,
86 backoff: 'exponential',
87 baseWait: 1000,
88 jitter: 0.1, // Add 10% random variation to prevent thundering herd
89 maxExecutionTime: 5000, // Abort individual calls after 5 seconds
90 maxTotalExecutionTime: 30000, // Abort entire operation after 30 seconds
91 onRetry: (attempt, error) => console.log(`Retry attempt ${attempt} after error:`, error),
92 onSuccess: (result) => console.log('Success:', result),
93 onError: (error) => console.error('Error:', error),
94 onLastError: (error) => console.error('All retries failed:', error),
95})
96​
97const result = await retryer.execute('/api/data')
98```
99​
100## Type Parameters
101​
102### TFn
103​
104`TFn` *extends* [`AnyAsyncFunction`](../type-aliases/AnyAsyncFunction.md)
105​
106The async function type to be retried.
107​
108## Constructors
109​
110### Constructor
111​
112```ts
113new AsyncRetryer<TFn>(fn, initialOptions?): AsyncRetryer<TFn>;
114```
115​
116Defined in: [async-retryer.ts:311](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L311)
117​
118Creates a new AsyncRetryer instance
119​
120#### Parameters
121​
122##### fn
123​
124`TFn`
125​
126The async function to retry
127​
128##### initialOptions?
129​
130[`AsyncRetryerOptions`](../interfaces/AsyncRetryerOptions.md)\<`TFn`\> = `{}`
131​
132Configuration options for the retryer
133​
134#### Returns
135​
136`AsyncRetryer`\<`TFn`\>
137​
138## Properties
139​
140### fn
141​
142```ts
143fn: TFn;
144```
145​
146Defined in: [async-retryer.ts:312](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L312)
147​
148The async function to retry
149​
150***
151​
152### key
153​
154```ts
155key: string | undefined;
156```
157​
158Defined in: [async-retryer.ts:302](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L302)
159​
160***
161​
162### options
163​
164```ts
165options: AsyncRetryerOptions<TFn> & Omit<Required<AsyncRetryerOptions<any>>,
166 | "initialState"
167 | "key"
168 | "onAbort"
169 | "onError"
170 | "onLastError"
171 | "onRetry"
172 | "onSettled"
173 | "onSuccess"
174 | "onExecutionTimeout"
175| "onTotalExecutionTimeout">;
176```
177​
178Defined in: [async-retryer.ts:303](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L303)
179​
180***
181​
182### store
183​
184```ts
185readonly store: Store<Readonly<AsyncRetryerState<TFn>>>;
186```
187​
188Defined in: [async-retryer.ts:299](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L299)
189​
190## Methods
191​
192### abort()
193​
194```ts
195abort(reason?): void;
196```
197​
198Defined in: [async-retryer.ts:612](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L612)
199​
200Cancels the current execution and any pending retries
201​
202#### Parameters
203​
204##### reason?
205​
206`"manual"` \| `"execution-timeout"` \| `"total-timeout"` \| `"new-execution"`
207​
208The reason for the abort (defaults to 'manual')
209​
210#### Returns
211​
212`void`
213​
214***
215​
216### execute()
217​
218```ts
219execute(...args): Promise<Awaited<ReturnType<TFn>> | undefined>;
220```
221​
222Defined in: [async-retryer.ts:419](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L419)
223​
224Executes the function with retry logic
225​
226#### Parameters
227​
228##### args
229​
230...`Parameters`\<`TFn`\>
231​
232Arguments to pass to the function
233​
234#### Returns
235​
236`Promise`\<`Awaited`\<`ReturnType`\<`TFn`\>\> \| `undefined`\>
237​
238The function result, or undefined if disabled or all retries failed (when throwOnError is false)
239​
240#### Throws
241​
242The last error if throwOnError is true and all retries fail
243​
244***
245​
246### getAbortSignal()
247​
248```ts
249getAbortSignal(): AbortSignal | null;
250```
251​
252Defined in: [async-retryer.ts:604](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L604)
253​
254Returns the current AbortSignal for the executing operation.
255Use this signal in your async function to make it cancellable.
256Returns null when not currently executing.
257​
258#### Returns
259​
260`AbortSignal` \| `null`
261​
262#### Example
263​
264```typescript
265const retryer = new AsyncRetryer(async (userId: string) => {
266 const signal = retryer.getAbortSignal()
267 if (signal) {
268 return fetch(`/api/users/${userId}`, { signal })
269 }
270 return fetch(`/api/users/${userId}`)
271})
272​
273// Abort will now actually cancel the fetch
274retryer.abort()
275```
276​
277***
278​
279### reset()
280​
281```ts
282reset(): void;
283```
284​
285Defined in: [async-retryer.ts:632](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L632)
286​
287Resets the retryer to its initial state
288​
289#### Returns
290​
291`void`
292​
293***
294​
295### setOptions()
296​
297```ts
298setOptions(newOptions): void;
299```
300​
301Defined in: [async-retryer.ts:330](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-retryer.ts#L330)
302​
303Updates the retryer options
304​
305#### Parameters
306​
307##### newOptions
308​
309`Partial`\<[`AsyncRetryerOptions`](../interfaces/AsyncRetryerOptions.md)\<`TFn`\>\>
310​
311Partial options to merge with existing options
312​
313#### Returns
314​
315`void`