← Back to all snippets
JAVASCRIPT

Graceful API Rate Limit Handling with Exponential Backoff

Implement robust API rate limit management in JavaScript using exponential backoff and `Retry-After` headers for reliable integration and fewer failed requests.

async function fetchWithRateLimitRetry(url, options = {}, retries = 5, backoff = 1000) {
  try {
    const response = await fetch(url, options);

    if (response.status === 429) { // Too Many Requests
      const retryAfter = response.headers.get('Retry-After');
      const delay = retryAfter ? parseInt(retryAfter, 10) * 1000 : backoff;

      if (retries > 0) {
        console.warn(`Rate limit hit, retrying in ${delay / 1000}s...`);
        await new Promise(resolve => setTimeout(resolve, delay));
        return fetchWithRateLimitRetry(url, options, retries - 1, backoff * 2); // Exponential backoff
      } else {
        throw new Error('Max retries exceeded for rate limit.');
      }
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return response.json();
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error;
  }
}

// Example usage:
// fetchWithRateLimitRetry('https://api.example.com/data')
//   .then(data => console.log('Fetched data:', data))
//   .catch(error => console.error('Failed to fetch:', error));
How it works: This JavaScript function `fetchWithRateLimitRetry` extends the standard `fetch` API to gracefully handle `429 Too Many Requests` errors. It checks for a `Retry-After` header to determine the recommended delay. If not present, it uses an exponential backoff strategy, doubling the delay with each retry. This ensures your application doesn't overwhelm the API and can recover from temporary rate limit breaches, improving integration reliability.

Need help integrating this into your project?

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

Hire DigitalCodeLabs