SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Service Discovery
  • API Gateway Pattern
  • Backend for Frontend (BFF)
  • Sidecar Pattern
  • Circuit Breaker
  • Bulkhead
  • Strangler Fig
  • Service Mesh
  • Database per Service
  • Timeouts and Deadlines
  • API Composition
  • Anti-Corruption Layer
  • Ambassador Pattern
  • Idempotent Consumer and Inbox Pattern
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Microservices Patterns

Circuit Breaker

Stop calling a failing service for a while, so one failure does not spread.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A circuit breaker watches calls to another service. When that service keeps failing, the breaker stops sending calls for a while and fails fast, instead of waiting for each one to time out.

  • It has three states: closed (normal), open (calls blocked) and half-open (a trial call to test recovery).
  • It protects the caller, whose threads would otherwise be stuck waiting, and gives the sick service time to recover.
  • While open, the caller can return a fallback (cached data, a default, a friendly message).

02Concept: What is it?

In a system of many services, one service calls another over the network. What happens if the other one is down or very slow? Each call waits until its timeout (say 2 seconds) and then fails. Meanwhile new requests keep arriving and each one also waits. Threads and connections fill up with waiting calls, and soon the caller itself becomes slow or dead. A failure spreads from one service to the next. This is a cascading failure.

A circuit breaker works like the fuse box in a house. When there is a fault, the fuse trips and cuts the line, so the fault does not burn down the house. In software, the breaker counts recent failures. When there are too many, it trips open and rejects calls immediately (in microseconds, not seconds).

After a waiting period the breaker moves to half-open and lets one or a few trial calls through. If they succeed, the service is healthy again and the breaker closes. If they fail, it opens again.

The three states
🟒Closedcalls go through
→↓too many failures
πŸ”΄Opencalls rejected fast
→↓wait time over
🟑Half-opentrial calls
🟑Trial worksback to closed
→↓or
🟑Trial failsback to open
Closed is normal. Open blocks calls. Half-open tests with a trial call.
🧠Fail fast is a feature
A quick, clear error is better than a slow one. Fast failures free up threads and let the caller show a fallback.

03Real-Life Example

🍡The Fuse Box and the Broken Phone Line
Imagine you must call a friend, but their phone line is broken. Each time you call, you wait on the line for 30 seconds before giving up. After three failed calls you stop and think: "Their line is broken. I will not try again for 10 minutes." You do something else in the meantime (leave a note). After 10 minutes you try one call. If it works, you go back to calling normally. If not, you wait another 10 minutes. You saved a lot of waiting, and your friend's phone company was not flooded with calls while fixing the line.
Phone calls
Circuit breaker
Normal calling
Closed state
Three failed calls in a row
Failure threshold reached
Deciding not to call for 10 minutes
Open state, with a wait time
Leaving a note instead
A fallback response
One test call after waiting
Half-open trial call
The test call works, go back to normal
Breaker closes
The 30 seconds wasted on each failed call
The timeout the breaker avoids
A call through a breaker
🧠Caller
→↓
πŸ”ŒBreakerchecks its state
→↓if closed
πŸͺService

04Why Do We Need It?

🧯Stop cascading failures
One sick service does not drag down everything that calls it.
⚑Fail fast
A rejected call returns in about a millisecond instead of waiting for a long timeout.
🧡Save threads and connections
Resources are not stuck waiting on a service that will not answer.
🩹Room to recover
Less traffic hits a struggling service, so it can come back faster.
🎭Graceful fallback
Show cached data, a default or a polite message instead of an error page.
πŸ“ŠA clear signal
Breaker state is a simple health signal to alert on.
When a dependency is failing, calling it again and again only makes things worse. Stop, step back and test it gently.

05Where Do We Use It?

πŸ”—Service-to-service calls
Any microservice calling another over HTTP or gRPC.
πŸ—„οΈDatabases and caches
Protect your app from a slow or unreachable database.
πŸ’³Third-party APIs
Payment, email, maps and SMS providers you do not control.
πŸšͺAPI gateways
A gateway can break the circuit to a failing backend.
πŸ•ΈοΈService meshes
Proxies such as Envoy offer circuit breaking and outlier detection for every service.
πŸ“šResilience libraries
Resilience4j (Java), Polly (.NET), opossum (Node), pybreaker (Python), gobreaker (Go).

