Dashboard

What Is a Circuit Breaker in Software? Fail Fast, Recover

A circuit breaker stops your app from hammering a service that is already failing. Here are the three states, a short working example, and where AI-written retry code goes wrong.

Carlo Zuercher
Carlo Zuercher
Staff Engineer, Platform
29 October 20261 min read

In software, a circuit breaker is a small piece of code that wraps a risky call, such as a request to a payment provider or an AI model API, and stops making that call after it has failed too many times in a row. While the breaker is "open", your app fails immediately instead of waiting on a service that is not answering. After a pause, it lets one test request through to see whether the service has recovered.

The name comes from the electrical device. A household breaker trips when current is dangerous so the wiring does not burn. The software version trips when a dependency is unhealthy so your own servers do not drown.

The problem it solves

Say your app calls an AI API for every page view, and that API starts taking 30 seconds to respond. Without protection, every incoming request waits 30 seconds, each one holding a connection and some memory. Within a minute your own app is out of workers, and now your whole site is down, not only the AI feature. One slow dependency became a full outage.

Retrying makes it worse. Every failed call is tried again, so a struggling service gets two or three times its normal traffic exactly when it can least handle it. A circuit breaker is the opposite instinct: stop asking, give it room, check back later.

The three states

Martin Fowler's description of the circuit breaker pattern lays out the standard model:

  • Closed. Normal operation. Calls pass through. Each failure, such as a timeout, adds to a counter, and a success resets the counter to zero.

  • Open. Once failures reach a threshold (five in his example), the breaker trips. Calls fail immediately without touching the remote service, which protects both your resources and the struggling server.

  • Half-open. After a reset timeout has passed since the last failure, the breaker allows a single trial call. If it succeeds, the breaker closes. If it fails, the open period starts over.

Fowler also notes that each protected call needs its own timeout, and that a timeout counts as a failure. Without a timeout, a hung call never registers as a failure at all, and the breaker never trips.

A breaker in about 30 lines

js
class CircuitBreaker {
  constructor(fn, { threshold = 5, resetMs = 30000, timeoutMs = 5000 } = {}) {
    Object.assign(this, { fn, threshold, resetMs, timeoutMs });
    this.failures = 0;
    this.openedAt = 0;
  }

  get state() {
    if (this.failures < this.threshold) return 'closed';
    return Date.now() - this.openedAt >= this.resetMs ? 'half-open' : 'open';
  }

  async call(...args) {
    if (this.state === 'open') throw new Error('circuit open');
    try {
      const result = await Promise.race([
        this.fn(...args),
        new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), this.timeoutMs)),
      ]);
      this.failures = 0;
      return result;
    } catch (err) {
      this.failures += 1;
      if (this.failures >= this.threshold) this.openedAt = Date.now();
      throw err;
    }
  }
}

const askModel = new CircuitBreaker(callModelApi, { threshold: 5, resetMs: 30000 });

This version keeps state in memory, so each server instance has its own breaker. For a small app that is fine. If you run several instances, each trips independently, which is usually acceptable. In production, consider a maintained library instead of your own class, and test it either way.

The decision most examples skip

When the breaker is open, what does the caller do? Throwing an error is the easy answer and often the wrong one. Fowler's page says clients must decide how to respond when the breaker rejects a call, for example queuing the request or showing stale data. For an AI feature that could mean:

  • show a cached answer from the last good run,

  • fall back to a cheaper or different model,

  • hide the feature and say it is temporarily unavailable,

  • queue the job and email the result later.

Pick one on purpose. "It throws and the page crashes" is a choice too, just not one you meant to make.

Circuit breaker versus retry versus timeout

These three work as a team and are often confused:

  • A timeout limits how long one call can wait. See how to set timeouts.

  • A retry repeats a failed call, which only helps for brief glitches. Unlimited retries are a hazard, as covered in AI coding agent retry logic.

  • A circuit breaker decides when to stop trying at all, across many calls.

Order matters: timeout inside, retry around it with a small cap, breaker around both.

Monitoring and manual control

Fowler recommends that a breaker raise an alert when it opens and when it resets, and that operators can trip or reset it by hand. Log state changes with enough detail to see which dependency failed, and expose the current state on a status route. Good logging turns a mystery outage into a one-line answer. Rate-limit your own outbound calls as well, using the same ideas as rate limiting inbound traffic.

When you do not need one

A small app with one low-traffic integration may not need a breaker. A plain timeout and a clear error message are often enough. Add the pattern when a single slow dependency can exhaust your workers, or when many users share one upstream quota. For queued, non-urgent work, a queue may solve the same problem more simply.

FAQ

What is the circuit breaker pattern in simple terms?

It is a wrapper that counts failures from a dependency and, past a limit, stops calling it for a while. That keeps one broken service from dragging your whole app down.

What are the circuit breaker states?

Closed (calls pass through), open (calls are rejected immediately) and half-open (one trial call is allowed to test recovery).

Is a circuit breaker the same as a retry?

No. A retry repeats one failed call. A circuit breaker watches many calls and stops sending them when failures pile up. Used badly, retries can cause the overload a breaker is meant to prevent.

What should happen when the circuit is open?

Decide in advance: serve cached data, use a fallback, show a clear unavailable message, or queue the work. Do not leave it to a default crash.

Do I need a circuit breaker for an AI API?

If a slow model API can tie up your workers, yes, or at least a strict timeout and a fallback. For low-traffic internal tools, a timeout alone is usually enough.

How did this land?

About the author

Carlo Zuercher
Carlo Zuercher

Staff Engineer, Platform

Carlo works on the platform that turns prompts into running apps. He writes the engineering deep dives and the changelog notes worth reading.

Share

Get the next post in your inbox

One email a month. Product updates, engineering posts, and the best of Built with Swarmz.

I agree to receive emails about AI building tips and Swarmz product news. Unsubscribe any time.