Circuit Breaker Pattern

Stop hammering a dependency that is already down; fail fast, then cautiously probe for recovery.

A circuit breaker wraps calls to an unreliable remote dependency and moves between three states so that cascading failures don't take down the whole system.

States:

  1. CLOSED (normal operation):
    • Calls pass through to the dependency.
    • Each failure increments a consecutive-failure counter.
    • A success resets the counter to 0.
    • When the counter reaches failureThreshold, the breaker trips: it prints "TRIPPED -> OPEN" and records the trip timestamp.
  2. OPEN (tripped):
    • Calls fail immediately without touching the dependency: "FAST_FAIL (Circuit Open)".
    • Once recoveryTimeoutMs have elapsed since the trip, the next call is treated as a probe and the breaker moves to HALF_OPEN before evaluating that call's outcome.
  3. HALF_OPEN (probing):
    • Exactly one call is admitted as a trial.
    • If it succeeds: reset the failure counter to 0, transition to CLOSED, print "PROBE SUCCESS -> CLOSED".
    • If it fails: transition back to OPEN, reset the trip timestamp to now, print "PROBE FAILED -> OPEN".

Successful calls in CLOSED print "OK (<consecutiveFailures> failures)" and failed calls that don't trip the breaker print "FAIL (<consecutiveFailures>/<failureThreshold>)".

Input format: CONFIG:<failureThreshold>,<recoveryTimeoutMs> then CALL:<timestampMs>,<OK|FAIL>.

Input:  CONFIG:2,1000;CALL:0,FAIL;CALL:50,FAIL;CALL:100,FAIL;CALL:1200,FAIL;CALL:2300,OK;CALL:2350,FAIL
Output: FAIL (1/2)
        TRIPPED -> OPEN
        FAST_FAIL (Circuit Open)
        PROBE FAILED -> OPEN
        PROBE SUCCESS -> CLOSED
        FAIL (1/2)

Constraints

  • No call reaches the dependency while OPEN and the cooldown has not elapsed.
  • Only a single call is ever evaluated as the HALF_OPEN probe.
  • The failure counter used for the threshold check always resets to 0 on any success.
Ad SpaceGoogle AdSense active for guests & free-tier learners.