Circuit Breaker
Resilience4j CircuitBreaker — states, thresholds, fallback, health indicators
- Configure Resilience4j CircuitBreaker with failure rate thresholds
- Implement a fallback method for graceful degradation
- Monitor circuit breaker state transitions with Actuator health
Overview
The Circuit Breaker pattern is a design pattern used in microservices architecture to prevent an application from making repeated calls to a downstream service that is likely to fail. It acts as a protective mechanism between services, monitoring failures and automatically stopping calls to a failing service to allow it time to recover.
The name "Circuit Breaker" comes from electrical engineering — just like a physical circuit breaker in your home that trips when there is a power surge to protect your appliances, the software circuit breaker "trips" (opens) when too many failures are detected, protecting the system from cascading failures.
Why This Concept Exists
The Problem
Consider a microservices architecture where an Order Service calls a Product Service:
1Order Service ──────────────▶ Product ServiceNow assume Product Service goes down. Every call from Order Service to Product Service will fail. Two major problems arise:
- Unnecessary load on the failing service: Every failed call adds load to Product Service. Since it is already struggling, this extra load can delay its recovery. We are essentially kicking a service while it is down.
- Resource waste in Order Service: Each call to the (unavailable) Product Service:
- Blocks a thread while waiting for a response or timeout
- Increases latency — Order Service must wait until the connection times out before it can send an error to the client
- If there are thousands of concurrent calls, thousands of threads are blocked and wasted
The Solution
The Circuit Breaker solves this by giving Order Service awareness of the downstream service's health. When too many failures are detected, it stops further calls entirely and fails them immediately — without waiting. After some time, it tests whether the downstream service has recovered and, if so, resumes normal operation.
Definition
Circuit Breaker
is a fault-tolerance pattern that wraps calls to external services and monitors failures. When the failure rate exceeds a configured threshold, the circuit "opens" and all further calls are immediately rejected (fail-fast) without actually reaching the downstream service. After a wait period, the circuit transitions to a half-open state to test recovery, then either closes (resumes normal calls) or opens again (still failing).
Real-World Analogy
Think of the circuit breaker in your home's electrical panel:
- Closed (normal): Current flows freely through the circuit. All devices work.
- Open (tripped): Current is blocked. No electricity flows to the circuit. This protects devices from damage.
- Half-Open (testing): You reset the breaker to see if the fault has been cleared. If electricity flows normally, it stays closed. If it trips again, it opens once more.
State Diagram
The Three States Detailed Explanation
1. CLOSED State (Normal Operation)
- All calls are allowed to the downstream service.
- The circuit breaker monitors each call, tracking successes and failures within a sliding window.
- If the failure rate crosses the configured threshold, the circuit transitions to the Open state.
2. OPEN State (Blocking All Calls)
- No calls are allowed to the downstream service.
- All incoming calls are immediately rejected (fail-fast) — no waiting, no thread blocking.
- The fallback method is invoked for every rejected call.
- The circuit breaker schedules a timer (using
ScheduledThreadPoolExecutor) for the configured wait duration (e.g., 10 seconds). - After the wait duration expires, it automatically transitions to the Half-Open state.
3. HALF-OPEN State (Testing Recovery)
- A limited number of trial calls are allowed to the downstream service (e.g., 3 calls).
- The circuit breaker tracks the success rate of these trial calls.
- If 100% of trial calls succeed: Transition back to Closed state.
- If any trial call fails (success rate < 100%): Transition back to Open state and wait again.
Architecture Diagram
Sequence Diagram Full Circuit Breaker Lifecycle
Implementation with Resilience4j
Dependency (pom.xml)
The Circuit Breaker in Spring Boot is provided by the Resilience4j library. No separate dependency is required — it is included in the Resilience4j starter:
1<dependency>2 <groupId>io.github.resilience4j</groupId>3 <artifactId>resilience4j-spring-boot3</artifactId>4</dependency>5
6<!-- Also required for AOP support -->7<dependency>8 <groupId>org.springframework.boot</groupId>9 <artifactId>spring-boot-starter-aop</artifactId>10</dependency>The `@CircuitBreaker` Annotation
1@CircuitBreaker(name = "productService", fallbackMethod = "productServiceFallback")2public String invokeProductAPI(String productId) {3 // Call to downstream Product Service via Feign Client4 return productClient.getProductById(productId);5}6
7public String productServiceFallback(String productId, Throwable throwable) {8 // This method is invoked for EVERY failed attempt9 System.out.println("Fallback triggered for productId: " + productId);10 System.out.println("Reason: " + throwable.getMessage());11 return "Product service is currently unavailable. Please try later.";12}Line-by-Line Explanation:
| Line | Explanation |
|---|---|
@CircuitBreaker(name = "productService", ...) | Declares a circuit breaker with the name productService. This name must match the configuration key in application.properties. |
fallbackMethod = "productServiceFallback" | When the circuit breaker rejects a call (either because the call failed or the circuit is open), this method is invoked. |
invokeProductAPI(String productId) | The protected method. Any exception thrown here is tracked by the circuit breaker. |
productServiceFallback(String productId, Throwable throwable) | Must have the same parameters as the original method, plus a Throwable parameter at the end. |
Feign Client (No Change from Previous Patterns)
1@FeignClient(name = "product-service") // Uses Eureka for service discovery2public interface ProductClient {3 @GetMapping("/products/{id}")4 String getProductById(@PathVariable String id);5}Since Eureka is used for service discovery, no URL is hardcoded. This is the same setup used in earlier lessons on Retry and Bulkhead.
Configuration `application.properties`
1# ─── Circuit Breaker Configuration ───────────────────────────────────────────2
3# Name matches the name in @CircuitBreaker annotation4resilience4j.circuitbreaker.instances.productService.sliding-window-type=COUNT_BASED5resilience4j.circuitbreaker.instances.productService.sliding-window-size=106resilience4j.circuitbreaker.instances.productService.minimum-number-of-calls=57resilience4j.circuitbreaker.instances.productService.failure-rate-threshold=508resilience4j.circuitbreaker.instances.productService.wait-duration-in-open-state=10s9resilience4j.circuitbreaker.instances.productService.permitted-number-of-calls-in-half-open-state=310
11# Optional: Control which exceptions are tracked12# resilience4j.circuitbreaker.instances.productService.record-exceptions=java.io.IOException13# resilience4j.circuitbreaker.instances.productService.ignore-exceptions=java.lang.IllegalArgumentExceptionConfiguration Parameters Deep Dive
1. `sliding-window-type`
| Value | Meaning |
|---|---|
COUNT_BASED | Track the last N calls (N = sliding-window-size). Evaluate failure rate over these N calls. |
TIME_BASED | Track all calls in the last N seconds (N = sliding-window-size). Evaluate failure rate over this time window. |
Example:
COUNT_BASEDwith size10→ The last 10 calls are evaluated.TIME_BASEDwith size10→ All calls in the last 10 seconds are evaluated.
2. `sliding-window-size`
- For
COUNT_BASED: The number of recent calls to track (e.g.,10= last 10 calls). - For
TIME_BASED: The time period in seconds (e.g.,10= last 10 seconds).
3. `minimum-number-of-calls`
Purpose: Prevents false positives when the sample size is too small.
Why it matters: Imagine your threshold is 50% failures. If only 2 calls have been made and 1 fails, that's 50% failure — but it would be a false alarm to open the circuit from just one failure.
With minimum-number-of-calls=5, the circuit breaker will not evaluate the failure rate until at least 5 calls have been made. This ensures the failure rate calculation is statistically meaningful.
1Window size: 102Minimum calls: 53Threshold: 50%4
5Call 1: FAIL → failure count = 1, minimum not reached, stay CLOSED6Call 2: FAIL → failure count = 2, minimum not reached, stay CLOSED7Call 3: FAIL → failure count = 3, minimum not reached, stay CLOSED8Call 4: FAIL → failure count = 4, minimum not reached, stay CLOSED9Call 5: FAIL → failure count = 5, minimum REACHED, evaluate now!10 → 5 failures out of 5 calls (within window of 10) = 100% failure11 → 100% > 50% threshold → OPEN circuit!4. `failure-rate-threshold`
- A percentage (0–100).
- If the failure rate within the sliding window exceeds this percentage, the circuit opens.
- Example:
50means if 50% or more of the calls in the window fail → open the circuit.
With sliding-window-size=10 and failure-rate-threshold=50:
- Threshold = 50% of 10 = 5 failures out of 10 calls
- Once 5 calls fail in any window of 10, the circuit opens.
5. `wait-duration-in-open-state`
- How long the circuit stays in OPEN state before transitioning to HALF-OPEN.
- Format:
10s,5s,30s, etc. - During this period, all calls are immediately rejected.
- Internally, a
ScheduledThreadPoolExecutoris used to schedule the state transition (see Internal Working section below).
6. `permitted-number-of-calls-in-half-open-state`
- The maximum number of test/trial calls allowed when the circuit is in HALF-OPEN state.
- Example:
3→ Only 3 calls will be sent to the downstream service as a test. - After these 3 calls, the circuit evaluates:
- 100% success → transition to CLOSED
- Any failure → transition back to OPEN
7. Exception Tracking (Optional Configuration)
By default, Resilience4j tracks all RuntimeExceptions and Errors as failures.
You can override this behavior:
1# Track ONLY these exceptions as failures2resilience4j.circuitbreaker.instances.productService.record-exceptions=\3 java.io.IOException,\4 java.net.ConnectException5
6# Ignore these exceptions (do not count them as failures)7resilience4j.circuitbreaker.instances.productService.ignore-exceptions=\8 java.lang.IllegalArgumentException| Configuration | Behavior |
|---|---|
record-exceptions | Only the listed exception types are counted as failures |
ignore-exceptions | The listed exception types are not counted as failures |
| Neither specified | All RuntimeExceptions and Errors are counted as failures |
Configuration Summary Table
| Property | Example Value | Description |
|---|---|---|
sliding-window-type | COUNT_BASED | How the window is measured (by calls or by time) |
sliding-window-size | 10 | Size of the window (10 calls or 10 seconds) |
minimum-number-of-calls | 5 | Minimum calls before failure rate is evaluated |
failure-rate-threshold | 50 | Failure % that triggers OPEN state |
wait-duration-in-open-state | 10s | How long circuit stays OPEN before HALF-OPEN |
permitted-number-of-calls-in-half-open-state | 3 | Trial calls in HALF-OPEN state |
record-exceptions | IOException | Only count these as failures (optional) |
ignore-exceptions | IllegalArgumentException | Ignore these exceptions (optional) |
Step-by-Step Execution Walkthrough
Based on the configuration:
sliding-window-type=COUNT_BASEDsliding-window-size=10minimum-number-of-calls=5failure-rate-threshold=50wait-duration-in-open-state=10spermitted-number-of-calls-in-half-open-state=3
Product Service is not started (unavailable).
1Call 1 → Circuit: CLOSED → Tries to reach Product Service → FAIL2 Fallback invoked. Failure count: 1. Minimum (5) not reached.3
4Call 2 → Circuit: CLOSED → Tries to reach Product Service → FAIL5 Fallback invoked. Failure count: 2. Minimum not reached.6
7Call 3 → Circuit: CLOSED → Tries to reach Product Service → FAIL8 Fallback invoked. Failure count: 3. Minimum not reached.9
10Call 4 → Circuit: CLOSED → Tries to reach Product Service → FAIL11 Fallback invoked. Failure count: 4. Minimum not reached.12
13Call 5 → Circuit: CLOSED → Tries to reach Product Service → FAIL14 Fallback invoked. Failure count: 5.15 ✅ Minimum reached! Evaluate now:16 5 failures / 5 calls in window = 100% > 50% threshold17 ⚡ Circuit transitions: CLOSED → OPEN18 ScheduledThreadPoolExecutor schedules transition to HALF-OPEN after 10s.19
20[Calls 6, 7, 8...] → Circuit: OPEN → Immediately rejected (no downstream call)21 Fallback invoked instantly. No thread blocking. No latency.22
23[After 10 seconds] ⏰24 ScheduledThreadPoolExecutor triggers: OPEN → HALF-OPEN25
26Trial Call 1 → Circuit: HALF-OPEN → Tries to reach Product Service → FAIL27Trial Call 2 → Circuit: HALF-OPEN → Tries to reach Product Service → FAIL28Trial Call 3 → Circuit: HALF-OPEN → Tries to reach Product Service → FAIL29 All 3 trial calls failed. Success rate = 0%.30 ⚡ Circuit transitions: HALF-OPEN → OPEN again.31 ScheduledThreadPoolExecutor schedules next HALF-OPEN after 10s.Internal Working How State Transitions Work
How Does CLOSED OPEN Happen?
Resilience4j uses AOP (Aspect-Oriented Programming). When you annotate a method with @CircuitBreaker, Resilience4j wraps it with an aspect (a proxy).
Every time an exception occurs, the AOP interceptor invokes the CircuitBreakerStateMachine class (internal Resilience4j class).
The logic is approximately:
1// Pseudocode of CircuitBreakerStateMachine2public void onError(long duration, TimeUnit durationUnit, Throwable throwable) {3 if (currentState == CLOSED) {4 boolean thresholdExceeded = checkIfThresholdExceeded();5 if (thresholdExceeded) {6 transitionToOpenState(); // CLOSED → OPEN7 }8 } else if (currentState == HALF_OPEN) {9 boolean successRateAchieved = checkSuccessRate();10 if (!successRateAchieved) {11 transitionToOpenState(); // HALF_OPEN → OPEN12 }13 }14}Every failure triggers a threshold check. If the threshold is crossed, the state changes.
How Does OPEN HALF-OPEN Happen Automatically?
This is the most interesting internal mechanism.
When the circuit transitions to OPEN, Resilience4j internally does this:
1// Inside CircuitBreakerStateMachine - openState() method (pseudocode)2private void transitionToOpenState() {3 this.currentState = OPEN;4 5 // Schedule automatic transition to HALF-OPEN after waitDuration6 scheduledExecutor.schedule(7 () -> transitionToHalfOpenState(), // Task: change to HALF-OPEN8 waitDurationInOpenState, // Delay: e.g., 10 seconds9 TimeUnit.MILLISECONDS10 );11}It uses a ScheduledThreadPoolExecutor to schedule the state transition. This is how a task can be executed after a specific delay without manually sleeping a thread.
Internal Working ScheduledThreadPoolExecutor
What Is ScheduledThreadPoolExecutor?
ScheduledThreadPoolExecutor is a Java class that allows you to schedule tasks to run:
- After a specific delay (one-time)
- At a fixed rate or interval (recurring)
1ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);2
3// Run task after 10 seconds4executor.schedule(5 () -> System.out.println("Transitioning to HALF-OPEN"),6 10,7 TimeUnit.SECONDS8);Internal Data Structure DelayQueue
ScheduledThreadPoolExecutor internally uses a DelayQueue to manage scheduled tasks.
How DelayQueue Works:
- Tasks are ordered by expiry time — the task that expires soonest is always at the head.
- A worker thread peeks at the head to see if the task is ready.
- If the task's delay has not expired, the thread goes into a WAIT/BLOCKED state for the remaining delay duration.
- The OS wakes the thread after that duration using native timers.
- The thread picks up the now-ready task and executes it.
- Other worker threads handle remaining tasks in the queue similarly.
The underlying data structure is a PriorityQueue, sorted by delay (ascending — smallest delay at the head).
Thread Locking in DelayQueue
When multiple worker threads are available:
- All threads attempt to peek at the head of the
DelayQueue. - If the task is not yet ready, all threads go into wait state for the same remaining duration.
- When the OS wakes the threads, only one thread acquires the lock and picks up the task.
- The remaining threads look at the next item in the queue and repeat the process.
Interview Questions
Q1: What is the Circuit Breaker pattern?
Answer: A resilience pattern that monitors failures to a downstream service. When failures exceed a threshold within a sliding window, the circuit "opens" and all further calls are immediately failed (fail-fast) without reaching the downstream service. After a wait period, a limited number of trial calls are made (half-open state). If they succeed, the circuit closes; otherwise, it opens again.
Q2: What are the three states of a Circuit Breaker?
Answer:
- Closed: Normal operation. All calls reach the downstream service.
- Open: All calls are immediately rejected. No downstream calls.
- Half-Open: A limited number of test calls are made to check recovery.
Q3: How does Resilience4j transition from OPEN to HALF-OPEN automatically?
Answer: It uses a ScheduledThreadPoolExecutor to schedule a state-transition task with a delay equal to wait-duration-in-open-state. When this delay expires, the executor runs the task which transitions the circuit to HALF-OPEN.
Q4: How does ScheduledThreadPoolExecutor work internally?
Answer: It uses a DelayQueue (backed by a PriorityQueue) to store tasks sorted by their expiry time. Worker threads peek at the head — if the delay hasn't expired, the thread blocks for the remaining duration. The OS wakes the thread when the delay expires, and the thread executes the task.
Q5: How would you implement a "disappearing message" feature (like WhatsApp's 24-hour view-once message)?
Answer: Using a DelayQueue. Each message is wrapped in a Delayed object with an expiry of 24 hours. A consumer thread monitors the queue; when a message's delay expires (i.e., it reaches the head of the queue), the consumer picks it up and deletes it. This is the same mechanism used internally by ScheduledThreadPoolExecutor.
Q6: What is the difference between COUNT_BASED and TIME_BASED sliding windows?
| Feature | COUNT_BASED | TIME_BASED |
|---|---|---|
| Window defined by | Number of calls (e.g., last 10) | Time period (e.g., last 10 seconds) |
| Call count | Fixed: always last N calls | Variable: could be 5 or 500 in 10s |
| Use case | Consistent traffic patterns | Bursty or variable traffic |
Q7: What happens if the minimum-number-of-calls is too low?
Answer: You risk false positives. For example, if minimum-number-of-calls=2 and failure-rate-threshold=50%, a single failure out of 2 calls (50%) would open the circuit — even though just 1 failed request could be a transient network glitch that would pass on retry.
Q8: What is the role of AOP in Resilience4j's Circuit Breaker?
Answer: Resilience4j uses Spring AOP to intercept method calls annotated with @CircuitBreaker. The AOP proxy wraps the method and delegates execution through the CircuitBreakerStateMachine, which tracks successes and failures and manages state transitions. You do not need to write any state-management code yourself.
Common Mistakes
Mistake 1: Confusing Open/Closed State
1"Circuit is CLOSED" → Beginners think: no calls allowed ❌2"Circuit is CLOSED" → Correct: all calls ALLOWED ✅3
4"Circuit is OPEN" → Beginners think: calls are open/allowed ❌5"Circuit is OPEN" → Correct: circuit is tripped, calls BLOCKED ✅Mistake 2: Fallback Method Signature Mismatch
1// ❌ Wrong — missing Throwable parameter2public String productServiceFallback(String productId) { ... }3
4// ✅ Correct — Throwable must be the last parameter5public String productServiceFallback(String productId, Throwable throwable) { ... }Mistake 3: Name Mismatch Between Annotation and Config
1// Annotation uses "productService"2@CircuitBreaker(name = "productService", ...)3
4# ❌ Config uses different name5resilience4j.circuitbreaker.instances.product.sliding-window-size=106
7# ✅ Config must match exactly8resilience4j.circuitbreaker.instances.productService.sliding-window-size=10Mistake 4: Setting minimum-number-of-calls Higher Than sliding-window-size
1# ❌ This means the threshold is never evaluated (minimum > window)2resilience4j.circuitbreaker.instances.productService.sliding-window-size=53resilience4j.circuitbreaker.instances.productService.minimum-number-of-calls=104
5# ✅ Minimum should be ≤ window size6resilience4j.circuitbreaker.instances.productService.sliding-window-size=107resilience4j.circuitbreaker.instances.productService.minimum-number-of-calls=5Best Practices
- Set
minimum-number-of-callsto avoid false positives. A low minimum on low-traffic services will cause unnecessary circuit opens.
- Choose
COUNT_BASEDfor steady traffic,TIME_BASEDfor bursty traffic.
- Configure
wait-duration-in-open-statebased on the expected recovery time of your downstream service. Too short = the circuit will keep flipping to HALF-OPEN and back to OPEN. Too long = users experience prolonged degradation.
- Always provide a meaningful fallback method. Return cached data, a default response, or a user-friendly error — never let the fallback throw its own exception.
- Use
record-exceptionsandignore-exceptionsto control what counts as a circuit breaker failure. Not every exception indicates the service is down (e.g., a404 Not Foundmight be expected business logic).
- Monitor circuit breaker state using Resilience4j's metrics integration with Micrometer and expose them via Spring Boot Actuator. This allows dashboards (Grafana) to show circuit states in production.
- Test your fallback logic. The circuit breaker is only as good as its fallback. Ensure your fallback does not cause more harm.
Related Concepts
| Concept | Relationship |
|---|---|
| Retry Pattern | Complements Circuit Breaker. Retry handles transient failures; Circuit Breaker handles sustained failures. Use together carefully to avoid retry storms. |
| Bulkhead Pattern | Limits concurrent calls to prevent resource exhaustion. Works alongside Circuit Breaker. |
| Rate Limiter | Limits the rate of calls. Prevents overloading a service. |
| Fallback Pattern | Used with Circuit Breaker to provide degraded responses. |
| AOP (Aspect-Oriented Programming) | Resilience4j uses AOP to intercept annotated methods. |
| Feign Client | HTTP client used to call downstream services in Spring Boot. Circuit Breaker wraps Feign calls. |
| Eureka Service Discovery | Used for dynamic service resolution without hardcoding URLs. |
| ScheduledThreadPoolExecutor | Java class used internally to schedule the OPEN → HALF-OPEN transition. |
| DelayQueue / PriorityQueue | Internal data structures used by ScheduledThreadPoolExecutor. |
Mind Map
Practice Questions
Easy
- What are the three states of a Circuit Breaker? Briefly describe each.
- What does
failure-rate-threshold=50mean in the configuration? - What is the purpose of
minimum-number-of-calls? - When is the fallback method invoked?
Medium
- Given:
sliding-window-size=10,minimum-number-of-calls=5,failure-rate-threshold=50. How many failures are needed to open the circuit? At what point does evaluation begin? - Explain the difference between
COUNT_BASEDandTIME_BASEDsliding windows. When would you use each? - What happens to calls made while the circuit is in OPEN state?
- What happens if all 3 trial calls (in HALF-OPEN state) succeed? What if 1 fails?
Hard
- Explain the internal mechanism by which the Circuit Breaker automatically transitions from OPEN to HALF-OPEN after the wait duration. Name the Java class and data structure involved.
- How does
ScheduledThreadPoolExecutoruseDelayQueueinternally? Describe what happens when a worker thread finds a task whose delay has not yet expired. - A team is using Circuit Breaker + Retry together. Explain the potential problem of "retry storms" and how to mitigate it.
- Design a "disappearing message" feature (like WhatsApp's view-once). What Java data structure would you use? How does it relate to
ScheduledThreadPoolExecutor?
Summary
- Circuit Breaker prevents an application from making calls to a likely-failing downstream service.
- Three states: CLOSED (normal), OPEN (fail-fast, no calls), HALF-OPEN (trial calls).
- Closed = calls flow. Open = calls blocked. (Think: electrical circuit analogy.)
- CLOSED → OPEN: When failure rate in the sliding window exceeds the threshold.
- OPEN → HALF-OPEN: Automatically after
wait-duration-in-open-state, usingScheduledThreadPoolExecutor. - HALF-OPEN → CLOSED: If all permitted trial calls succeed (100% success rate).
- HALF-OPEN → OPEN: If any trial call fails.
- Implemented in Spring Boot via
@CircuitBreakerannotation from Resilience4j (no extra dependency needed). - Fallback method is invoked for every failure, regardless of circuit state.
minimum-number-of-callsprevents false positives on small samples.- Internally,
ScheduledThreadPoolExecutoruses aDelayQueue(backed byPriorityQueue) to schedule state transitions. - Worker threads block until the task's delay expires; the OS wakes them at the right time.
- This same pattern is used to implement features like "disappearing messages" in chat applications.
Mastery check
How well can you recall this?
Finished this lesson?