JAVASCRIPT

Exponential Backoff Retry for API Calls

Implement an exponential backoff strategy in JavaScript to gracefully retry failed API requests, improving resilience for intermittent network or server issues.

async function fetchWithExponentialBackoff(url, options = {}, retries = 3, delay = 1000) {
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      if (response.status >= 500 && retries > 0) { // Retry for server errors
        console.warn(`Attempt failed for ${url}. Retrying in ${delay / 1000}s... (${retries} retries left)`);
        await new Promise(res => setTimeout(res, delay));
        return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2); // Exponentially increase delay
      }
      throw new Error(`HTTP error! status: ${response.status} for ${url}`);
    }
    return await response.json();
  } catch (error) {
    if (retries > 0 && error.name === 'TypeError') { // Network errors like 'Failed to fetch'
        console.warn(`Network error for ${url}. Retrying in ${delay / 1000}s... (${retries} retries left)`);
        await new Promise(res => setTimeout(res, delay));
        return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2);
    }
    console.error(`Final attempt failed for ${url}:`, error);
    throw error;
  }
}

// Example Usage:
// fetchWithExponentialBackoff('https://api.example.com/unreliable-service', {}, 5, 500) // 5 retries, starting with 0.5s delay
//   .then(data => console.log('Successfully fetched:', data))
//   .catch(error => console.error('Failed after multiple retries:', error));

// // To test network error, you can make it call a non-existent domain:
// // fetchWithExponentialBackoff('https://nonexistent-domain-test.com/data', {}, 3, 200)
// //   .then(data => console.log('Successfully fetched:', data))
// //   .catch(error => console.error('Failed after multiple retries:', error));
How it works: This JavaScript snippet implements an exponential backoff retry strategy for `fetch` API calls. When an API request fails due to server errors (5xx status codes) or network issues (`TypeError`), the function recursively retries the request after a progressively longer delay. This improves the robustness of integrations by automatically handling transient failures, with a configurable number of retries and initial delay.

Need help integrating this into your project?

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

Hire DigitalCodeLabs