JAVASCRIPT

Implementing API Call Retries with Exponential Backoff

Build resilient API integrations by adding an exponential backoff retry mechanism to your `fetch` requests, improving reliability for transient network or server errors.

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

    if (response.status === 429 || response.status >= 500) { // Retry for Too Many Requests or Server Errors
      if (retries > 0) {
        console.warn(`Retrying API call for ${url}. Status: ${response.status}. Retries left: ${retries}`);
        await new Promise(resolve => setTimeout(resolve, delay));
        return fetchWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
      }
    }

    if (!response.ok) {
      const errorBody = await response.json().catch(() => ({ message: 'No error body' }));
      throw new Error(`HTTP error! Status: ${response.status}, Details: ${JSON.stringify(errorBody)}`);
    }

    return await response.json();
  } catch (error) {
    console.error(`Fetch operation failed after all retries for ${url}:`, error);
    throw error;
  }
}

// Example usage:
// (async () => {
//   try {
//     const data = await fetchWithRetry(
//       'https://jsonplaceholder.typicode.com/todos/1',
//       { method: 'GET' },
//       5, // Max 5 retries
//       500 // Initial delay of 500ms
//     );
//     console.log('Data fetched with retry:', data);
//   } catch (error) {
//     console.error('Failed to fetch data after retries:', error);
//   }

//   // Example of a failing call (replace with an actual URL that might fail or simulate a 500)
//   // try {
//   //   const failingData = await fetchWithRetry(
//   //     'https://api.brokenexample.com/data', // Assume this URL returns 500 errors
//   //     {}, 2, 200
//   //   );
//   //   console.log('Should not reach here for failing call:', failingData);
//   // } catch (error) {
//   //   console.error('Correctly caught error for failing call after retries:', error);
//   // }
// })();
How it works: This snippet provides a robust `fetch` wrapper that implements a retry mechanism with exponential backoff. It automatically retries API calls that encounter transient network issues, server-side errors (5xx status codes), or rate limiting responses (429 Too Many Requests). The delay between retries increases exponentially, preventing overwhelming the server and giving it time to recover, significantly improving the reliability 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