Retry Strategy
Purpose
The Retry Strategy subtopic addresses the need for a robust and configurable mechanism to handle transient errors during data fetching. Within the broader context of error handling and retry logic, this strategy defines how failed requests should be retried automatically, balancing responsiveness with avoiding excessive load on servers or clients. Its main goal is to enable controlled retry attempts with exponential backoff delays, improving resilience without overwhelming resources.
Functionality
At the core of this strategy is the onErrorRetry function, which governs the retry behavior after a fetch failure. It receives error details, the key of the resource, the SWR configuration, a revalidation callback, and options including the current retry count.
Key aspects of the functionality include:
Retry Limit: The maximum number of retry attempts is controlled by the errorRetryCount configuration option. Once this limit is exceeded, no further retries occur.
Exponential Backoff Delay: The delay before the next retry is computed exponentially based on the current retry count, capped at 8 to avoid excessively long waits. A small random factor is added to prevent retry storms when multiple clients fail simultaneously. This delay is scaled by the configurable
errorRetryInterval.Asynchronous Scheduling: The next retry is scheduled using
setTimeout, which calls the provided revalidate function with the original options, triggering a new fetch attempt.Integration with Config: This retry logic is part of the default configuration under the
onErrorRetryproperty, enabling users to override or customize the strategy if desired.
This strategy ensures retries happen with increasing delays to reduce load and collision, while allowing developers to control retry behavior through config parameters.
Code Snippet Illustrating Retry Delay Calculation
const timeout =
~~(
(Math.random() + 0.5) *
(1 << (currentRetryCount < 8 ? currentRetryCount : 8))
) * config.errorRetryInterval;
This line calculates the exponential backoff delay with a random factor between 0.5 and 1.5, doubling the delay each retry up to 2^8 times the base interval.
Relationship and Integration
The Retry Strategy integrates tightly with the parent topic of Error Handling and Retry Logic by providing the default mechanism for automatic retrying after errors. It complements the Manual Retry UI subtopic, which focuses on user-initiated retries, by handling automated retries transparently in the background.
Within the larger SWR data fetching system, this strategy works alongside suspense boundaries and error boundaries to:
Automatically attempt revalidation without user intervention.
Limit retry attempts to prevent infinite loops.
Coordinate with other triggers like focus or reconnect revalidation.
Provide hooks (
onError,onErrorRetry) for logging or custom side effects.
By encapsulating retry logic as a configurable callback, it also fits into the middleware architecture, allowing future extensions or custom retry policies to be plugged in seamlessly.
Diagram
flowchart TD
A[Fetch Attempt Fails] --> B{Retry Count Exceeded?}
B -->|Yes| C[Stop Retrying]
B -->|No| D[Calculate Exponential Backoff Delay]
D --> E[Schedule Retry via setTimeout]
E --> F[Invoke Revalidate (Retry Fetch)]
F --> A
This flowchart visualizes the core retry process: after a failure, it checks the retry count, computes a delay with exponential backoff, schedules the next retry, and attempts the fetch again.
This retry strategy ensures a resilient data fetching experience by balancing retry aggressiveness and network load, seamlessly operating behind the scenes to recover from intermittent errors.