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:

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:

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.