JAVASCRIPT

Client-Side Rate Limit Handling with Exponential Backoff

Implement a robust client-side retry mechanism for API requests encountering 429 (Too Many Requests) errors, using exponential backoff to prevent overwhelming the server.

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

    if (response.status === 429 && retries > 0) {
      console.warn(`Rate limit hit for ${url}. Retrying in ${delay / 1000} seconds...`);
      await new Promise(resolve => setTimeout(resolve, delay));
      return fetchWithRateLimitRetry(url, options, retries - 1, delay * 2); // Exponential backoff
    }

    if (!response.ok) {
      const errorBody = await response.text();
      throw new Error(`HTTP error! Status: ${response.status}, Body: ${errorBody}`);
    }

    return response.json();
  } catch (error) {
    console.error("Fetch failed after retries:", error);
    throw error;
  }
}

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

// fetchWithRateLimitRetry('https://api.example.com/protected', {
//   method: 'POST',
//   headers: { 'Content-Type': 'application/json' },
//   body: JSON.stringify({ key: 'value' })
// }, 5) // Try up to 5 times
//   .then(data => console.log('Posted data response:', data))
//   .catch(error => console.error('Failed to post:', error.message));
How it works: This JavaScript function `fetchWithRateLimitRetry` enhances the standard `fetch` API by automatically retrying requests that fail due to a 429 "Too Many Requests" status code. It implements an exponential backoff strategy, doubling the delay between retries with each attempt, to prevent further overloading the API. The `retries` parameter limits the number of attempts, ensuring the client doesn't get stuck in an infinite loop. This snippet makes API integrations more resilient to transient rate limiting.

Need help integrating this into your project?

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

Hire DigitalCodeLabs