Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/retry-delay-jitter.md
Original file line number Diff line number Diff line change
@@ -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.
28 changes: 0 additions & 28 deletions docs/framework/angular/guides/query-retries.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/framework/react/guides/important-defaults.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 2 additions & 0 deletions docs/framework/react/guides/mutations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 11 additions & 27 deletions docs/framework/react/guides/query-retries.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <QueryClientProvider client={queryClient}>...</QueryClientProvider>
}
```

[//]: # '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'

Expand Down
20 changes: 0 additions & 20 deletions docs/framework/svelte/guides/query-retries.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,26 +31,6 @@ replace:
```

[//]: # 'Example'
[//]: # 'Example2'

```svelte
<script lang="ts">
// Configure for all queries
import { QueryClient, QueryClientProvider } from '@tanstack/svelte-query'

const queryClient = new QueryClient({
defaultOptions: {
queries: {
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
},
},
})
</script>

<QueryClientProvider client={queryClient}>...</QueryClientProvider>
```

[//]: # 'Example2'
[//]: # 'Example3'

```svelte
Expand Down
18 changes: 0 additions & 18 deletions docs/framework/vue/guides/query-retries.md
Original file line number Diff line number Diff line change
Expand Up @@ -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'
51 changes: 29 additions & 22 deletions packages/query-core/src/__tests__/retryer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>>().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<number> = []
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 () => {
Expand Down
11 changes: 7 additions & 4 deletions packages/query-core/src/retryer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,15 @@ type RetryDelayFunction<TError = DefaultError> = (
) => 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))
}

/**
Expand Down
16 changes: 9 additions & 7 deletions packages/query-core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,15 +374,16 @@ export interface QueryOptions<
*/
retry?: RetryValue<TError>
/**
* 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<TError>
/**
Expand Down Expand Up @@ -1874,10 +1875,11 @@ export interface MutationOptions<
*/
retry?: RetryValue<TError>
/**
* 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<TError>
/**
Expand Down
Loading