JAVASCRIPT

Robust API Retries with Exponential Backoff in JavaScript

Implement a resilient API integration pattern using exponential backoff to handle rate limits and transient network errors gracefully in JavaScript.

async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) {
  try {
    const response = await fetch(url, options);
    if (response.status === 429 || !response.ok) { // 429 Too Many Requests, or other non-OK status
      if (retries > 0) {
        console.warn(`Request failed with status ${response.status}. Retrying in ${delay / 1000}s...`);
        await new Promise(resolve => setTimeout(resolve, delay));
        return fetchWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
      } else {
        throw new Error(`Max retries exceeded. Last status: ${response.status}`);
      }
    }
    return response.json();
  } catch (error) {
    console.error('Fetch operation failed:', error.message);
    if (retries > 0) {
      console.warn(`Network error. Retrying in ${delay / 1000}s...`);
      await new Promise(resolve => setTimeout(resolve, delay));
      return fetchWithRetry(url, options, retries - 1, delay * 2);
    } else {
      throw new Error(`Max retries exceeded for network error.`);
    }
  }
}

// Example Usage:
// fetchWithRetry('https://api.example.com/data', { method: 'GET' })
//   .then(data => console.log('Fetched data after retries:', data))
//   .catch(error => console.error('Failed to fetch after all retries:', error.message));
How it works: This snippet demonstrates a `fetchWithRetry` function that enhances API integrations by automatically retrying failed requests. It uses an exponential backoff strategy, increasing the delay between retries to avoid overwhelming the API and to gracefully handle transient issues like rate limiting (HTTP 429) or temporary network outages. The `retries` and `delay` parameters can be configured for specific use cases.

Need help integrating this into your project?

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

Hire DigitalCodeLabs