diff --git a/.changeset/retry-delay-jitter.md b/.changeset/retry-delay-jitter.md new file mode 100644 index 00000000000..2d05b2b8cb7 --- /dev/null +++ b/.changeset/retry-delay-jitter.md @@ -0,0 +1,5 @@ +--- +'@tanstack/query-core': major +--- + +Add bounded jitter to the default retry delay for queries and mutations. Each retry waits a random duration from 80% to 100% of the exponential backoff delay, up to 30 seconds. diff --git a/docs/framework/angular/guides/query-retries.md b/docs/framework/angular/guides/query-retries.md index e19c8f85a37..c55a4962b24 100644 --- a/docs/framework/angular/guides/query-retries.md +++ b/docs/framework/angular/guides/query-retries.md @@ -26,34 +26,6 @@ const todoQuery = injectQuery(() => ({ ``` [//]: # 'Example' -[//]: # 'Example2' - -```ts -// Configure for all queries -import { - QueryCache, - QueryClient, - QueryClientProvider, -} from '@tanstack/angular-query' - -const createQueryClient = () => - new QueryClient({ - defaultOptions: { - queries: { - retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000), - }, - }, - }) - -bootstrapApplication(AppComponent, { - providers: [provideTanStackQuery(createQueryClient)], -}) -``` - -[//]: # 'Example2' - -Though it is not recommended, you can obviously override the `retryDelay` function/integer in both the Provider and individual query options. If set to an integer instead of a function the delay will always be the same amount of time: - [//]: # 'Example3' ```ts diff --git a/docs/framework/react/guides/important-defaults.md b/docs/framework/react/guides/important-defaults.md index 68277f9c399..e8b091eeb95 100644 --- a/docs/framework/react/guides/important-defaults.md +++ b/docs/framework/react/guides/important-defaults.md @@ -30,7 +30,7 @@ Out of the box, TanStack Query is configured with **aggressive but sane** defaul > To change this, you can alter the default `gcTime` for queries to something other than `5 * 60 * 1000` milliseconds. -- Queries that fail are **silently retried 3 times, with exponential backoff delay** before capturing and displaying an error to the UI. +- Queries that fail are **silently retried 3 times, with exponential backoff and jitter** before capturing and displaying an error to the UI. > To change this, you can alter the default `retry` and `retryDelay` options for queries to something other than `3` and the default exponential backoff function. diff --git a/docs/framework/react/guides/mutations.md b/docs/framework/react/guides/mutations.md index 19aa7c1ea6d..def2dba1032 100644 --- a/docs/framework/react/guides/mutations.md +++ b/docs/framework/react/guides/mutations.md @@ -280,6 +280,8 @@ const mutation = useMutation({ [//]: # 'Example9' +When you enable mutation retries, they use the same default delay as query retries. Set `retryDelay` to use a custom delay. + If mutations fail because the device is offline, they will be retried in the same order when the device reconnects. ## Persist mutations diff --git a/docs/framework/react/guides/query-retries.md b/docs/framework/react/guides/query-retries.md index 08e2fbab265..1bea6d0a0b0 100644 --- a/docs/framework/react/guides/query-retries.md +++ b/docs/framework/react/guides/query-retries.md @@ -36,36 +36,20 @@ const result = useQuery({ ## Retry Delay -By default, retries in TanStack Query do not happen immediately after a request fails. As is standard, a back-off delay is gradually applied to each retry attempt. +By default, each retry waits a random duration from 80% to 100% of the base delay. This jitter spreads out retries when many requests fail at the same time. -The default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds: +The base delay starts at 1 second and doubles for each retry, up to 30 seconds. -[//]: # 'Example2' +| Retry | Delay range | Average delay | +| ----------- | ----------- | ------------- | +| 1 | 0.8–1 s | 0.9 s | +| 2 | 1.6–2 s | 1.8 s | +| 3 | 3.2–4 s | 3.6 s | +| 4 | 6.4–8 s | 7.2 s | +| 5 | 12.8–16 s | 14.4 s | +| 6 and later | 24–30 s | 27 s | -```tsx -// Configure for all queries -import { - QueryCache, - QueryClient, - QueryClientProvider, -} from '@tanstack/react-query' - -const queryClient = new QueryClient({ - defaultOptions: { - queries: { - retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000), - }, - }, -}) - -function App() { - return ... -} -``` - -[//]: # 'Example2' - -Though it is not recommended, you can obviously override the `retryDelay` function/integer in both the Provider and individual query options. If set to an integer instead of a function the delay will always be the same amount of time: +Set `retryDelay` in the query client's default query options or in the options for one query. Use a number for a fixed delay in milliseconds or a function to calculate the delay for each retry. [//]: # 'Example3' diff --git a/docs/framework/svelte/guides/query-retries.md b/docs/framework/svelte/guides/query-retries.md index a57e32170d8..06c97e66d1f 100644 --- a/docs/framework/svelte/guides/query-retries.md +++ b/docs/framework/svelte/guides/query-retries.md @@ -31,26 +31,6 @@ replace: ``` [//]: # 'Example' -[//]: # 'Example2' - -```svelte - - -... -``` - -[//]: # 'Example2' [//]: # 'Example3' ```svelte diff --git a/docs/framework/vue/guides/query-retries.md b/docs/framework/vue/guides/query-retries.md index 33163b5e3a4..5804270f898 100644 --- a/docs/framework/vue/guides/query-retries.md +++ b/docs/framework/vue/guides/query-retries.md @@ -19,21 +19,3 @@ const result = useQuery({ ``` [//]: # 'Example' -[//]: # 'Example2' - -```ts -import { VueQueryPlugin } from '@tanstack/vue-query' - -const vueQueryPluginOptions = { - queryClientConfig: { - defaultOptions: { - queries: { - retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000), - }, - }, - }, -} -app.use(VueQueryPlugin, vueQueryPluginOptions) -``` - -[//]: # 'Example2' diff --git a/packages/query-core/src/__tests__/retryer.test.tsx b/packages/query-core/src/__tests__/retryer.test.tsx index 7368d8777eb..a36adde9342 100644 --- a/packages/query-core/src/__tests__/retryer.test.tsx +++ b/packages/query-core/src/__tests__/retryer.test.tsx @@ -108,29 +108,36 @@ describe('createRetryer', () => { expect(fn).toHaveBeenCalledTimes(2) }) - it('should use the default exponential backoff capped at 30 seconds', async () => { - const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout') - let calls = 0 - const fn = vi.fn<() => Promise>().mockImplementation(() => { - calls++ - return calls < 7 - ? Promise.reject(new Error('failed')) - : Promise.resolve('success') - }) - const retryer = createRetryer({ - fn, - retry: true, - networkMode: 'online', - canRun: () => true, - }) + it('should use 80% to 100% of the default backoff delay, including at the cap', async () => { + const random = vi.spyOn(Math, 'random').mockReturnValue(0) + for (const value of [0, 0.99999, 0.5, 0.5, 0.5, 0.99999]) { + random.mockReturnValueOnce(value) + } + + try { + const delays: Array = [] + let lastAttemptTime = Date.now() + const retryer = createRetryer({ + fn: () => { + const now = Date.now() + delays.push(now - lastAttemptTime) + lastAttemptTime = now + throw new Error('failed') + }, + retry: 7, + networkMode: 'online', + canRun: () => true, + }) - const promise = retryer.start() - await vi.advanceTimersByTimeAsync(100000) - await expect(promise).resolves.toBe('success') - const delays = setTimeoutSpy.mock.calls - .filter((call) => typeof call[1] === 'number') - .map((call) => call[1]) - expect(delays).toStrictEqual([1000, 2000, 4000, 8000, 16000, 30000]) + const promise = retryer.start() + await vi.advanceTimersByTimeAsync(100000) + await expect(promise).rejects.toThrow('failed') + expect(delays).toStrictEqual([ + 0, 1000, 1600, 3600, 7200, 14400, 24000, 30000, + ]) + } finally { + random.mockRestore() + } }) it('should reject with a CancelledError carrying the cancel options and call onCancel', async () => { diff --git a/packages/query-core/src/retryer.ts b/packages/query-core/src/retryer.ts index f3df73545bb..bb46eb2cb6b 100644 --- a/packages/query-core/src/retryer.ts +++ b/packages/query-core/src/retryer.ts @@ -80,12 +80,15 @@ type RetryDelayFunction = ( ) => number /** - * The default `retryDelay`: doubles with every failure, starting at 1 second, up to 30 seconds. - * @param failureCount - The number of failures so far. - * @returns The delay before the next retry, in milliseconds. + * Applies exponential backoff with jitter. The base delay starts at 1 second + * and doubles for each retry, up to 30 seconds. + * @param failureCount - The number of previous failures. Starts at 0 for the first retry. + * @returns A random delay from 80% to 100% of the base delay, in milliseconds. */ function defaultRetryDelay(failureCount: number) { - return Math.min(1000 * 2 ** failureCount, 30000) + const baseDelay = Math.min(1000 * 2 ** failureCount, 30000) + const maxJitter = baseDelay * 0.2 + return baseDelay - Math.floor(Math.random() * (maxJitter + 1)) } /** diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index 30fd21df754..77f7a14fc46 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -374,15 +374,16 @@ export interface QueryOptions< */ retry?: RetryValue /** - * This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the - * next attempt in milliseconds. + * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives + * the failure count and error and returns the delay. The count starts at 0 for the first retry. * - * A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential + * A function like `attempt => Math.min(1000 * 2 ** attempt, 30000)` applies exponential * backoff. * * A function like `attempt => attempt * 1000` applies linear backoff. * - * Defaults to a function that applies exponential backoff, capped at 30 seconds. + * By default, each retry waits a random duration from 80% to 100% of the base delay. + * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. */ retryDelay?: RetryDelayValue /** @@ -1874,10 +1875,11 @@ export interface MutationOptions< */ retry?: RetryValue /** - * This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the - * next attempt in milliseconds. + * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives + * the failure count and error and returns the delay. The count starts at 0 for the first retry. * - * Defaults to a function that applies exponential backoff, capped at 30 seconds. + * By default, each retry waits a random duration from 80% to 100% of the base delay. + * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. */ retryDelay?: RetryDelayValue /**