06Types / Parts / How It Works

The three states in detail

StateWhat the breaker doesLeaves when
ClosedLets every call through and counts failuresFailures pass the threshold
OpenRejects calls at once (or calls a fallback). No traffic reaches the serviceThe wait time ends
Half-openAllows a small number of trial callsTrials succeed (close) or one fails (open again)

How a breaker decides to open

RuleMeaningGood and bad
Consecutive failuresOpen after N failures in a rowSimple. One lucky success resets the count.
Failure rate in a windowOpen if more than X% of the last N calls (or last T seconds) failedCommon and stable. Needs a minimum number of calls first.
Slow call rateTreat calls slower than a limit as failuresCatches a service that is up but crawling.
What counts as a failure?
Count as failure
⏱️Timeout
πŸ”ŒConnection refused
πŸ’₯HTTP 5xx
Usually do not count
πŸ™…HTTP 400 / 404caller's fault
πŸ”’HTTP 401 / 403
Service unhealthy Normal business answers
Count the errors that mean the service is unhealthy. Not the ones that mean the caller made a mistake.
VisualizerBreak the circuit: an outage with and without a breakerTurn the breaker on and off, then change how many failures open it, how long it stays open and how long the outage lasts. Watch the closed, open and half-open states.
Protection
One box per request (second 40). Green = worked, red = timed out on the dead service, amber = rejected instantly by the breaker.
C
C
C
C
C
C
C
C
C
C
C
O
O
O
O
O
H
O
O
O
O
O
H
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
0 stop bar: red = service down40 s
Letters under the boxes: C = closed, O = open, H = half-open (a white ring marks the trial call).
Hit the dead service
4
slow failures
Stopped by breaker
10
fast failures
Succeeded
26
requests
Time wasted waiting
8.0 s
on failed calls
Avg latency
233 ms
all requests
CLOSED: calls go through normally and the service answers fast.

A simplified model with a simulated clock (no random numbers): a healthy call takes 50 ms, a call to a dead service waits 2 s, a rejected call takes about 2 ms. Real breakers often use a failure rate over a time window instead of failures in a row.

07How to Use It / Steps / Implementation

Using a breaker well

  1. 1
    Wrap one dependency per breaker
    Give each remote service its own breaker, so a failing recommendation service does not block payments.
  2. 2
    Always set a timeout first
    A breaker needs failures to count. Without a call timeout, a hung call is never a failure.
  3. 3
    Choose the open rule
    Pick a failure-rate rule with a minimum call count (for example, 50% of the last 20 calls) so a few errors on quiet traffic do not trip it.
  4. 4
    Set the open wait time
    Long enough for recovery (seconds to a minute). Some libraries grow it with each failed trial (backoff).
  5. 5
    Limit half-open trials
    Allow only a few calls through, so a barely recovered service is not flooded again.
  6. 6
    Design a fallback
    Cached value, default, empty list, a queued request or a clear error message. Decide what is acceptable for each call.
  7. 7
    Alert and measure
    Emit state changes as metrics and logs. An open breaker is an incident signal.
πŸ’‘Combine with other patterns
Use timeouts and retries with backoff for short blips, a circuit breaker for longer outages, and a bulkhead so one dependency cannot use all your threads.
⚠️Retries can fight the breaker
Aggressive retries multiply traffic towards a sick service. Put the retry inside the breaker, so rejected calls are not retried, and add a random delay (jitter).

08Key Terms to Know

TermMeaning in easy words
Circuit breakerA guard that blocks calls to a failing dependency for a while
ClosedNormal state: calls pass through
OpenBlocked state: calls fail fast
Half-openTesting state: a few trial calls are allowed
Failure thresholdHow many failures (or what rate) make the breaker open
Cascading failureA failure that spreads from one service to the services that depend on it
Fail fastReturn an error at once instead of waiting
FallbackA backup answer used when the real call is not possible
TimeoutThe longest a caller will wait for a reply
Backoff and jitterWaiting longer between retries, with a little random variation
Health checkA request that tests whether a service is working

09Pros, Cons and Trade-offs

