JAVASCRIPT

Implementing API Request Retry with Exponential Backoff

Enhance web application resilience by implementing an API request retry mechanism with exponential backoff, effectively handling transient network issues and server errors.

async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) {
  for (let i = 0; i <= retries; i++) {
    try {
      const response = await fetch(url, options);

      if (response.status >= 500 || response.status === 429) { // Retry on server errors or Too Many Requests
        if (i < retries) {
          const delay = backoff * Math.pow(2, i) + Math.random() * 100; // Exponential backoff + jitter
          console.warn(`Retrying API call in ${delay}ms... (Attempt ${i + 1}/${retries})`);
          await new Promise(resolve => setTimeout(resolve, delay));
          continue; // Go to next loop iteration for retry
        }
      }

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

      return await response.json();

    } catch (error) {
      if (i < retries && (error.name === 'TypeError' || error.message.includes('network error'))) { // Retry on network errors
        const delay = backoff * Math.pow(2, i) + Math.random() * 100;
        console.warn(`Retrying API call due to network error in ${delay}ms... (Attempt ${i + 1}/${retries})`);
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      console.error('API Request Failed after retries:', error);
      throw error;
    }
  }
  throw new Error('API request failed after multiple retries.');
}

// Example Usage:
// fetchWithRetry('https://api.example.com/flaky-data', {}, 5, 500)
//   .then(data => console.log('Fetched data with retries:', data))
//   .catch(error => console.error('Failed after retries:', error));
How it works: This `fetchWithRetry` function enhances API call reliability by automatically retrying failed requests. It uses an exponential backoff strategy, meaning the delay between retries increases exponentially, plus a random 'jitter' to prevent thundering herd problems. It specifically retries on network errors, server errors (5xx status codes), or 'Too Many Requests' (429) errors, making your application more resilient to transient issues.

Need help integrating this into your project?

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

Hire DigitalCodeLabs