JAVASCRIPT

Implement Exponential Backoff for API Request Retries

Implement a robust function to automatically retry failed API requests using an exponential backoff strategy, improving integration reliability.

async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) {
    try {
        const response = await fetch(url, options);
        if (!response.ok) {
            // Treat non-OK responses as potential retry candidates,
            // unless it's a client error (4xx) that won't resolve on retry.
            // For demonstration, we'll retry all non-OK for simplicity.
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return await response.json();
    } catch (error) {
        if (retries > 0) {
            console.warn(`Request failed, retrying in ${backoff}ms... (${retries} retries left)`);
            await new Promise(resolve => setTimeout(resolve, backoff));
            return fetchWithRetry(url, options, retries - 1, backoff * 2); // Exponential backoff
        } else {
            console.error("Max retries reached. Request failed:", error.message);
            throw error; // Re-throw the error after max retries
        }
    }
}

// Example Usage:
// fetchWithRetry('https://api.example.com/data', { method: 'GET' })
//     .then(data => console.log('Fetched data:', data))
//     .catch(err => console.error('Failed to fetch data after retries:', err));
How it works: This JavaScript function `fetchWithRetry` makes an API request using the Fetch API. If the request fails (due to network error or a non-OK HTTP status), it attempts to retry the request. It implements an exponential backoff strategy, meaning the delay between retries doubles with each attempt, starting from `backoff` milliseconds. The `retries` parameter controls the maximum number of retry attempts before giving up. This pattern significantly enhances the robustness of API integrations by gracefully handling transient issues.

Need help integrating this into your project?

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

Hire DigitalCodeLabs