AlgoViz

Circuit breaker

medium 30 min

A 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

callCallerBreakerCLOSEDServicehealthy

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

Users100 a secondOrdersnormalPayment company0.2 s
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

    major

    A bad client sends 404s and 400s and opens the breaker for everybody.

    Wrong
    except Exception: failures += 1
    Right
    except (Timeout, ConnectionError, ServerError):    failures += 1
  • Tests that cannot reach the goal

    critical

    The old code never counted test calls down. With 3 allowed and 5 needed it stays half-open for ever.

    Wrong
    half_open_max_calls = 3success_threshold = 5
    Right
    assert success_threshold <= half_open_max_calls
  • One breaker for several services

    critical

    Reviews fails and payments is refused.

    Wrong
    breaker = Breaker()      # used everywhere
    Right
    breakers = {name: Breaker() for name in services}
  • Retrying a refusal

    major

    The breaker has just said no. Trying again fights it.

    Wrong
    retry(lambda: breaker.call(f), on=Exception)
    Right
    retry(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.