When a dependency fails slowly, every request that calls it waits for a timeout. Threads, connections and memory fill with waiting requests, and soon your service fails too, even for requests that never needed that dependency. A circuit breaker stops the cascade by noticing the failure and failing fast until the dependency recovers.

The three states

StateBehaviourMoves to
ClosedCalls go through; failures are countedOpen, when failures cross a threshold
OpenCalls fail immediately (or use a fallback)Half-open, after a cool-down period
Half-openA few trial calls go throughClosed if they succeed, open again if they fail

The name comes from electrical circuit breakers: when there is a fault, break the circuit rather than let it burn.

Thresholds that work

  • Failure rate over a window (for example 50% of at least 20 calls in 30 seconds) is more robust than a fixed count.
  • Slow calls count as failures if they exceed a latency threshold; slow dependencies cause cascades too.
  • Cool-down of 10 to 60 seconds before trying again.
  • Half-open trial size: a handful of calls, so recovery is tested without a flood.

A minimal implementation

class CircuitBreaker {
  private state: 'closed' | 'open' | 'half_open' = 'closed';
  private failures = 0; private calls = 0; private openedAt = 0;
  constructor(private threshold = 0.5, private minCalls = 20, private coolDownMs = 30_000) {}

  async call<T>(fn: () => Promise<T>, fallback: () => T): Promise<T> {
    if (this.state === 'open') {
      if (Date.now() - this.openedAt < this.coolDownMs) return fallback();
      this.state = 'half_open';
    }
    try {
      const result = await fn();
      this.record(true);
      return result;
    } catch {
      this.record(false);
      return fallback();
    }
  }

  private record(ok: boolean) {
    if (this.state === 'half_open') {
      if (ok) { this.state = 'closed'; this.failures = 0; this.calls = 0; } else { this.trip(); }
      return;
    }
    this.calls += 1; if (!ok) this.failures += 1;
    if (this.calls >= this.minCalls && this.failures / this.calls >= this.threshold) this.trip();
  }
  private trip() { this.state = 'open'; this.openedAt = Date.now(); this.failures = 0; this.calls = 0; }
}

In production, prefer a mature library (resilience4j for Java, Polly for .NET, opossum for Node.js, gobreaker for Go) with sliding windows and metrics built in.

Fallbacks

Failing fast is only useful if the caller can do something sensible:

  • Serve cached or default data (recommendations from yesterday, a generic shipping estimate).
  • Degrade a feature (hide the reviews widget, skip personalisation).
  • Queue the work for later (send the email when the provider recovers).
  • Return a clear error quickly, which is still better than a 30-second hang.

Worked example

A product page calls a recommendations service. One afternoon recommendations slow to 8 seconds per call. Without a breaker, product pages take 8 seconds and worker threads fill; the whole site slows. With a breaker (open at 50% failures or calls over 1 second), it opens within 30 seconds, product pages render without recommendations in 200 ms, and every 30 seconds a few trial calls test recovery. When recommendations recover, the breaker closes and the widget returns.

Breakers, timeouts and retries together

Timeouts bound each call; retries handle brief blips; breakers handle sustained failure. Order matters: retries inside a closed breaker, and no retries while it is open. See timeouts in distributed systems and retries with backoff and jitter.

Monitoring breakers

A breaker that opens silently hides a problem. Emit an event or metric on every state change, alert when a breaker stays open for more than a few minutes, and record the state on spans (circuit.state=open) so traces explain why a call was skipped. In VitalRix, breaker state changes can be logged or sent as metrics and alerted on, and APM shows the dependency's error rate and latency that tripped it.

Checklist

  1. Timeouts on every dependency call.
  2. A breaker per dependency (not one global breaker).
  3. Failure-rate and slow-call thresholds with a minimum call count.
  4. A fallback that keeps the user experience acceptable.
  5. Alerts on breakers staying open.
  6. Tests that simulate the dependency failing. See chaos engineering basics.

Common mistakes

  • One breaker for many dependencies, so a failure in one blocks calls to all of them.
  • No minimum call count, so two failures out of three calls at 3 a.m. trip the breaker.
  • Ignoring slow calls: a dependency that answers in 20 seconds is as dangerous as one that errors.
  • Fallbacks that call the same failing dependency through another path.
  • Breakers in every layer with different thresholds, which makes behaviour hard to predict. Put them close to the call.

Testing breakers

Simulate a dependency failure in staging (return errors, add latency) and confirm three things: the breaker opens within the expected time, the fallback keeps the user experience acceptable, and the breaker closes again once the dependency recovers. Repeat after changes to thresholds or libraries.

When should I use a circuit breaker?

Around any remote dependency whose failure or slowness could tie up your resources, especially ones that are not critical to every request.

Is a circuit breaker the same as a retry?

No. Retries try again for brief failures; a breaker stops calling during sustained failures. They work together.

Should every service share one breaker?

No. Use one breaker per dependency, and sometimes per endpoint, so one failure does not block unrelated calls.

Try VitalRix free

Uptime monitoring, APM, logs, real user monitoring and status pages in one place. No credit card needed.