Circuit breaker
medium 30 minA circuit breaker watches the calls to one dependency.
See it run
Three states, the evidence to change them, and what can go wrong in between.
Operations
The three states
Threshold 3 failures in a row, 2 successes close it.
Step 1 of 8
Closed
failures in a row
0 of 3
Calls pass. A success sets the counter to zero.
Step 1: Closed
if state == OPEN: if now - opened_at < wait: raise Refused state, ok = HALF_OPEN, 0try: result = send() if state == HALF_OPEN: ok += 1; close_if(ok >= 2) else: failures = 0except Failure: failures += 1 if state == HALF_OPEN or failures >= 3: open()- Good for
- Both sides
- Costs
- Refuses some good calls
- Only a timeout
- every call waits for it
Closed is the good state. Think of current that flows.
In the real world
The same circuit breaker doing real jobs. Pick one and step through it.
100 orders a second, a timeout of 1 second, 200 threads.
Step 1 of 4
Healthy
- Threads waiting (of 200)
- 20
20 threads
A payment takes 0.2 seconds: 100 x 0.2 = 20 threads.
Step 1: Healthy
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Counting the caller's mistakes
majorA bad client sends 404s and 400s and opens the breaker for everybody.
Wrongexcept Exception: failures += 1Rightexcept (Timeout, ConnectionError, ServerError): failures += 1Tests that cannot reach the goal
criticalThe old code never counted test calls down. With 3 allowed and 5 needed it stays half-open for ever.
Wronghalf_open_max_calls = 3success_threshold = 5Rightassert success_threshold <= half_open_max_callsOne breaker for several services
criticalReviews fails and payments is refused.
Wrongbreaker = Breaker() # used everywhereRightbreakers = {name: Breaker() for name in services}Retrying a refusal
majorThe breaker has just said no. Trying again fights it.
Wrongretry(lambda: breaker.call(f), on=Exception)Rightretry(lambda: breaker.call(f), on=Temporary) # not Refused
Interview tips
How to explain it
- It learns from failures.
- It refuses quickly.
- It tests carefully.
Memory trick: COH
- Closed: normal.
- Open: fast-fail.
- Half-open: testing.
Four numbers
- Rate and minimum.
- Open time.
- Test calls.
- Successes needed.
Never alone
- Timeout inside.
- Fallback outside.
- Alert beside.