← Back to all snippets
JAVASCRIPT

Robust API Fetch with Exponential Backoff

Implement resilient API integrations by automatically retrying failed requests with increasing delays, effectively managing rate limits and temporary network issues.

/**
 * Fetches data from an API with exponential backoff and retries.
 * @param {string} url - The API endpoint URL.
 * @param {object} options - Fetch options (method, headers, body, etc.).
 * @param {number} retries - Maximum number of retries.
 * @param {number} delay - Initial delay in milliseconds for retries.
 * @returns {Promise<Response>} The fetch response.
 * @throws {Error} If all retries fail.
 */
async function fetchDataWithRetries(url, options = {}, retries = 3, delay = 1000) {
    let attempt = 0;
    while (attempt < retries) {
        try {
            const response = await fetch(url, options);
            if (!response.ok) {
                // If response is not OK, but not a network error, it's still a "failure" for this retry logic
                // Could check for specific status codes like 429 (Too Many Requests) or 5xx
                // For simplicity, we'll re-throw for any non-ok response here
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response;
        } catch (error) {
            attempt++;
            console.error(`Attempt ${attempt} failed: ${error.message}`);
            if (attempt < retries) {
                const backoffDelay = delay * Math.pow(2, attempt - 1);
                console.log(`Retrying in ${backoffDelay}ms...`);
                await new Promise(resolve => setTimeout(resolve, backoffDelay));
            } else {
                throw new Error(`Failed to fetch ${url} after ${retries} attempts: ${error.message}`);
            }
        }
    }
}

// Example usage:
// (async () => {
//     try {
//         const data = await fetchDataWithRetries('https://api.example.com/data', {
//             method: 'GET',
//             headers: { 'Content-Type': 'application/json' }
//         }, 5, 500); // 5 retries, starting with 500ms delay
//         const json = await data.json();
//         console.log('Fetched data:', json);
//     } catch (error) {
//         console.error('Final fetch error:', error.message);
//     }
// })();
How it works: This snippet provides a `fetchDataWithRetries` function that enhances API requests with exponential backoff. If an API call fails (due to network issues or non-OK HTTP responses), the function automatically retries the request after a progressively longer delay. This strategy prevents overwhelming the API during transient failures and gracefully handles common issues like rate limiting, significantly improving the robustness of API integrations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs