JAVASCRIPT

Retry Failed API Calls with Exponential Backoff

Implement a robust retry mechanism with exponential backoff for API requests to gracefully handle transient network errors and server issues, improving reliability.

async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) {
  try {
    const response = await fetch(url, options);

    if (!response.ok) {
      // Retry only for specific transient error codes like 5xx or network errors
      if (response.status >= 500 && retries > 0) {
        console.warn(`Retrying ${url} due to server error ${response.status}. Retries left: ${retries}`);
        await new Promise(resolve => setTimeout(resolve, delay));
        return fetchWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
      }
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return response;
  } catch (error) {
    if (error.message.includes('Failed to fetch') && retries > 0) { // Catch network errors
      console.warn(`Retrying ${url} due to network error. Retries left: ${retries}`);
      await new Promise(resolve => setTimeout(resolve, delay));
      return fetchWithRetry(url, options, retries - 1, delay * 2);
    }
    console.error('Error fetching data after retries:', error);
    throw error;
  }
}

// Usage example (e.g., fetching JSON):
// fetchWithRetry('https://api.example.com/volatile-data', { method: 'GET' }, 5, 500) // 5 retries, starting with 500ms delay
//   .then(response => response.json())
//   .then(data => console.log('Fetched data after retries:', data))
//   .catch(error => console.error('Failed to fetch after multiple retries:', error));
How it works: This snippet provides a `fetchWithRetry` function that wraps the standard Fetch API call, implementing an exponential backoff strategy for retrying failed requests. It attempts to re-fetch the data a specified number of times (`retries`) if the initial call fails due to transient issues (e.g., 5xx server errors or network errors like 'Failed to fetch'). The `delay` between retries doubles with each attempt, preventing overwhelming the server and giving it time to recover, significantly improving the robustness of API integrations.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs