Problem · Array

Circuit Breaker State Machine

Learn this problem
MediumWise logoWiseFULLTIMEONSITE INTERVIEW

Problem statement

Simulate a circuit breaker over a finite sequence of request attempts. The breaker starts in CLOSED. Each row of requests is [timestamp, outcome], where timestamps are nondecreasing and outcome is SUCCESS or FAILURE.

  • In CLOSED, every request is allowed. A success resets the consecutive-failure count. A failure increments it. Reaching failureThreshold failures opens the breaker until timestamp + openDuration.
  • In OPEN, a request before the reopen time is rejected and its supplied outcome is ignored.
  • At or after the reopen time, the next request is the single HALF_OPEN probe. A successful probe closes and resets the breaker. A failed probe opens it again for another openDuration.

Rows with the same timestamp are processed in input order. Return one string per row: REJECTED:OPEN for a rejected request, or ALLOWED:<state-after-request> for an allowed request.

Function

runCircuitBreaker(requests: String[][], failureThreshold: int, openDuration: int) → String[]

Examples

Example 1

requests = [["0","SUCCESS"],["1","FAILURE"],["2","FAILURE"],["3","SUCCESS"],["7","SUCCESS"]]failureThreshold = 2openDuration = 4return = ["ALLOWED:CLOSED","ALLOWED:CLOSED","ALLOWED:OPEN","REJECTED:OPEN","ALLOWED:CLOSED"]

The failures at times 1 and 2 open the breaker until time 6. Time 3 is rejected, and the successful probe at time 7 closes it.

Example 2

requests = [["0","FAILURE"],["1","FAILURE"],["4","FAILURE"],["5","SUCCESS"],["7","SUCCESS"]]failureThreshold = 2openDuration = 3return = ["ALLOWED:CLOSED","ALLOWED:OPEN","ALLOWED:OPEN","REJECTED:OPEN","ALLOWED:CLOSED"]

The failed half-open probe at time 4 reopens the breaker until time 7. The time-5 row is rejected.

Constraints

  • 1 <= requests.length <= 200000.
  • Every row has two strings: a nonnegative decimal timestamp and either SUCCESS or FAILURE.
  • Timestamps are nondecreasing and at most 10^18.
  • 1 <= failureThreshold <= 10^9.
  • 1 <= openDuration <= 2000000000.
drafts saved locally
public String[] runCircuitBreaker(String[][] requests, int failureThreshold, int openDuration) {
    // Write your code here.
}
requests[["0","SUCCESS"],["1","FAILURE"],["2","FAILURE"],["3","SUCCESS"],["7","SUCCESS"]]
failureThreshold2
openDuration4
expected["ALLOWED:CLOSED", "ALLOWED:CLOSED", "ALLOWED:OPEN", "REJECTED:OPEN", "ALLOWED:CLOSED"]
checking account