Skip to content
Coding · Medium · Reliability patterns · Target O(1) per call · Senior

Circuit breaker state machine

Implement a circuit breaker with closed, open and half-open states, driven by timestamps passed in, and get every transition exactly right.

Statement

Implement CircuitBreaker(failure_threshold, open_seconds, trial_calls) with three methods. allow(now) says whether a call may start, record(now, ok) reports how an admitted call ended, and state(now) returns "closed", "open" or "half_open". Every method is given the current time; the breaker never reads a clock.

Closed: every call is allowed. A failure adds one to a count of consecutive failures and a success sets the count back to zero. When the count reaches failure_threshold the breaker opens at that moment.

Open: no call is allowed, and a result that arrives from a call admitted earlier is ignored. Once now is at least open_seconds after the moment the breaker opened, it is half-open. Time alone causes this, so state(now) must report it even if nothing was called in between.

Half-open: allow admits at most trial_calls calls in total and refuses the rest. When trial_calls successes have been recorded the breaker closes with a failure count of zero. A single failure opens it again, and the open period starts from that failure. A result recorded while no trial is outstanding is ignored.

Examples

CircuitBreaker(3, 30, 2). The state shown is state(now) straight after the call.

record(0, False)   state → "closed"
record(1, False)   state → "closed"
record(2, False)   state → "open"        # third failure in a row
allow(3)           → False
state(31)          → "open"
state(32)          → "half_open"   # 2 + 30, on the dot
allow(32)          → True          # first trial
allow(32)          → True          # second trial
allow(32)          → False         # no trial slots left
record(33, True)   state → "half_open"
record(34, True)   state → "closed"

Constraints

now never decreases from one call to the next and may be fractional. failure_threshold and trial_calls are at least 1 and open_seconds is greater than 0. Up to 10⁵ calls, each in O(1). While the breaker is closed a result may be recorded without a matching allow, because every call is allowed there.

Free to try · sign in to save your attemptSolve it in the editor with visible tests
Open in the app