Skip to main content

Circuit Breaker Decisions

MediumReliabilitySimulationFault ToleranceBackend Systems

Description

A service client wraps calls to a flaky dependency in a circuit breaker. The breaker starts closed. While it is closed every call is attempted, and threshold consecutive failures trip the breaker open at the time of the failing call; a successful attempt resets the consecutive failure count. While the breaker is open, a call that arrives less than cooldownSeconds after it opened is rejected without being attempted. The first call to arrive once the cooldown has elapsed is attempted as a trial: if it succeeds the breaker closes with the failure count reset, and if it fails the breaker opens again from that call's time. Given threshold, cooldownSeconds, timestamps (the arrival time of each call, in non-decreasing order), and outcomes (1 if the call would succeed when attempted, 0 if it would fail), return one boolean per call: true if the call was attempted and false if it was rejected. A rejected call's outcome is ignored.

Examples

Input:threshold = 2, cooldownSeconds = 5, timestamps = [0,1,2,6,7], outcomes = [0,0,1,1,0]
Output:[true,true,false,true,true]
Explanation:

The calls at times 0 and 1 both fail, which reaches the threshold of 2 and opens the breaker at time 1. The call at time 2 arrives only 1 second later, so it is rejected. The call at time 6 arrives 5 seconds after opening, so it is attempted as a trial; it succeeds and the breaker closes. The call at time 7 is attempted normally and its failure is the first of a new streak.

Input:threshold = 1, cooldownSeconds = 10, timestamps = [0,3,10,12,20], outcomes = [0,1,0,1,1]
Output:[true,false,true,false,true]
Explanation:

A single failure trips this breaker, so the call at time 0 opens it. The call at time 3 is rejected. The call at time 10 is the trial after the cooldown; it fails, so the breaker opens again from time 10 and the call at time 12 is rejected. The call at time 20 is the next trial and succeeds, closing the breaker.

Input:threshold = 3, cooldownSeconds = 2, timestamps = [0,0,1,1,2], outcomes = [0,1,0,0,1]
Output:[true,true,true,true,true]
Explanation:

The breaker never trips because the failures are never three in a row: the success at time 0 resets the count after one failure, and the two failures at time 1 are followed by a success at time 2 before a third failure arrives. Every call is attempted.

Constraints

  • •1 ≤ threshold ≤ 100
  • •0 ≤ cooldownSeconds ≤ 10⁶
  • •1 ≤ timestamps.length = outcomes.length ≤ 10⁴
  • •0 ≤ timestamps[i] ≤ 10⁹, non-decreasing
  • •outcomes[i] is 0 or 1

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.