JAVASCRIPT

Robust API Fetch with Exponential Backoff and Retry

Implement a robust API fetching utility in JavaScript that automatically retries failed requests using an exponential backoff strategy, enhancing application resilience.

async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) {
    try {
        const response = await fetch(url, options);
        if (!response.ok) {
            // Check for server errors (5xx) or transient client errors (429 Too Many Requests)
            // that might be worth retrying. For 400s or 401s, retry is usually not helpful.
            if (response.status >= 500 || response.status === 429) {
                throw new Error(`API error: ${response.status} ${response.statusText}`);
            }
            // For other client errors, don't retry, just throw.
            throw new Error(`Client error: ${response.status} ${response.statusText}`);
        }
        return await response.json();
    } catch (error) {
        if (retries > 0) {
            console.warn(`Retrying API call to ${url} in ${backoff}ms. Retries left: ${retries - 1}`);
            await new Promise(resolve => setTimeout(resolve, backoff));
            return fetchWithRetry(url, options, retries - 1, backoff * 2); // Exponential backoff
        }
        throw error; // No retries left, rethrow the error
    }
}

// Usage Example:
/*
(async () => {
    try {
        const data = await fetchWithRetry('https://jsonplaceholder.typicode.com/posts/1', { method: 'GET' });
        console.log('Fetched data:', data);

        // Example of a failing call (simulate 500 error)
        // const failingData = await fetchWithRetry('https://httpstat.us/500', { method: 'GET' }, 2);
        // console.log('Failing data (should not reach here):', failingData);
    } catch (err) {
        console.error('Failed to fetch after multiple retries:', err.message);
    }
})();
*/
How it works: This JavaScript function provides a robust way to make API requests by implementing an exponential backoff retry mechanism. If an `fetch` call fails due to network issues or transient server errors (like 5xx status codes or 429 Too Many Requests), it will automatically retry the request up to a specified number of times, waiting longer between each attempt. This significantly improves the resilience of web applications when interacting with potentially unreliable external APIs, ensuring a better user experience by handling temporary glitches gracefully.

Need help integrating this into your project?

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

Hire DigitalCodeLabs