JAVASCRIPT

Implement Exponential Backoff for API Retries

Learn to build resilient web applications by implementing an exponential backoff strategy for API call retries, enhancing reliability in unstable network conditions.

async function fetchDataWithRetry(url, options = {}, retries = 3, delay = 1000) {
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      if (response.status === 429 || response.status >= 500 && retries > 0) {
        console.warn(`Request to ${url} failed with status ${response.status}. Retrying in ${delay / 1000}s...`);
        await new Promise(res => setTimeout(res, delay));
        return fetchDataWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
      } else {
        throw new Error(`API error: ${response.statusText}`);
      }
    }
    return await response.json();
  } catch (error) {
    if (retries > 0) {
      console.warn(`Network error for ${url}. Retrying in ${delay / 1000}s...`);
      await new Promise(res => setTimeout(res, delay));
      return fetchDataWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
    }
    console.error(`Failed to fetch data after multiple retries: ${error.message}`);
    throw error;
  }
}

// Usage example:
// fetchDataWithRetry('https://api.example.com/data')
//   .then(data => console.log('Fetched data:', data))
//   .catch(error => console.error('Failed:', error.message));
How it works: This JavaScript snippet demonstrates a robust way to make API calls using the `fetch` API, incorporating an exponential backoff strategy for retries. If an API request fails due to transient network issues (e.g., connection lost) or server-side problems (e.g., 5xx errors, rate limiting 429), the function will automatically retry the request after an increasing delay. This prevents overwhelming the server with immediate retries and improves the reliability of your application in less-than-ideal network conditions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs