Implement a circuit breaker with CLOSED, OPEN and HALF_OPEN states
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a circuit breaker that monitors failures of downstream calls and trips to prevent cascading failures in a distributed system.
The breaker has three states: `CLOSED` (requests flow normally), `OPEN` (requests are short-circuited and rejected), and `HALF_OPEN` (a single probe request is allowed through to test whether the downstream has recovered).
While `CLOSED`, every consecutive failure increments a counter; once it reaches `failureThreshold`, the breaker moves to `OPEN` and records the trip time. While `OPEN`, calls are rejected until `recoveryTimeoutMs` has elapsed since the trip time, after which the next call moves the breaker to `HALF_OPEN`. In `HALF_OPEN`, a single probe is allowed: a success closes the breaker and resets the failure counter, while a failure trips it back to `OPEN`. Any success while `CLOSED` resets the failure counter to `0`.
The constructor takes `failureThreshold` and `recoveryTimeoutMs`. Implement these methods:
- `allowRequest(timestampMs: int) -> bool` returns `True` if a request is allowed at the given timestamp. It may move the breaker from `OPEN` to `HALF_OPEN` once the recovery timeout has elapsed. The call that makes that move is the probe, and later calls return `False` until the probe's result is recorded.
- `recordSuccess()` records a successful call. It resets the failure counter and closes the breaker.
- `recordFailure(timestampMs: int)` records a failed call at the given timestamp. It trips the breaker to `OPEN` when the failure threshold is reached in `CLOSED`, or immediately when in `HALF_OPEN`.
- `getState() -> str` returns the current state as `"CLOSED"`, `"OPEN"` or `"HALF_OPEN"` without changing it.
Example 1, with threshold 2 and a 500 ms recovery timeout:
```text
Input:
["CircuitBreaker", "recordFailure", "recordFailure", "getState", "allowRequest", "getState", "recordFailure", "getState", "allowRequest"]
[[2, 500], [0], [100], [], [700], [], [750], [], [900]]
Output: [null, null, null, "OPEN", true, "HALF_OPEN", null, "OPEN", false]
Explanation:
cb = CircuitBreaker(2, 500)
cb.recordFailure(0) # failures: 1, state CLOSED
cb.recordFailure(100) # failures: 2, trips, openedAt = 100
cb.getState() # "OPEN"
cb.allowRequest(700) # True: 700 - 100 = 600 >= 500, this call is the probe
cb.getState() # "HALF_OPEN"
cb.recordFailure(750) # probe failed: OPEN again, openedAt = 750
cb.getState() # "OPEN"
cb.allowRequest(900) # False: 900 - 750 = 150 < 500
```
Example 2, with threshold 3 and a 1000 ms recovery timeout, shows a success resetting the counter and the single probe:
```text
Input:
["CircuitBreaker", "recordFailure", "recordFailure", "recordSuccess", "recordFailure", "getState", "recordFailure", "recordFailure", "getState", "allowRequest", "allowRequest", "allowRequest", "recordSuccess", "getState", "allowRequest"]
[[3, 1000], [10], [20], [], [30], [], [40], [50], [], [1049], [1050], [1060], [], [], [1070]]
Output: [null, null, null, null, null, "CLOSED", null, null, "OPEN", false, true, false, null, "CLOSED", true]
Explanation:
cb = CircuitBreaker(3, 1000)
cb.recordFailure(10) # failures: 1
cb.recordFailure(20) # failures: 2
cb.recordSuccess() # failures reset to 0
cb.recordFailure(30) # failures: 1
cb.getState() # "CLOSED"
cb.recordFailure(40) # failures: 2
cb.recordFailure(50) # failures: 3, trips, openedAt = 50
cb.getState() # "OPEN"
cb.allowRequest(1049) # False: 1049 - 50 = 999 < 1000
cb.allowRequest(1050) # True: exactly 1000 ms elapsed, this call is the probe
cb.allowRequest(1060) # False: the probe has not reported back yet
cb.recordSuccess() # probe succeeded: CLOSED, failures 0
cb.getState() # "CLOSED"
cb.allowRequest(1070) # True
```
```hint Fill in a transition table
Write the three states as rows and the three state-changing calls as columns, then decide every cell. The statement spells out some cells and only implies others. Check what your allowRequest returns when it is called twice in HALF_OPEN.
```
```hint No timer needed
The breaker only learns the time when a caller passes a timestamp. Think about which single value you must store so that a later call can tell whether the recovery timeout has passed.
```
### Constraints & Assumptions
- `1 <= failureThreshold <= 100`
- `1 <= recoveryTimeoutMs <= 10^9`
- `0 <= timestampMs <= 10^12`, and timestamps are non-decreasing across calls
- At most `10^4` operations are performed, one at a time
### Clarifying Questions to Ask
- What should a failure reported while the breaker is `OPEN` do? It can happen when a call admitted before the trip finishes late.
- Does exactly `recoveryTimeoutMs` of elapsed time count as elapsed, or must strictly more time pass?
- Will several threads call the breaker at once, so that two callers could race for the probe?
- If the probe's result never comes back, should the breaker eventually let another probe through?
### What a Strong Answer Covers
- Defined behavior for every method in every state, including the combinations the statement leaves implicit.
- How the recovery timeout is detected from caller-supplied timestamps, with the boundary at exactly `recoveryTimeoutMs` handled.
- How `HALF_OPEN` limits traffic to one probe and how the probe's result settles the state.
- When the failure counter resets, so that it really counts consecutive failures.
- Constant time and memory per operation, and what would change with concurrent callers.
### Follow-up Questions
- How would you make the breaker thread-safe so that exactly one of many concurrent callers gets the probe?
- How would you change the trip rule from consecutive failures to a failure rate over the last N calls or the last T seconds?
- Should slow calls count as failures, and which errors (for example client-side 4xx responses) should not count at all?
- The service runs on many instances. Should each instance keep its own breaker or should they share state, and what does sharing cost?
Overview: Implement a three-state circuit breaker (CLOSED, OPEN, HALF_OPEN) with a consecutive-failure threshold, a recovery timeout and a single probe request. It tests state machine design, working with caller-supplied timestamps, and edge cases such as the timeout boundary and late call results.