βœ… Pros
  • Stops failures from spreading
  • Fast errors instead of long waits
  • Protects threads and connections
  • Gives a failing service time to recover
  • Enables graceful fallbacks
  • Easy to monitor through its state
⚠️ Cons
  • Wrong settings trip too often or too late
  • Needs a sensible fallback for each call
  • Can hide a real problem if nobody watches it
  • Per-instance state means each instance learns on its own
  • Adds testing work (failure scenarios)
  • Not useful for errors caused by bad requests

Trade-offs

ChoiceWe gainWe lose
Low failure thresholdReacts fast to real outagesMay trip on a small blip and block healthy calls
High failure thresholdIgnores random errorsMore slow failures before the breaker acts
Long open timeMore recovery time for the serviceLonger period of fallback, even after recovery
Short open timeQuick return to normalA service still unwell is hit again and again
Many half-open trialsFaster closingRisk of overloading a fragile service
Breaker in each instanceSimple, no shared stateEach instance must learn the outage by itself

10Common Problems and Mistakes

Common mistakes

  1. No timeout. Calls hang forever, so the breaker never sees a failure.
  2. One breaker for everything. One bad endpoint blocks all calls to the service.
  3. Counting client errors. A flood of 404s opens the breaker, though the service is fine.
  4. No fallback. The user just gets an error, but a faster one.
  5. Opening on tiny samples. 2 failures out of 2 calls is 100%, but it proves little. Use a minimum call count.
  6. Ignoring breaker alerts. A breaker can hide a long outage behind a polished fallback.
  7. Never testing it. Break a dependency on purpose in a test environment to see the real behaviour.

Things to watch

πŸ”Flapping
The breaker opens and closes again and again. Increase the wait time or the number of trial calls.
🐌Slow, not dead
A service that is only slow can be worse than one that is down. Count slow calls as failures.
🌊Thundering herd on recovery
When it closes, all callers return at once. Use limited half-open trials and ramp up.
🧩Stale fallback data
Cached answers can be old. Make sure that is acceptable for the use case.

11Real-World Examples

🎬Netflix Hystrix
Netflix made the pattern famous with Hystrix. It is now in maintenance mode, and teams use Resilience4j or mesh features instead.
β˜•Resilience4j
The common Java library, with sliding-window failure rates and slow-call detection.
πŸ”·Polly in .NET
A popular resilience library with circuit breaker, retry and timeout policies.
πŸ•ΈοΈEnvoy and Istio
Envoy provides circuit-breaking limits and outlier detection (ejecting bad hosts) for the whole mesh.
πŸ›’Shop recommendations
If the recommendation service is down, the page shows popular items and still lets you check out.
πŸ’³Payment providers
If a provider fails, switch to a second provider or queue the payment for later.
πŸ“Note
Library names and maintenance status change over time. Check the current docs of your language and platform.
Mini case: product page and recommendations
πŸ“„Product page
→↓
πŸ”ŒBreaker: openrejects at once
⇒⇣skipped
πŸ€–Recommendationsdown
πŸ“¦Fallbacktop sellers from cache
→↓shown instead
πŸ™‚Happy user
The breaker is open, so the page uses a fallback and stays fast.

12Related Topics to Read Next

Bulkhead→

A bulkhead limits resources per dependency, while a breaker stops calls to a failing one.

Microservices→

Many network calls between services is where breakers are needed.

Rate Limiting→

Another way to protect a service from too much traffic.

Availability→

Breakers keep the overall system up when a part fails.

Service Mesh→

Meshes apply circuit breaking to every service without code changes.

Idempotency→

Retries around a breaker are only safe for idempotent calls.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a guard that stops calls to a failing service for a while.
  • βœ”States: closed (normal), open (rejecting), half-open (testing).
  • βœ”Opens: when failures pass a threshold, by count or by rate over a window.
  • βœ”Why: fail fast, free threads, stop cascading failures, let the service recover.
  • βœ”Needs: a timeout, a minimum call count, limited trials and a fallback.
  • βœ”Count: timeouts, connection errors, 5xx. Not 4xx.
  • βœ”Tools: Resilience4j, Polly, Envoy and Istio. Hystrix is retired.
  • βœ”One line: β€œIf it keeps failing, stop calling, then test gently.”
← Previous
Sidecar Pattern
Next β†’
Bulkhead