Minimal Guide to Resilience4j and Circuit Breaker in Spring Boot
Source: Dev.to

What is a Circuit Breaker?
The Circuit Breaker pattern works similarly to electrical breakers in a house. If it detects a failure, it opens the circuit to prevent further damage and closes it once the problem is resolved.
A Circuit Breaker has three main states:
- Closed: Everything is working correctly. Requests flow normally.
- Open: Failures have exceeded the allowed threshold. Requests are blocked and a fallback is executed.
- Half‑Open: A trial period where a limited number of requests are allowed to check if the service has recovered.
Resilience4j Configuration
To start, create a Spring Boot project and add the following dependency:
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
</dependency>
In application.yml, define the parameters that will govern the behavior of the Circuit Breaker:
resilience4j:
circuitbreaker:
instances:
mainService:
registerHealthIndicator: true
slidingWindowSize: 10
permittedNumberOfCallsInHalfOpenState: 3
slidingWindowType: COUNT_BASED
minimumNumberOfCalls: 5
waitDurationInOpenState: 10s
failureRateThreshold: 50
eventConsumerBufferSize: 10
Parameter Breakdown
- slidingWindowSize: Number of calls to record when the circuit is closed.
- failureRateThreshold: Percentage of failures (e.g., 50%) at which the circuit should open.
- waitDurationInOpenState: How long the circuit stays Open before trying to recover.
- permittedNumberOfCallsInHalfOpenState: Number of successful calls needed in Half‑Open to close the circuit again.
Implementation with Annotations
The easiest way to use Resilience4j is by applying the @CircuitBreaker annotation. Specify the name of the instance configured in the YAML and a fallback method.
Note: The fallback method must have the same signature as the original method and receive a
Throwable(orException) as an argument.
@Service
public class ProductService {
@CircuitBreaker(name = "mainService", fallbackMethod = "fallbackGetProducts")
public List<Product> getProducts() {
// Logic that might fail (e.g., calling an external API)
return externalApi.fetchProducts();
}
// Fallback Method
public List<Product> fallbackGetProducts(Throwable e) {
return List.of(new Product("Default Product", 0.0));
}
}
Other Resilience4j Modules
While the Circuit Breaker is the most well‑known, Resilience4j provides additional tools to improve stability:
- TimeLimiter – Sets a maximum execution time for a request; exceeding it triggers a failure.
- Retry – Automatically retries a failed operation a configurable number of times before giving up.
- Bulkhead – Limits the number of concurrent calls to a service to avoid saturating resources (e.g., thread pools).
Conclusions
Resilience4j is a powerful tool for building robust microservices. By implementing the Circuit Breaker pattern, you ensure that your application can fail gracefully instead of crashing completely under pressure.