Building Resilient Systems with Java
A Guide to Resilience4j and Circuit Breakers
A practical guide to Circuit Breaker, Retry, Bulkhead, Timeout, and Graceful Degradation in Java applications.
1. Introduction
Failures are inevitable in distributed systems.
A remote API may become unavailable. Database responses may slow down. Network connections can fail, and sudden traffic spikes can exhaust application resources.
In distributed architectures, a failure in one service can spread to other services and trigger cascading failures if appropriate safeguards are not in place.
This is why resilience — the ability of a system to handle failures, limit their impact, and recover gracefully — is an essential aspect of modern Java application development.
In the Java ecosystem, Resilience4j is a modular library that provides mechanisms such as Circuit Breaker, Retry, Rate Limiter, Bulkhead, and Time Limiter.
In this guide, we will explore these mechanisms through practical examples, configuration snippets, and production-oriented recommendations.
We will cover:
- Resilience concepts and fundamental design principles
- Setting up Resilience4j with Maven
- Circuit Breaker and Retry patterns
- Bulkhead, Rate Limiter, and Timeout
- Fallback and Graceful Degradation
- Monitoring and testing strategies
2. What Is Resilience?
Resilience is a system’s ability to preserve critical functionality under failure conditions and recover when dependencies become available again.
Consider an e-commerce application consisting of the following services:
OrderService: Manages orders.PaymentService: Processes payments.InventoryService: Checks product availability.RecommendationService: Provides product recommendations.NotificationService: Sends notifications.
If the recommendation service becomes unavailable, the entire product page does not necessarily need to fail. The application can continue displaying product information without recommendations.
Critical operations, such as payment processing and inventory validation, require different safeguards and business rules.
Resilience patterns address different problems:
Mechanism Purpose
Timeout Prevent operations from waiting indefinitely
Retry Retry operations after transient failures
Circuit Breaker Prevent repeated calls to an unhealthy dependency
Bulkhead Isolate and limit resource consumption
Rate Limiter Control request frequency
Fallback Provide an alternative response or behavior
Observability Measure failures and recovery behavior
These mechanisms complement one another, but they are not interchangeable.
For example, a circuit breaker does not automatically impose a timeout on an HTTP request. Likewise, retrying an operation does not guarantee that repeating it is safe.
3. Setting Up Resilience4j with Maven
Resilience4j can be integrated into Spring Boot applications through a dedicated Spring integration starter.
The following Maven configuration illustrates a setup targeting Spring Boot 3 and Java 17 or later.
Maven dependencies
<properties>
<java.version>17</java.version>
<resilience4j.version>YOUR_COMPATIBLE_VERSION</resilience4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
<version>${resilience4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>Replace YOUR_COMPATIBLE_VERSION with a verified Resilience4j release compatible with your Java and Spring Boot versions.
Resilience4j 2.x requires Java 17 or later. Applications using Spring Boot 2 should use the appropriate Boot 2 integration rather than the Boot 3 starter.
Reference: Resilience4j — Getting Started
4. Circuit Breaker: Preventing Cascading Failures
A Circuit Breaker prevents an application from repeatedly calling a dependency that is experiencing failures.
It operates in three primary states.
Closed
Calls are allowed, and their success or failure is recorded.
Open
When the configured failure conditions are met, the circuit opens. New calls are rejected without executing the protected operation.
Half-open
After a configured waiting period, a limited number of test calls are permitted.
If the dependency has recovered, the circuit closes. If failures continue, the circuit opens again.
Configuring a Circuit Breaker
Add the following configuration to application.yml:
resilience4j:
circuitbreaker:
instances:
inventoryService:
slidingWindowType: COUNT_BASED
slidingWindowSize: 10
minimumNumberOfCalls: 5
failureRateThreshold: 50
waitDurationInOpenState: 5s
permittedNumberOfCallsInHalfOpenState: 2his configuration means:
- The sliding window contains up to 10 calls.
- At least 5 calls are required before the failure rate is evaluated.
- The circuit can open when the failure rate reaches 50%.
- The circuit remains open for 5 seconds before transitioning toward recovery.
- Up to 2 calls are permitted in the half-open state.
These values are illustrative. Production thresholds should be based on traffic patterns, latency, and service-level objectives.
Using @CircuitBreaker
io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
org.springframework.stereotype.Service;
@Service
public class InventoryService {
@CircuitBreaker(
name = "inventoryService",
fallbackMethod = "inventoryFallback"
)
public String checkInventory(String productId) {
return callInventoryApi(productId);
}
private String inventoryFallback(
String productId,
Throwable throwable) {
return "Inventory service temporarily unavailable";
}
private String callInventoryApi(String productId) {
// Implement the actual remote API call.
return "Inventory available";
}
}The @CircuitBreaker annotation protects the method using the named circuit breaker configuration.
The fallback method must have compatible parameters: the original method arguments followed by a compatible exception parameter. Its return type must also match the protected method’s return type.
In production, fallback responses must respect business rules. Assuming that a product is in stock when inventory cannot be verified could lead to incorrect orders.
For this reason, the example returns an explicit message indicating that the inventory status is unavailable.
For further reading, see Baeldung — A Quick Guide to Spring Cloud Circuit Breaker.
5. Retry: Handling Transient Failures
Not all failures are permanent.
A network connection may reset, a remote service may temporarily return an overload response, or a short-lived infrastructure issue may cause a request to fail.
The Retry pattern allows an operation to be attempted again under controlled conditions.
Configuring Retry
resilience4j:
retry:
instances:
paymentService:
maxAttempts: 3
waitDuration: 500msHere, maxAttempts: 3 means three attempts in total, including the initial call.
The example uses a fixed waiting interval between attempts. In high-traffic systems, exponential backoff and randomized jitter may be more appropriate.
Using @Retry
io.github.resilience4j.retry.annotation.Retry;
org.springframework.stereotype.Service;
@Service
public class PaymentService {
@Retry(
name = "paymentService",
fallbackMethod = "paymentFallback"
)
public String processPayment(String orderId) {
return callPaymentGateway(orderId);
}
private String paymentFallback(
String orderId,
Throwable throwable) {
return "Payment outcome could not be confirmed";
}
private String callPaymentGateway(String orderId) {
// Implement the actual payment gateway call.
return "Payment processed";
}
}This example demonstrates a fallback when the operation continues to fail after retry processing.
However, retrying payment operations requires special care.
The server may successfully process a payment while the response never reaches the client. If the client sends the request again, a duplicate charge may occur.
To prevent this, use an idempotency key or an equivalent deduplication mechanism. Also distinguish between a confirmed failure and an operation whose outcome is unknown.
Not every failure should be retried. Invalid requests and permanent business-rule violations are generally unsuitable for retry.
Reference: Baeldung — Exponential Backoff and Jitter.
6. Bulkhead: Isolating Resources
The Bulkhead pattern prevents a slow or overloaded service from exhausting resources needed by other parts of an application.
Imagine an application that calls both a payment service and a recommendation service.
If recommendation requests consume all available execution resources, payment requests may also become delayed or rejected.
Bulkhead limits help isolate these workloads.
Resilience4j provides two primary approaches:
SemaphoreBulkhead: Limits concurrent calls using a semaphore.FixedThreadPoolBulkhead: Uses a dedicated thread pool and a bounded queue.
Configuration Example
resilience4j:
bulkhead:
instances:
recommendationService:
maxConcurrentCalls: 10
maxWaitDuration: 100msThis configuration limits concurrent calls for the named bulkhead. The actual resource behavior depends on the selected bulkhead implementation.
Get mkonca’s stories in your inbox
Join Medium for free to get updates from this writer.
A semaphore-based approach may be sufficient when only a concurrency limit is needed. A thread-pool bulkhead can be considered when a separate execution pool is appropriate.
A bulkhead does not make a service faster. Its purpose is to limit the damage a slow dependency can cause to the rest of the application.
Reference: Resilience4j — Bulkhead.
7. Rate Limiter: Controlling Request Frequency
A Rate Limiter restricts the number of calls permitted within a specified period.
It can help applications comply with external API quotas and prevent excessive traffic from overwhelming a service.
Configuration Example
resilience4j:
ratelimiter:
instances:
catalogService:
limitForPeriod: 20
limitRefreshPeriod: 1s
timeoutDuration: 0This example permits up to 20 calls per one-second refresh period for the configured limiter.
With timeoutDuration: 0, a call that cannot immediately obtain permission is rejected rather than waiting.
Rate limiting and bulkheads solve different problems:
- Rate limiting controls the frequency of calls.
- Bulkheads control concurrent execution or isolate resource consumption.
Depending on the workload, both mechanisms can be used together.
Reference: Resilience4j — RateLimiter.
8. Timeout: Limiting Waiting Time
A timeout limits how long an application waits for an operation to complete.
Without appropriate timeouts, an unresponsive dependency can occupy threads or connections for longer than necessary.
Resilience4j provides a TimeLimiter module, particularly for supported asynchronous operations involving Future and CompletionStage.
Configuration Example
resilience4j:
timelimiter:
instances:
remoteOperation:
timeoutDuration: 2s
cancelRunningFuture: trueThe cancellation setting applies to supported future-based execution models. Cancelling a future does not guarantee that the underlying network operation or remote server has stopped processing the request.
For HTTP clients, connection and request timeouts should also be configured separately.
A robust design considers the following together:
- An appropriate timeout for the network call.
- An overall deadline for the operation.
- A retry policy bounded by the remaining time budget.
- Explicit error handling when the deadline is exceeded.
Timeouts, retries, and circuit breakers should not be configured independently of one another.
9. Graceful Degradation and Fallback
Graceful degradation allows an application to preserve critical functionality when a dependency becomes unavailable.
For example, product information can remain visible even when the recommendation service fails.
public ProductPage loadProductPage(String productId) {
Product product = productService.getProduct(productId);
List<Product> recommendations;
try {
recommendations =
recommendationService.getRecommendations(productId);
} catch (RecommendationServiceException exception) {
recommendations = List.of();
}
return new ProductPage(product, recommendations);
}In this example, an empty recommendation list is returned when the recommendation service fails. The product information remains available to the user.
A fallback may also use cached data or another response that respects the application’s business rules.
However, fallback behavior must be appropriate for the operation. A payment failure must not be handled in the same way as an optional recommendation failure.
Avoid catching all exceptions indiscriminately. Expected dependency failures should be handled deliberately, while unexpected programming errors should remain visible.
10. Monitoring and Observability
Resilience mechanisms must be monitored to provide value in production.
A circuit breaker may open too frequently. A retry policy may generate unnecessary traffic. A bulkhead may reject requests because its capacity is too low.
Useful metrics include:
- Request success and failure rates.
- p95 and p99 latency.
- Timeout counts.
- Retry attempts.
- Circuit breaker state transitions.
- Bulkhead rejections.
- Rate limiter rejections.
- Fallback execution counts.
Resilience4j supports metrics integration through Micrometer. Spring Boot Actuator can help expose these metrics to monitoring infrastructure when configured appropriately.
Reference: Baeldung — Resilience4j Events Endpoints.
A good observability strategy should answer three questions:
- Which dependency is failing?
- Which resilience mechanism is being activated?
- Is the system recovering while maintaining its service-level objectives?
11. Combining Resilience Mechanisms
Each mechanism targets a different failure mode. Combining them can provide stronger protection, but their configuration must be deliberate.
A practical strategy for a remote service call may include:
- Define an overall time budget for the operation.
- Configure the HTTP client’s timeout values.
- Apply bounded retries only to appropriate transient failures.
- Use a circuit breaker to avoid repeatedly calling an unhealthy dependency.
- Consider a bulkhead to limit concurrent resource consumption.
- Apply rate limiting when necessary.
- Define fallback behavior that respects business rules.
- Monitor failures and recovery through metrics.
The interaction between Retry and Circuit Breaker is particularly important.
For example, should the circuit breaker count every retry attempt individually, or should it evaluate the outcome of the complete retry process? The answer depends on the application’s failure-handling policy.
Resilience4j’s annotation-based integration has a defined aspect order that can be configured. When more precise control is required, its programmatic decorator APIs can be considered.
Reference: Resilience4j — Getting Started.
12. Testing Resilience
A system that works under normal conditions has not necessarily demonstrated resilience.
The following scenarios should be tested:
- A remote service responds slowly.
- A dependency becomes completely unavailable.
- Requests fail repeatedly.
- The circuit breaker opens.
- The dependency recovers.
- The bulkhead reaches its capacity.
- The rate limit is exceeded.
- The fallback returns the expected response.
Tests should verify recovery behavior as well as failure handling.
For example, an automated test can confirm that a product page remains accessible when the recommendation service is unavailable.
Performance tests should also evaluate latency, resource consumption, and retry behavior under heavy load.
Conclusion
Resilience is a fundamental part of building reliable Java applications.
Timeouts prevent indefinite waiting. Retries help recover from transient failures. Circuit breakers reduce calls to unhealthy dependencies. Bulkheads isolate resource consumption. Rate limiters control request frequency, while graceful degradation preserves critical functionality.
Resilience4j provides modular implementations of these patterns and integrates with the Spring ecosystem.
However, adding a few annotations does not automatically make an application resilient.
A resilient system is designed to handle failures in a controlled manner, protect critical functionality, and recover predictably.
The most important engineering decision is not simply which library to use, but how the application should behave when its dependencies fail.
References
- Baeldung — A Quick Guide to Spring Cloud Circuit Breaker
- Baeldung — Guide to Resilience4j With Spring Boot
- Baeldung — Exponential Backoff and Jitter
- Baeldung — Resilience4j Events Endpoints
- Resilience4j — Getting Started
- Resilience4j — CircuitBreaker
- Resilience4j — Retry
- Resilience4j — Bulkhead
- Resilience4j — RateLimiter








