JAVASCRIPT

Implement API Rate Limit Retries with Exponential Backoff

Gracefully handle 429 'Too Many Requests' API errors with robust retry logic using exponential backoff in JavaScript for reliable integrations.

async function fetchWithExponentialBackoff(url, options = {}, maxRetries = 5) {
    let retries = 0;
    while (retries < maxRetries) {
        try {
            const response = await fetch(url, options);

            if (response.status === 429) { // Too Many Requests
                retries++;
                const retryAfter = response.headers.get('Retry-After');
                let delay = retryAfter ? parseInt(retryAfter, 10) * 1000 : Math.pow(2, retries) * 1000 + Math.random() * 1000;
                
                console.warn(`Rate limit hit. Retrying in ${delay / 1000} seconds... (Attempt ${retries}/${maxRetries})`);
                await new Promise(resolve => setTimeout(resolve, delay));
                continue; // Try again
            }

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

            return response;
        } catch (error) {
            console.error(`Fetch error on attempt ${retries + 1}:`, error.message);
            if (retries === maxRetries - 1) {
                throw error; // Re-throw error if max retries reached
            }
            retries++;
            const delay = Math.pow(2, retries) * 1000 + Math.random() * 1000;
            console.warn(`Retrying in ${delay / 1000} seconds due to network error... (Attempt ${retries}/${maxRetries})`);
            await new Promise(resolve => setTimeout(resolve, delay));
        }
    }
    throw new Error('Max retries exceeded for fetch operation.');
}

// Example usage:
// (async () => {
//     try {
//         const response = await fetchWithExponentialBackoff('https://api.example.com/data', { method: 'GET' });
//         const data = await response.json();
//         console.log('Fetched data:', data);
//     } catch (error) {
//         console.error('Failed to fetch data after multiple retries:', error.message);
//     }
// })();
How it works: This JavaScript snippet provides a robust `fetchWithExponentialBackoff` function to handle API rate limiting (HTTP 429 errors) and network failures. It automatically retries requests, progressively increasing the delay between attempts using an exponential backoff strategy, optionally respecting `Retry-After` headers. This improves the reliability of API integrations by making them resilient to temporary service overloads.

Need help integrating this into your project?

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

Hire DigitalCodeLabs