Retrying rest request with fetch
Image Source: Picsum

Key Takeaways

While the Fetch API is standard for modern web requests, its lack of native retry logic can make applications brittle. This guide demonstrates how to implement a robust, recursive retry pattern using Promises and setTimeout, allowing developers to configure retry counts and intervals to enhance application resilience against transient network errors.

  • Native Fetch API lacks built-in retry mechanisms, requiring custom recursive Promise wrappers to handle transient network failures effectively.
  • Implementing configurable retry limits and time intervals prevents immediate failure while allowing the system to recover from temporary outages.
  • Proper error propagation in the retry logic ensures that the final rejection captures the original error after all attempts are exhausted.
  • Using setTimeout within the retry cycle is a critical pattern to avoid overwhelming the server with rapid-fire requests during downtime.

Javascript fetch api is a great tool to make rest request. It is very easy to use and it is supported by all modern browsers. But sometimes we need to retry the request if it fails. In this post we will see how to retry the request if it fails.

Fetch usages without retry

Let’s see how to use fetch api to make a rest request. We will use the fake api to make the request

We will use the following code to make the request.

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

  

Fetch usages with retry

Now we will see how to retry the request if it fails. We will use the following code to retry the request.


const retry = (fn, retriesLeft = 5, interval = 1000) => {
  return new Promise((resolve, reject) => {
    fn()
      .then(resolve)
      .catch(error => {
        setTimeout(() => {
          if (retriesLeft === 1) {
            // reject('maximum retries exceeded');
            reject(error);
            return;
          }
          // Passing on "reject" is the important part
          retry(fn, retriesLeft - 1, interval).then(resolve, reject);
        }, interval);
      });
  });
};

retry(() => fetch('https://jsonplaceholder.typicode.com/todos/1'))
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.log(error));  

  

The above code will retry the request if it fails. The retry function will take three parameters. The first parameter is the function to retry. The second parameter is the number of retries. The third parameter is the interval between retries. The retry function will return a promise. The promise will resolve if the request is successful. The promise will reject if the request fails after the maximum retries.

It will retry the request 5 times with an interval of 1 second. If the request fails after 5 retries then the promise will reject with the error. The error will be printed in the console.

The SQL Whisperer

The SQL Whisperer

Senior Backend Engineer with a deep passion for Ruby on Rails, high-concurrency systems, and database optimization.

Polyfill node core modules in Webpack 5
Prev post

Polyfill node core modules in Webpack 5

Next post

Top Vs code extension for javascript developer in 2022

Top Vs code extension for javascript developer in 2022