JAVASCRIPT

Robust API Calls with Exponential Backoff Retry

Implement resilient API requests using exponential backoff to automatically retry failed network calls, improving application stability and user experience.

async function fetchWithExponentialBackoff(url, options = {}, retries = 3, delay = 1000) {
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      if (response.status === 429 || response.status >= 500) { // Retry for Too Many Requests or Server Errors
        throw new Error(`API error: ${response.status} ${response.statusText}`);
      }
    }
    return response;
  } catch (error) {
    if (retries > 0) {
      console.warn(`Attempt failed: ${error.message}. Retrying in ${delay / 1000}s... (Attempts left: ${retries})`);
      await new Promise(resolve => setTimeout(resolve, delay));
      return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2); // Exponential backoff
    } else {
      console.error("All retry attempts failed.");
      throw error; // Re-throw the error if no retries left
    }
  }
}

// Example usage:
// fetchWithExponentialBackoff('https://api.example.com/data', { method: 'GET' })
//   .then(response => response.json())
//   .then(data => console.log('Data fetched:', data))
//   .catch(error => console.error('Failed to fetch data after retries:', error));
How it works: This JavaScript function enhances `fetch` requests with an exponential backoff retry mechanism. It attempts to re-call an API if it encounters transient errors (like 429 Too Many Requests or 5xx server errors). The `delay` between retries doubles with each attempt, preventing the client from overwhelming the server and giving the server 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