Module 2 · Backend architectureLesson 20 of 886 minIntermediate

Circuit breakers

When a dependency keeps failing, stop calling it for a while. Failing fast protects both you and it.

Try it

Watch "No breaker" waste seconds on every call. Then "Breaker opens" fails fast, and "Recovery" lets a test call through before closing again.

When a service you depend on gets slow or starts failing, the natural thing is to keep trying. That's often the worst thing to do:

  • Each call waits for a timeout, holding a thread and a connection.
  • Waiting requests pile up until your service runs out of resources and fails too.
  • The struggling dependency keeps getting traffic and can't recover.

This is a cascading failure: one slow service drags down everything that calls it.

How a circuit breaker works

It wraps calls to a dependency and tracks failures:

  1. Closed (normal): calls go through. Failures are counted.
  2. When failures cross a threshold (say 50% of the last 20 calls), it opens.
  3. Open: calls fail immediately without touching the dependency.
  4. After a cool-down, it goes half-open and lets a few test calls through.
  5. If they succeed, it closes. If not, it opens again.

Fallbacks

Failing fast is better than failing slowly, but you can often do better than an error:

  • show cached or slightly old data,
  • hide one section of the page ("recommendations unavailable"),
  • queue the action to try later.

Related patterns

  • Timeouts: every remote call needs one. A breaker without timeouts never sees failures.
  • Bulkheads: give each dependency its own limited pool of threads or connections, so one bad dependency can't use them all.
  • Libraries like Resilience4j and service meshes like Istio provide breakers out of the box.

Quick check

What happens to calls while a circuit breaker is open?