A circuit breaker helps your system avoid repeated failures by stopping calls to a failing service temporarily. Resilience4j is a tool that makes adding this protection easy in Spring Boot apps.
Circuit breaker with Resilience4j in Spring Boot
1. Add Resilience4j dependency to your Spring Boot project. 2. Configure circuit breaker properties in application.yml or application.properties. 3. Annotate your service method with @CircuitBreaker(name = "serviceName", fallbackMethod = "fallbackMethodName"). 4. Implement the fallback method to handle failures gracefully.
The name in @CircuitBreaker links to configuration settings.
The fallbackMethod is called when the circuit is open or an error occurs.
callPaymentService method with a circuit breaker named 'paymentService'.@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback") public String callPaymentService() { // call external payment API }
public String paymentFallback(Exception e) {
return "Payment service is down, please try later.";
}resilience4j.circuitbreaker.instances.paymentService.registerHealthIndicator=true resilience4j.circuitbreaker.instances.paymentService.slidingWindowSize=10 resilience4j.circuitbreaker.instances.paymentService.failureRateThreshold=50
This Spring Boot app has a REST endpoint /pay that simulates a payment service. It fails twice and succeeds on the third call. The circuit breaker stops calls when failures are high and uses the fallback method to respond gracefully.
package com.example.demo; import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @RestController class PaymentController { private int attempt = 0; @GetMapping("/pay") @CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback") public String pay() { attempt++; if (attempt % 3 != 0) { throw new RuntimeException("Payment service failure"); } return "Payment successful on attempt " + attempt; } public String paymentFallback(Exception e) { return "Payment service is currently unavailable. Please try again later."; } }
Configure circuit breaker properties carefully to balance between sensitivity and availability.
Fallback methods should be quick and safe to avoid further failures.
Use monitoring tools to track circuit breaker states and metrics.
Circuit breakers protect your app from repeated failures by stopping calls temporarily.
Resilience4j integrates easily with Spring Boot using annotations and configuration.
Fallback methods provide graceful responses when services fail.
Practice
Solution
Step 1: Understand circuit breaker role
A circuit breaker stops calls to a failing service temporarily to avoid cascading failures.Step 2: Identify the main benefit
This helps the system recover and prevents wasting resources on repeated failing calls.Final Answer:
To prevent repeated calls to a failing service and allow recovery -> Option DQuick Check:
Circuit breaker purpose = prevent repeated failures [OK]
- Confusing circuit breaker with scaling
- Thinking it speeds up database queries
- Assuming it encrypts data
Solution
Step 1: Recall Resilience4j integration
Resilience4j provides the @CircuitBreaker annotation to mark methods for circuit breaking.Step 2: Differentiate from other annotations
@Retryable is for retries, @Cacheable for caching, and @Transactional for DB transactions.Final Answer:
@CircuitBreaker -> Option BQuick Check:
Resilience4j circuit breaker annotation = @CircuitBreaker [OK]
- Confusing with @Retryable for retries
- Using caching or transaction annotations incorrectly
- Misspelling annotation names
@CircuitBreaker(name = "serviceA", fallbackMethod = "fallback")
public String callService() {
// calls external service
throw new RuntimeException("Service down");
}
public String fallback(Throwable t) {
return "Fallback response";
}
What will be the output when callService() is invoked?Solution
Step 1: Analyze method behavior with circuit breaker
The method throws an exception, but the circuit breaker calls the fallback method.Step 2: Understand fallback method output
The fallback method returns the string "Fallback response" which is returned to the caller.Final Answer:
"Fallback response" -> Option AQuick Check:
Fallback method output = "Fallback response" [OK]
- Expecting exception to propagate without fallback
- Assuming null is returned on failure
- Thinking method returns normally without fallback
@CircuitBreaker(name = "serviceB", fallback = "fallbackMethod")
public String fetchData() {
// call external API
}
What is the main issue with this code?Solution
Step 1: Check annotation attribute names
The correct attribute for fallback method name is fallbackMethod, not fallback.Step 2: Validate other conditions
Method return type and visibility are valid; circuit breaker name can be any string.Final Answer:
The fallback method name should be specified with fallbackMethod, not fallback -> Option CQuick Check:
Correct fallback attribute = fallbackMethod [OK]
- Using 'fallback' instead of 'fallbackMethod'
- Thinking method must be void
- Assuming circuit breaker name is restricted
Solution
Step 1: Understand system stability needs
Using a circuit breaker prevents repeated calls to the unstable API, avoiding overload.Step 2: Importance of fallback for graceful degradation
A fallback method returning cached or default data keeps the system responsive during failures.Step 3: Evaluate other options
Retries alone can worsen overload; no fallback causes failures; increasing threads doesn't solve API instability.Final Answer:
Apply @CircuitBreaker with a fallback method returning a cached payment status -> Option AQuick Check:
Circuit breaker + fallback = stability + graceful degradation [OK]
- Relying only on retries without circuit breaker
- Not providing fallback causing failures
- Increasing threads without handling failures
Ready to prove it?
Pass the test and this pattern moves unknown
