Blog>
Snippets

Exponential Backoff Retry Strategy in Redux-Saga

Illustrate an exponential backoff strategy for retrying failed asynchronous actions in Redux-Saga, gradually increasing the wait time between retries.
import { call, put } from 'redux-saga/effects';

function* exponentialBackoffRetrySaga(apiFunc, maxRetries, action) {
  let attempts = 0;
  while (attempts < maxRetries) {
    try {
      // Attempt to call the API function
      const response = yield call(apiFunc, action.payload);
      // If successful, dispatch success action
      yield put({type: 'FETCH_SUCCESS', payload: response});
      return; // Exit the loop and saga
    } catch (error) {
      if (attempts >= maxRetries - 1) {
        // In case max retries reached, dispatch a failure
        yield put({type: 'FETCH_FAILURE', error});
        return;
      }
      // Calculate delay with exponential backoff
      // Example: 100ms, 200ms, 400ms, etc.
      const delayTime = (2 ** attempts) * 100;
      // Wait for the calculated delay before next attempt
      yield call(delay, delayTime);
      attempts++;
    }
  }
}
This code snippet defines a Redux-Saga worker saga that implements an exponential backoff retry strategy for calling an asynchronous API function. It tries to execute a given API function, catching any errors. If the call fails, it retries the call, increasing the wait time exponentially between each attempt. The number of max retries and the action to call are parameters. It dispatches success or failure actions based on the outcome after all attempts.
import { delay } from 'redux-saga/effects';

function* exponentialBackoff(maxRetries, initialDelay = 100) {
  let attempts = 0;
  while (attempts < maxRetries) {
    // Wait using the exponential backoff strategy
    yield delay(initialDelay * (2 ** attempts));
    attempts++;
  }
}
This is an abstracted helper generator function demonstrating the core logic of exponential backoff, where the delay before each retry attempt is exponentially increased. It's designed to be reusable in different sagas that might need an exponential backoff strategy. 'maxRetries' controls the number of attempts, and 'initialDelay' sets the starting wait time, which doubles after each attempt.