Cloud
Circuit Breaker
Checking the breaker's state is O(1) — instant. The real payoff: you avoid minutes of wasted timeouts across every caller during an outage.
The idea, in plain English
Think of the circuit breaker in your house. If something plugged in draws too much power, the breaker flips off ('trips') to stop a fire. A code circuit breaker does the same job. It sits between your app and a service it depends on, like a database or a payment API. If that service keeps failing, the breaker trips. It stops sending requests for a while. This gives the service time to recover. It also stops your app from waiting on calls that were never going to work.
How it works
- 1Closed (normal): requests flow through as usual. The breaker quietly counts how many fail in a row.
- 2Open (tripped): once failures hit a set limit, the breaker flips open. It rejects every request right away, with no waiting on a doomed call, for a set cooldown time.
- 3Half-open (testing the water): after the cooldown, the breaker lets exactly one test request through. If it succeeds, the breaker closes again and goes back to normal. If it fails, the breaker opens again and the cooldown restarts.
When you'd use it
Use this whenever your app calls another service over a network — an API, a database, a payment processor — that might be slow or down. Without a breaker, every caller keeps retrying a dead service. That wastes time and makes the outage worse for everyone.
Common beginner mistakes
- Setting the cooldown too short. Then the breaker keeps flipping open-closed-open ('flapping') on a service that hasn't really recovered.
- Skipping the half-open test and trusting the service again right away. One lucky request doesn't prove it's healthy.
- Counting every kind of error as a failure worth tripping the breaker. Some errors are the caller's fault, like a bad request, not the service's.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Call 1: failed -> state closed (1/3 failures)
Call 2: failed -> state closed (2/3 failures)
Call 3: failed -> state open (3/3 failures, breaker tripped)
Call 4: rejected -> circuit open, call skipped
Call 5: half-open trial succeeded -> state closed (breaker recovered)Not sure this is the right topic? See the learning paths → or where this leads →