What you'll learn: By the end of this lesson you will be able to explain how a circuit breaker in the browser works (closed, open, half-open), choose which responses count as failures, give each page section a fallback that matches how essential it is, say what a breaker in one tab does and does not do for the servers behind it, and read the output of a virtual-clock lab with a product page and 200 simulated browsers.
Think of a lift with a sign. When the lift has failed three times in a row, a good building puts up "Out of order, back at 10:30" and people take the stairs at once. A bad building lets every visitor press the button, wait a minute and discover the fault alone. A circuit breaker is the sign: after enough recent failures it stops sending calls and says so immediately, and after a pause it lets one visitor test the lift before the sign comes down.
A front end has the same problem on every page that depends on several services. This lesson is the dedicated treatment of the idea in the browser. Client Retries, Exponential Backoff and Jitter covers what happens after one failure, and Error, Loading and Empty States covers how a screen shows a failure. The back-end version, with thread isolation and the bulkhead, is Circuit Breaker and Bulkhead. The planned lessons Graceful Degradation and Error Boundaries cover page-wide rules and render errors.
The running example is a grocery product page with three sections that each call a different service: price and stock (essential), recommendations (optional) and reviews (optional). All times and counts are illustrative virtual numbers unless a source is named.
The core idea
- A breaker is a small state machine around calls to one dependency. While it looks healthy it counts outcomes and lets calls through (closed). When recent failures pass a threshold it refuses calls at once (open). After a wait it lets a few trial calls through (half-open): if they succeed it closes, and if one fails it opens again.
- A breaker answers "should I call?", not "what do I show?". The second question is the fallback, and it is a product decision per section.
- In the browser, the breaker belongs to one tab. It makes that user's page fast and calm. It helps a struggling server only as far as many clients behave the same way, which the lab measures.
Why the browser needs one
A timeout bounds one call; it says nothing about the next, which waits just as long. The Azure Architecture Center says a circuit breaker "prevents an application from performing an operation that's likely to fail", unlike retry, which expects the operation to eventually succeed, and says the two can be combined if retry logic stops when the breaker says the fault is not transient. In a browser the cost of calling a dead service is the user's patience, battery and data, and a page whose sections all wait on the slowest one.
Figure 1. One breaker per dependency in the data layer
How to read this: each section reaches its service through its own breaker. When recommendations fails, only its breaker opens. One breaker over all three would hide the healthy ones too, the "resource differentiation" mistake the Azure page warns about.
The states and what moves between them
The three states follow the Azure page and Martin Fowler's article. Closed: calls go through and failures are counted. Open: calls fail immediately and a timer runs. Half-open: when the timer ends, a limited number of calls pass; if they succeed the breaker closes and the failure counter resets, and if any fails it opens again and restarts the timer. The Azure page says half-open helps prevent a recovering service from being flooded.
Figure 2. The three states
How to read this: the only road back to closed goes through half-open, so a recovering service is tested with a few calls first.
Illustration 1: a minimal example. A breaker with a window of 4, a 50 percent threshold and a minimum of 4 calls opens when 2 of the last 4 have failed, stays open for its wait, then admits trial calls.
What counts as a failure
Fowler's warning applies in the browser: "Not all errors should trip the circuit, some should reflect normal failures and be dealt with as part of regular logic." Resilience4j lets you list exceptions that are ignored: they "neither count as a failure nor success".
The browser adds a trap. MDN says a fetch() promise only rejects when the request fails, not when the server answers 404 or 504, so a data layer must turn a Response into an outcome itself. The lab's rule, a choice and not a standard:
| Reply | Counted as | Why |
|---|---|---|
| 2xx | success | The dependency answered |
| 4xx (for example 404) | ignored | The request was wrong or refused; this says nothing about health |
| 5xx | failure | The dependency or something behind it is broken |
| Network error | failure | fetch() rejected |
| Timeout | failure | Slow is a failure the user can see |
A team might treat 429 differently, as a request to wait; the lab ignores it. For timeouts, AbortSignal.timeout() aborts with a TimeoutError DOMException, and MDN notes the timeout is based on active time, paused while the document is in the back-forward cache. A dependency that answers too slowly raises no error, so map "too slow" to a timeout, as Resilience4j does with its slow-call threshold.
Fallbacks: what to show while the breaker refuses
A refused call has to produce something. The Azure page says the open state can return a default value meaningful to the application. The right choice depends on how essential the section is.
Figure 3. From a call to a view
a call?"} B -->|"no"| F B -->|"yes"| C["Send request"] C --> D{"Reply"} D -->|"2xx"| L["Live data
(remember it)"] D -->|"4xx or failure"| F{"Fallback policy"} F -->|"recent last answer"| S["Stale data
with its age"] F -->|"optional, none"| H["Hide or placeholder"] F -->|"essential"| E["Error with
try again in N s"]
How to read this: the breaker only decides the first diamond. The fallback is the same whether the call was refused or failed.
- Stale data when old data is still true enough: the last good answer, with its age, only while younger than a limit you choose. See Server State, Caching and Revalidation.
- Hide an optional section, or leave a placeholder that keeps the layout. Recommendations that cannot load are better absent than shown as an error box mid-purchase.
- An error with a wait time for an essential section. An open breaker knows how long is left, so the message can say "try again in 3 seconds". The lab's
retryAfterMs()returns it.
A refusal is an ordinary return value, not a thrown exception, so no error boundary is involved: React's documentation says error boundaries do not catch errors in event handlers or asynchronous code, so a failed request must become state before it changes what renders.
Illustration 2: the realistic example
The product page loads once a second in the lab. Recommendations is down from 3000 to 9000 ms and price from 5000 to 6500 ms. Recommendations is optional with a stale fallback up to 2500 ms old; price is essential with no fallback. Each breaker uses a window of 4 calls, a 50 percent threshold, a 3000 ms wait and 2 trial calls.
Build it
The lab is examples/frontend/labs/client-circuit-breaker, plain TypeScript: breaker.ts (the state machine, time and randomness injected), widget.ts (a section with a breaker, a last-good cache and a fallback policy), fleet.ts (many browsers, each with its own breaker) and a demo on a virtual clock, so nothing waits. The 29 tests passed with Node 26.13.1 and Vitest 5.1.0, and the type check passed.
cd examples/frontend/labs/client-circuit-breaker
../../node_modules/.bin/vitest run
node src/demo.ts
Expected output, captured from a real run (the product page scenario, in full):
=== Product page, one load per second. Recommendations is down 3000-9000, price 5000-6500
(sent = the request went out; refused = the breaker did not let it out)
t(ms) recommendations price
0 live [sent, closed] live [sent, closed]
1000 live [sent, closed] live [sent, closed]
2000 live [sent, closed] live [sent, closed]
3000 stale (1s old) [sent, closed] live [sent, closed]
4000 stale (2s old) [sent, open] live [sent, closed]
5000 hidden [refused, open] error, try again in 0s [sent, closed]
6000 hidden [refused, open] error, try again in 3s [sent, open]
7000 hidden [sent, open] error, try again in 2s [refused, open]
8000 hidden [refused, open] error, try again in 1s [refused, open]
9000 hidden [refused, open] live [sent, half-open]
10000 live [sent, half-open] live [sent, closed]
11000 live [sent, closed] live [sent, closed]
12000 live [sent, closed] live [sent, closed]
13000 live [sent, closed] live [sent, closed]
breaker transitions:
t= 4000 recommendations: closed -> open
t= 6000 price: closed -> open
t= 7000 recommendations: open -> half-open
t= 7000 recommendations: half-open -> open
t= 9000 price: open -> half-open
t=10000 recommendations: open -> half-open
t=10000 price: half-open -> closed
t=11000 recommendations: half-open -> closed
Read it in order. At 4000 ms the second failure fills the window to 50 percent and the recommendations breaker opens; every later call is refused and costs nothing. Stale data older than 2500 ms is no longer shown, so the section is hidden. At 7000 ms the wait ends, the trial call fails and the breaker reopens. At 10000 ms the dependency is back, the trial succeeds, and at 11000 ms the second trial closes the breaker. Price is essential, so once its breaker opens at 6000 ms the section says how long is left (3s, 2s, 1s) until a trial at 9000 ms succeeds. At 5000 ms it says 0s because the breaker is still closed: a wait time means something only once the breaker is open.
The run also prints the classification table above. The tests also check that a result arriving after the breaker changed state is dropped, a 404 never opens the breaker, and an open breaker sends no request.
Break it. In breaker.ts, make the half-open branch of onOutcome ignore a failed trial (remove the if (outcome === "failure") return this.open(); line). Three tests fail (this was run: 3 failed, 26 passed), including "reopens and restarts the timer when a trial call fails". Restore the line and run the tests again.
What the model leaves out. Slow-call detection (map slowness to a timeout yourself), time-based windows, sharing state across tabs, and persistence across a reload.
A breaker lives in one tab
A breaker's state is a few numbers in memory. That has three consequences.
- Each tab learns alone. Three tabs send failing calls until each breaker opens. Sharing state needs a channel such as the one in Cross-Tab Sync with BroadcastChannel, at the price of more state.
- A reload starts closed. The first few failing calls teach it again, which is usually acceptable.
- Timers are unreliable in the background. MDN says browsers enforce a minimum timeout delay in inactive tabs, so the lab never relies on a timer: it compares the clock when the next call arrives.
Illustration 3: the failure example, a herd of clients
A client breaker protects the user's experience; the server only feels it when many clients have tripped, and then in a different pattern. The lab runs 200 browsers that poll once a second while the dependency is down from 10 s to 40 s. Each has its own breaker (window 4, 50 percent, 5000 ms wait, one trial call) and a random start offset. All numbers are illustrative.
Expected output, captured from a real run (the 200-browser scenario):
=== 200 browsers poll every 1000 ms, the dependency is down from 10 s to 40 s (requests that reach it)
setup all 30 s last 15 s peak, 1 s of last 15 s
no breaker 6000 3000 200
breaker, no jitter on the open time 1400 600 200
breaker, 0 to 5000 ms jitter on the open time 1019 397 38
Without a breaker the dependency receives every poll, 6000 requests. With breakers it receives 1400, but in the last 15 seconds its busiest second is still 200 requests, as many as with none: every browser opened its breaker at about the same moment, so all try again after the same wait. A random 0 to 5000 ms added to each open period cuts the total to 1019 and the busiest second to 38. The Google SRE book's advice to always use randomized exponential backoff when scheduling retries is the same idea. The jitter is the lab's design, and the numbers belong to its made-up scenario.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Breaker per dependency | A failing service does not hide healthy ones | More state and more fallbacks to design |
| Short open time | Recovers quickly | Trial calls hit a service that is still down |
| Long open time | Gentle on a recovering service | Users see the fallback after it has recovered |
| Stale fallback | Page stays useful | Data may be out of date and must say so |
| State kept in memory | Simple, no storage | Each tab and each reload learns again |
The other side of this topic
On the server the same pattern protects threads and connection pools and is paired with a bulkhead; see Circuit Breaker and Bulkhead and Load Shedding and Retry Storms.
In practice: the product page when recommendations goes down
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The recommendations service of a grocery marketplace degrades one evening: calls hang until the client timeout. The product page waits for it before showing the "Add to basket" button, so conversion drops, and support hears "the page is slow".
Starting architecture
Figure 4. Starting point: every section waits for its own request
How to read this: the warning box is the page that treats the three requests as one. Each failing visitor waits out the full timeout again, because nothing remembers that the last ones failed.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Shorter timeouts only | Bounds each wait | Every visitor still calls | Cuts good slow answers |
| Retries with backoff | Rides out brief faults | More calls to a failing service | Amplifies the outage |
| Breaker and fallback per section | Fast failure; page stays usable | State and fallbacks to maintain | A wrong failure rule hides a healthy section |
The decision
| Field | Decision record |
|---|---|
| Context | An optional section blocks an essential one when its dependency fails. |
| Decision | One breaker per dependency in the data layer. Recommendations: stale for a short time, then hidden. Price: no fallback, an error with the wait time. Timeouts count as failures; 4xx are ignored. Jitter on the open time. |
| Consequences, good | The purchase path no longer depends on an optional service; failures are quick. |
| Consequences, bad | More states per section to design and test; stale data can mislead if its age is not shown. |
| Revisit when | Several tabs or a service worker make per-tab state a problem, or the server returns a wait hint. |
Rollout and verification
- Write the table of sections, with how essential each is and its fallback, before coding.
- Test the breaker and each fallback on a virtual clock, then force the failures by hand: a hanging service, a 503, a 404, a recovery.
- Log every state change with the dependency name. Fowler says breaker behavior is often a good source of warnings about deeper troubles.
The 2 a.m. failure
A release changes the reviews request so the service answers 400 for some products. The team counted every non-2xx reply as a failure, so the reviews breaker opens for all products, and the section vanishes site-wide although the service is healthy.
First three checks: (1) look at the breaker transitions and the reply statuses that opened it; (2) check whether 4xx replies are counted; (3) check whether one breaker covers requests that fail independently. Mitigation: deploy the rule that ignores 4xx. Follow-up: a test that a run of 404 and 400 replies leaves the breaker closed, as the lab has.
Architect's notes
- One breaker per dependency, not per page and not per URL: group calls that fail together.
- Decide the fallback before the threshold. The user sees the fallback; the threshold only picks when.
- Keep the breaker pure, with time and randomness injected, so it is testable without waiting.
- Put retry outside the breaker and stop it when the breaker refuses.
- Emit state changes to monitoring. A breaker that opens silently looks like a missing feature.
Common mistakes
- One breaker for every dependency.
- Counting 4xx replies as failures, or trusting
fetch()to throw on HTTP errors. - Relying on a timer in a background tab to reach half-open.
- No jitter, so every browser tests the service in the same second.
- Stale data without an age or a limit, or hiding an essential section as if it were optional.
Key takeaways
- A breaker decides whether to call; a fallback decides what to show.
- Closed counts, open refuses, half-open tests with a few calls.
- Count network errors, timeouts and 5xx; ignore 4xx.
- Pick each section's fallback by how essential it is: stale, hide, placeholder or an error with a wait.
- A breaker lives in one tab, so the server is spared only when many clients trip, and only if their tests are spread out.
Practice exercises
Exercise 1: Starter (30 min). Run the demo and list which price loads were sent and which refused. Explain why the wait at 5000 ms is 0s.
Exercise 2: Intermediate (2 hours). Add a test that a 429 with a Retry-After of 5000 ms opens the breaker for that long (the Azure page calls this accelerated circuit breaking), then implement it.
Exercise 3: Advanced (half day). Share breaker state between tabs with BroadcastChannel, and decide what two tabs that disagree should do.
Related reading
In this course:
- Client Retries, Exponential Backoff and Jitter: the layer outside the breaker.
- Error, Loading and Empty States: how a section shows a failure.
- Request Cancellation, Timeouts and Race Conditions: the timeout that turns slow into failed.
- Circuit Breaker and Bulkhead: the back-end view.
Official documentation
- Azure Architecture Center: Circuit Breaker pattern: states, retry versus breaker, considerations.
- Martin Fowler: CircuitBreaker: which errors trip it, logging and monitoring.
- Resilience4j: CircuitBreaker: thresholds, defaults and ignored exceptions.
- MDN: Window.fetch() and AbortSignal.timeout(): when a request rejects and how a timeout aborts.
- React: Component (error boundaries): what an error boundary does not catch.
- Google SRE book: Addressing Cascading Failures: retries, backoff and overload.