Circuit Breaker

Hard
ConcurrencyCircuit BreakerState MachineAtomic OperationsResilienceConcurrent Design

Problem Statement

Implement a thread-safe Circuit Breaker that wraps calls to an external service and prevents cascading failures. The circuit breaker has three states:

  • CLOSED (normal): Requests pass through. Count failures.
  • OPEN (tripped): Requests fail fast (no actual call). After a timeout, transitions to HALF_OPEN.
  • HALF_OPEN (recovery probe): Allow one request through. If it succeeds → CLOSED; if it fails → OPEN again.
class CircuitBreaker {
    public CircuitBreaker(int failureThreshold, long openTimeoutMs, int successThreshold) {}
    // Execute the supplier; handle circuit logic
    public <T> T execute(Supplier<T> operation) throws CircuitOpenException {}
    public CircuitState getState() {}
    public int getFailureCount() {}
    public void reset() {}
}

enum CircuitState { CLOSED, OPEN, HALF_OPEN }
class CircuitOpenException extends RuntimeException {}

Key Entities

  • State machine: Atomic state transitions (CLOSED→OPEN, OPEN→HALF_OPEN, HALF_OPEN→CLOSED/OPEN).
  • AtomicInteger failureCount: Thread-safe failure counter.
  • AtomicReference<CircuitState>: Current state with CAS-based transitions.
  • lastOpenTime: Timestamp when circuit opened; used to compute reset timeout.

Requirements

  1. CLOSED → OPEN when failureCount >= failureThreshold.
  2. OPEN → HALF_OPEN after openTimeoutMs milliseconds.
  3. HALF_OPEN → CLOSED after successThreshold consecutive successes.
  4. HALF_OPEN → OPEN on any single failure.
  5. All state transitions must be atomic and thread-safe.

Asked at: Netflix, Amazon, Microsoft, Uber, Google, LinkedIn, Swiggy, Zomato

!Constraints

- 1 ≤ failureThreshold ≤ 100 - openTimeoutMs ≥ 100 - 1 ≤ successThreshold ≤ 10 - Concurrent threads calling execute() must observe consistent state. - Only one thread should probe in HALF_OPEN state (others fail fast).
Output

Run or submit your code to see output here.