CODING CHALLENGE · N°23

Circuit Breaker

Medium SystemsReliabilityDistributed Systems

The pattern that stops one failing dependency from taking down the fleet: trip after consecutive failures, fail fast while open, probe once after a cooldown. Implement the closed → open → half-open state machine as a pure replay.

The problem

Implement a circuit breaker as a pure replay: given threshold (consecutive failures that trip it), cooldown (seconds it stays open), and calls — a non-decreasing list of [time, succeeds] pairs describing calls and whether the dependency would succeed — return one outcome per call: "ok", "fail", or "rejected". Rules: while closed, calls go through; a success resets the consecutive-failure count, a failure increments it, and reaching threshold trips the breaker open at that call’s time. While open, calls before opened_at + cooldown are "rejected" without touching the dependency. The first call at or after that moment is a half-open probe: it goes through — success closes the breaker (count reset), failure re-opens it from the probe’s time.

EXAMPLE 1
Input threshold = 2, cooldown = 10, calls = [[0,false],[1,false],[2,true],[11,true],[12,true]]
Output ["fail","fail","rejected","ok","ok"]
trips at t=1, rejects during cooldown, probe at t=11 heals it
EXAMPLE 2
Input probe fails
Output breaker re-opens for another full cooldown
half-open is one chance, not a reopening of the floodgates
EXAMPLE 3
Input success between failures
Output the consecutive count resets — no trip
threshold counts CONSECUTIVE failures
CONSTRAINTS
  • Outcomes are exactly "ok", "fail", or "rejected".
  • The count is of consecutive failures; any success while closed resets it to 0.
  • Rejected calls never touch the dependency and do not change the failure count.
  • The half-open probe is a single call; its result alone decides closed vs re-opened.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement circuit_breaker(threshold, cooldown, calls) → list of "ok" / "fail" / "rejected", replaying the closed → open → half-open state machine.

HINTS — 4 IDEAS
  1. Track three things: state (closed/open), consecutive failure count, and when the breaker opened.
  2. Open + time < opened_at + cooldown → "rejected", and nothing else changes.
  3. Open + time ≥ opened_at + cooldown → treat as the half-open probe: run the call, then either close (success) or re-open with opened_at = this time.
  4. Trip check happens after counting a closed-state failure: count == threshold → open, opened_at = now.
CPython · WebAssembly

Explore the topic

See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.