JAVASCRIPT

Implementing a Retry Mechanism for Failed API Requests

Enhance API integration robustness by adding a retry mechanism with exponential backoff, ensuring temporary network glitches don't disrupt critical data fetches.

async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) {
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      // Consider specific status codes for retries, e.g., 429 (Too Many Requests), 5xx (Server Errors)
      if (retries > 0 && (response.status === 429 || response.status >= 500)) {
        console.warn(`Request to ${url} failed with status ${response.status}. Retrying in ${delay}ms...`);
        await new Promise(resolve => setTimeout(resolve, delay));
        return fetchWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
      }
      throw new Error(`HTTP error! status: ${response.status} - ${response.statusText}`);
    }
    return await response.json();
  } catch (error) {
    console.error(`Fetch operation failed: ${error.message}`);
    throw error;
  }
}

// Example usage:
// (async () => {
//   try {
//     const data = await fetchWithRetry('https://api.example.com/data', { method: 'GET' }, 5);
//     console.log('Successfully fetched data:', data);
//   } catch (error) {
//     console.error('Failed to fetch data after multiple retries.');
//   }
// })();
How it works: This `fetchWithRetry` function enhances API call reliability by automatically retrying failed requests. It uses a recursive approach with a specified number of `retries` and implements exponential backoff, doubling the `delay` between attempts. This strategy helps overcome transient network issues or temporary API server unavailability by waiting longer before subsequent retries.

Need help integrating this into your project?

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

Hire DigitalCodeLabs