AlgoMaster Logo
AlgoMasterSimulate a Circuit Breakermedium

Simulate a Circuit Breaker

medium

A circuit breaker protects a caller from repeatedly invoking an unhealthy dependency. It starts closed, opens after a run of failures, and later becomes half-open so one recovery probe can decide whether normal calls should resume.

Design a CircuitBreakerSimulator class:

  • CircuitBreakerSimulator() creates a stateless simulator.
  • String[] simulate(String[] events, int failureThreshold) returns the breaker's state after every event.

The initial state is "closed", and the initial consecutive-failure count is zero. Every event is one of "success", "failure", or "timeout".

Apply these transition rules:

  • Closed: A success resets the consecutive-failure count to zero and leaves the breaker closed. A failure increments the count and opens the breaker once the count reaches failureThreshold. A timeout leaves both the state and the count unchanged.
  • Open: A timeout moves the breaker to "half_open". Success and failure events are rejected and leave the breaker open.
  • Half-open: A success resets the consecutive-failure count to zero and closes the breaker. A failure reopens the breaker. A timeout leaves the breaker half-open.

Return the state after applying each event. Every call to simulate starts with a fresh breaker; state must not carry across calls.

Example 1:

Input:

Output:

Explanation: The second consecutive failure reaches the threshold and opens the breaker. The timeout begins a half-open trial, and the successful trial closes the breaker.

Example 2:

Input:

Output:

Explanation: The timeout permits one trial, but that trial fails. A failed half-open probe immediately reopens the breaker.

Constraints

  • 0 <= events.length <= 10^5
  • events[i] is "success", "failure", or "timeout".
  • 1 <= failureThreshold <= 10^5
  • States are returned exactly as "closed", "open", and "half_open".
  • At most 100 calls are made to simulate.
Hints

Loading...
CallReturns
new CircuitBreakerSimulator()null
simulate(["failure","failure","timeout","success"], 2)["closed","open","half_open","closed"]

The second consecutive failure opens the breaker. Timeout permits a half-open probe, and its success closes the breaker.

Run checks these cases. Submit also runs a larger hidden set.