When a downstream dependency starts failing, hammering it with retries makes things worse — you pile load onto a service that is already struggling and you make your own callers wait on calls that are doomed to fail. The circuit breaker pattern fixes this by failing fast: after enough failures it stops calling the dependency entirely for a cooldown period, then cautiously tests whether it has recovered.
A breaker has three states:
Implement CircuitBreaker:
__init__(self, failure_threshold: int, cooldown_ms: int, success_threshold: int = 1)call(self, timestamp_ms: int, succeeds: bool) -> bool — process one request arriving at timestamp_ms. succeeds is what the underlying dependency would return if called. Return True if the request was allowed through and succeeded; return False if it was rejected (OPEN) or if it was allowed through but failed.Behavior:
failure_threshold consecutive failures, trip to OPEN (record the time).cooldown_ms since opening → move to HALF_OPEN and treat this request as a trial.success_threshold successes, close the breaker. Return True.Constraints:
timestamp_ms is non-decreasing across callsfailure_threshold >= 1, cooldown_ms >= 0, success_threshold >= 1Official solution locked
Give the problem a real attempt before peeking — revealing it affects your credit for this problem for 4 hours.