Course contentsShow
← Web Development
Lesson 1690 of 2,98231. Error Handling and ResilienceFree lesson

Maximum Retry Attempts and Circuit Breakers

Set retry limits and implement circuit breaker patterns to prevent infinite retry loops.

Maximum Retry Attempts and Circuit Breakers

What you'll learn: How to prevent retry mechanisms from running indefinitely and use circuit breakers to fail fast when systems are down.

Why Retry Limits Matter

You've learned about exponential backoff and jitter to space out retries intelligently. But what if the server is completely down for 30 minutes? Without a maximum retry limit, your application could retry hundreds of times, wasting resources and creating a terrible user experience.

Think of it like calling a friend whose phone is dead. After 3-4 attempts, you stop trying and accept they're unavailable—you don't keep redialing every few seconds for an hour.

Setting Maximum Attempts

Define a hard limit on retries:

async function fetchWithRetry(url, maxAttempts = 3) {
  let attempt = 0;
  
  while (attempt < maxAttempts) {
    try {
      const response = await fetch(url);
      if (response.ok) return response;
      throw new Error(`HTTP ${response.status}`);
    } catch (error) {
      attempt++;
      if (attempt >= maxAttempts) {
        throw new Error(`Failed after ${maxAttempts} attempts: ${error.message}`);
      }
      await exponentialBackoffDelay(attempt);
    }
  }
}

Circuit Breaker Pattern

A circuit breaker takes this further: after detecting repeated failures, it temporarily stops all retry attempts (the circuit "opens"). After a timeout, it allows one test request (the circuit "half-opens"). If that succeeds, normal operation resumes.

const circuitBreaker = {
  state: 'CLOSED', // CLOSED, OPEN, HALF_OPEN
  failureCount: 0,
  threshold: 5,
  timeout: 30000,
  nextAttempt: null
};

This prevents cascading failures in distributed systems and gives failing services time to recover without being bombarded.

Key Takeaway: Always set maximum retry attempts to prevent infinite loops, and consider circuit breakers to fail fast and protect both your application and struggling backend services from excessive load.