Concurrency PatternCRITICAL8 min deep dive

Circuit Breaker Pattern Pattern

Detects failures and encapsulates the logic of preventing a failure from constantly recurring during maintenance, temporary external or system difficulties.

Real-World Mental Model / Metaphor:

An electrical circuit breaker in your house. If a wire shorts out, the breaker trips to prevent electrical fires and damage to appliances.

Interactive Runtime Simulator

Test and tweak inputs dynamically

Interactive Circuit Breaker Pattern SimulatorLIVE PLAYGROUND

Interact with the controls below to see how this design pattern executes in memory at runtime.

Category: Concurrency
Configure Chain Handlers (Toggle Failures):
CHAIN PIPELINE STATUS
Step 1: AuthHandler.check() -> PASSED
Step 2: RateLimitHandler.check() -> PASSED
Step 3: PayloadGuard.check() -> PASSED
The Problem It Solves

Cascading microservice failures: an unresponsive downstream API holds worker threads hostage until the entire calling service runs out of memory.

The Architectural Solution

Track failure rates in a rolling window across 3 states: CLOSED (healthy), OPEN (fail-fast immediately), and HALF-OPEN (testing trial requests).

Pattern Structure & Participants

ParticipantRole & ResponsibilityType
CircuitBreakerState machine tracking failure % and managing transitionsclass
CLOSED StateAll requests pass through to external dependencyclass
OPEN StateFail fast: return fallback or 503 without hitting dependencyclass
HALF-OPEN StateAllows limited trial requests to see if dependency healedclass
Collaboration Rules:
  • Failure rate > 50% -> trips CLOSED to OPEN
  • Wait duration expires -> transitions OPEN to HALF-OPEN
  • Trial calls succeed -> heals back to CLOSED

Production Code Implementation

Circuit Breaker Pattern.java
// Resilience4j Circuit Breaker in Spring Boot
@Service
public class PaymentGatewayClient {

    private final RestClient restClient;

    @CircuitBreaker(name = "paymentService", fallbackMethod = "fallbackPayment")
    public PaymentResponse charge(PaymentRequest request) {
        return restClient.post()
            .uri("/v1/charge")
            .body(request)
            .retrieve()
            .body(PaymentResponse.class);
    }

    // Fail-fast fallback executed when circuit is OPEN
    public PaymentResponse fallbackPayment(PaymentRequest request, Throwable ex) {
        System.out.println("Circuit OPEN: Payment service degraded. Queueing request.");
        return PaymentResponse.degradedQueue(request.getId());
    }
}
When to Use:
  • •Every outbound network call to external APIs, remote microservices, or databases over a network.
  • •To prevent cascading thread starvation in high-throughput distributed systems.
When to Avoid (Anti-Pattern):
  • •For local in-memory method calls within the same process.

Staff Engineering Interview Insights & Gotchas

  • Draw the 3-state state machine: CLOSED -> OPEN -> HALF-OPEN -> CLOSED.
  • Highlight how it saves thread pools from exhaustion during partner outages.