JAVASCRIPT

Handle API Rate Limiting with Exponential Backoff

Implement a robust retry mechanism with exponential backoff for API calls, gracefully handling rate limits and transient errors to ensure successful data retrieval.

async function fetchWithRateLimitRetry(url, options = {}, retries = 5, delay = 1000) {
  for (let i = 0; i < retries; i++) {
    try {
      const response = await fetch(url, options);
      if (response.status === 429) { // Too Many Requests
        const retryAfter = response.headers.get('Retry-After');
        const waitTime = retryAfter ? parseInt(retryAfter, 10) * 1000 : delay * Math.pow(2, i);
        console.warn(`Rate limit hit. Retrying after ${waitTime / 1000} seconds...`);
        await new Promise(resolve => setTimeout(resolve, waitTime));
        continue; // Try again
      }
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      if (i === retries - 1) {
        console.error(`Failed after ${retries} attempts:`, error);
        throw error;
      }
      const waitTime = delay * Math.pow(2, i);
      console.warn(`Attempt ${i + 1} failed. Retrying in ${waitTime / 1000} seconds...`);
      await new Promise(resolve => setTimeout(resolve, waitTime));
    }
  }
}

// Example usage:
// (async () => {
//   try {
//     const data = await fetchWithRateLimitRetry('https://api.example.com/data');
//     console.log('API Data:', data);
//   } catch (err) {
//     console.error('Failed to fetch data:', err);
//   }
// })();
How it works: This function fetches data from an API, implementing an exponential backoff strategy to handle rate limiting (HTTP 429) and general network errors. If a 429 status is received, it first checks for a `Retry-After` header. Otherwise, it uses an exponentially increasing delay before retrying the request, preventing continuous hammering of the API and improving the chance of eventual success.

Need help integrating this into your project?

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

Hire DigitalCodeLabs