Recover from transient failures
A flaky network or intermittently unavailable service may succeed after a later request.
Redux Toolkit · Function
RTK Query's retry utility wraps a base query and retries failed requests with exponential backoff. Configure maxRetries per API or endpoint, and use retry.fail to stop immediately when further attempts cannot help.
retry decorates an RTK Query baseQuery so failed requests are attempted again using exponential backoff. Configure the maximum retry count with maxRetries, disable retries for an endpoint with maxRetries: 0, or call retry.fail from the wrapped query to stop immediately when another attempt would be pointless.
retry(baseQuery, options)| Name | Type | Description |
|---|---|---|
baseQuery | BaseQueryFn | The base query function to wrap so its failed requests can be retried. |
options | RetryOptions | Configuration options such as maxRetries that control retry behavior. |
A wrapped base-query function with retry behavior and the retry.fail method.
import { fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'
const staggeredBaseQuery = retry(
fetchBaseQuery({ baseUrl: '/' }),
{ maxRetries: 5 }
)
export const api = createApi({
baseQuery: staggeredBaseQuery,
endpoints: (build) => ({
getPost: build.query({
query: (id: number) => `posts/${id}`,
}),
}),
})Wrap the base query passed to createApi to retry failed requests with exponential backoff.
A flaky network or intermittently unavailable service may succeed after a later request.
Different endpoints need different retry policies.
An authentication or validation error will not improve through repetition.
retry wraps the API's baseQuery and retries failed requests. Its default policy makes five attempts and applies exponential backoff with jitter between attempts.
Follow-up: How can one endpoint opt out? Set maxRetries: 0 in that endpoint's definition.
Pass the wrapped function as createApi's baseQuery. The wrapper accepts an options object, including maxRetries, so the retry limit can be changed from its default.
Follow-up: What happens when maxRetries is zero? The endpoint is not retried.
The wrapper exposes retry.fail as a method. Calling it with the error, and optionally metadata, ends retrying immediately for the current request.
Follow-up: When is that useful? Use it for conditions such as unauthorized responses where repeating the request cannot succeed.
fetchBaseQuerycreateApiretry.failmaxRetriesBaseQueryFn