Simulate a circuit breaker in front of a model API
Why it matters LLM gateways put circuit breakers in front of each provider to fail over quickly during outages.
A circuit breaker stops calling a failing model endpoint and retries after a cooldown.
Write circuit_breaker(events, fail_threshold, cooldown). events is a list of (time, ok) in time order, each one an attempted call that would succeed if ok is True. States: "closed" (calls go through), "open" (calls rejected without trying), "half_open" (one trial call). In closed state, count consecutive failures; on reaching fail_threshold switch to open at that time. In open state, a call at time >= open_time + cooldown becomes a trial in half_open: if it succeeds go closed (reset count), else go open again with open_time = that time. Calls while open and before the cooldown are rejected. Return the list of outcomes per event: "ok", "fail" or "rejected".
def circuit_breaker(events, fail_threshold, cooldown)Example
circuit_breaker([(0, False), (1, False), (2, True), (10, True)], 2, 5) is ["fail", "fail", "rejected", "ok"].
Understand the idea
A circuit breaker protects your app from a failing model endpoint, like a fuse at home. While closed, calls go through and consecutive failures are counted. After enough failures it opens and rejects calls instantly, without trying, so users do not wait on timeouts. After a cooldown it lets one trial call through (half open): success closes it again, failure reopens it with a fresh cooldown. Worked example: events [(0, F), (1, F), (3, T), (6, F), (7, T), (13, T)], threshold 2, cooldown 5. t0 fails (count 1). t1 fails (count 2), so it opens at time 1. t3 is before 1 + 5 = 6, rejected. t6 reaches the cooldown, a trial, which fails, so it reopens at 6. t7 is before 11, rejected. t13 is a trial that succeeds, ok, and it closes. Outcomes [fail, fail, rejected, fail, rejected, ok]. Rule: closed: an ok call resets the count; a failure adds 1, opening at that time when the count hits the threshold. open: time < open_time + cooldown means rejected; otherwise run the call as a trial. Used in: resilient LLM API clients and fallback routing.
Shapes and data flow
closed --(N fails)--> open --(cooldown)--> half_open half_open --ok--> closed, --fail--> open