JAVASCRIPT

Retry Failed API Requests with Exponential Backoff

Implement robust error handling for API integrations by automatically retrying failed requests with increasing delays using an exponential backoff strategy in JavaScript.

async function fetchDataWithRetry(url, options = {}, retries = 3, backoff = 300) {
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      if (response.status === 429) { // Too Many Requests
        const retryAfter = response.headers.get('Retry-After');
        const waitTime = retryAfter ? parseInt(retryAfter) * 1000 : backoff;
        console.warn(`Rate limit hit. Retrying after ${waitTime / 1000} seconds.`);
        await new Promise(resolve => setTimeout(resolve, waitTime));
        return fetchDataWithRetry(url, options, retries, backoff * 2); // Double backoff on rate limit
      }
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    if (retries > 0) {
      console.warn(`Fetch error: ${error.message}. Retrying in ${backoff / 1000} seconds. Attempts left: ${retries - 1}`);
      await new Promise(resolve => setTimeout(resolve, backoff));
      return fetchDataWithRetry(url, options, retries - 1, backoff * 2);
    } else {
      console.error('Max retries exceeded.', error);
      throw error;
    }
  }
}

// Usage example:
// fetchDataWithRetry('https://api.example.com/data')
//   .then(data => console.log('Data fetched:', data))
//   .catch(error => console.error('Failed to fetch data after retries:', error));

// Example with custom options:
// fetchDataWithRetry('https://api.example.com/protected', { headers: { 'Authorization': 'Bearer YOUR_TOKEN' } }, 5, 500)
//   .then(data => console.log('Protected data:', data))
//   .catch(error => console.error('Failed to fetch protected data:', error));
How it works: This JavaScript snippet demonstrates how to implement an exponential backoff strategy for API requests. The `fetchDataWithRetry` function attempts to fetch data from a given URL. If the request fails due to network issues or specific HTTP errors (like 5xx server errors, or 429 Too Many Requests), it waits for an increasing amount of time before retrying. The backoff delay doubles with each retry, preventing overwhelming the server and giving transient issues time to resolve. It also respects the `Retry-After` header for rate limits.

Need help integrating this into your project?

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

Hire DigitalCodeLabs