← Back to all snippets
JAVASCRIPT

Robust API Request Retry with Exponential Backoff

Learn how to implement a resilient API request mechanism with exponential backoff, automatically retrying failed calls with increasing delays to handle transient network issues and improve application reliability.

async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) {
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      if (response.status >= 500 && retries > 0) {
        console.log(`Retrying ${url} in ${delay / 1000}s... (Attempts left: ${retries})`);
        await new Promise(resolve => setTimeout(resolve, delay));
        return fetchWithRetry(url, options, retries - 1, delay * 2);
      } else {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
    }
    return response.json(); // Or response.text(), etc.
  } catch (error) {
    if (retries > 0 && (error instanceof TypeError || error.message.includes('Failed to fetch'))) {
      console.log(`Network error: ${error.message}. Retrying ${url} in ${delay / 1000}s... (Attempts left: ${retries})`);
      await new Promise(resolve => setTimeout(resolve, delay));
      return fetchWithRetry(url, options, retries - 1, delay * 2);
    } else {
      console.error('Final attempt failed:', error);
      throw error;
    }
  }
}

// Usage example:
// fetchWithRetry('https://api.example.com/data', { method: 'GET' })
//   .then(data => console.log('Fetched data:', data))
//   .catch(error => console.error('Failed after retries:', error));
How it works: This JavaScript snippet demonstrates how to implement a robust API request function with exponential backoff. It uses recursion to retry failed `fetch` calls, specifically for network errors or server-side issues (5xx status codes). Upon failure, it waits for an increasing amount of time (doubling the delay) before making the next attempt, up to a specified number of retries. This approach significantly improves the reliability of API integrations by gracefully handling transient failures without overwhelming the server.

Need help integrating this into your project?

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

Hire DigitalCodeLabs