Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
In this tutorial, weβll talk about the Resilience4j library.
The library helps with implementing resilient systems by managing fault tolerance for remote communications.
The library is inspired by Hystrix but offers a much more convenient API and a number of other features like Rate Limiter (block too frequent requests), Bulkhead (avoid too many concurrent requests) etc.
2. Maven Setup
To start, we need to add the target modules to our pom.xml (e.g. here we add the Circuit Breaker):
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-circuitbreaker</artifactId>
<version>2.1.0</version>
</dependency>
Here, weβre using the resilience4jβcircuitbreaker module. All modules and their latest versions can be found on Maven Central.
In the next sections, weβll go through the most commonly used modules of the library.
3. Circuit Breaker
Note that for this module we need the resilience4j-circuitbreaker dependency shown above.
The Circuit Breaker pattern helps us in preventing a cascade of failures when a remote service is down.
After a number of failed attempts, we can consider that the service is unavailable/overloaded and eagerly reject all subsequent requests to it. In this way, we can save system resources for calls which are likely to fail.
Letβs see how we can achieve that with Resilience4j.
First, we need to define the settings to use. The simplest way is to use default settings:
CircuitBreakerRegistry circuitBreakerRegistry
= CircuitBreakerRegistry.ofDefaults();
Itβs also possible to use custom parameters:
CircuitBreakerConfig config = CircuitBreakerConfig.custom()
.failureRateThreshold(20)
.withSlidingWindow(5)
.build();
Here, weβve set the rate threshold to 20% and a minimum number of 5 call attempts.
Then, we create a CircuitBreaker object and call the remote service through it:
interface RemoteService {
int process(int i);
}
CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config);
CircuitBreaker circuitBreaker = registry.circuitBreaker("my");
Function<Integer, Integer> decorated = CircuitBreaker
.decorateFunction(circuitBreaker, service::process);
Finally, letβs see how this works through a JUnit test.
Weβll attempt to call the service 10 times. We should be able to verify that the call was attempted a minimum of 5 times, then stopped as soon as 20% of calls failed:
when(service.process(any(Integer.class))).thenThrow(new RuntimeException());
for (int i = 0; i < 10; i++) {
try {
decorated.apply(i);
} catch (Exception ignore) {}
}
verify(service, times(5)).process(any(Integer.class));
3.1. Circuit Breakerβs States and Settings
A CircuitBreaker can be in one of the three states:
- CLOSED β everything is fine, no short-circuiting involved
- OPEN β remote server is down, all requests to it are short-circuited
- HALF_OPEN β a configured amount of time since entering OPEN state has elapsed and CircuitBreaker allows requests to check if the remote service is back online
We can configure the following settings:
- the failure rate threshold above which the CircuitBreaker opens and starts short-circuiting calls
- the wait duration which defines how long the CircuitBreaker should stay open before it switches to half open
- the size of the ring buffer when the CircuitBreaker is half open or closed
- a custom CircuitBreakerEventListener which handles CircuitBreaker events
- a custom Predicate which evaluates if an exception should count as a failure and thus increase the failure rate
4. Rate Limiter
Similar to the previous section, this features requires the resilience4j-ratelimiter dependency.
As the name implies, this functionality allows limiting access to some service. Its API is very similar to CircuitBreakerβs β there are Registry, Config and Limiter classes.
Hereβs an example of how it looks:
RateLimiterConfig config = RateLimiterConfig.custom().limitForPeriod(2).build();
RateLimiterRegistry registry = RateLimiterRegistry.of(config);
RateLimiter rateLimiter = registry.rateLimiter("my");
Function<Integer, Integer> decorated
= RateLimiter.decorateFunction(rateLimiter, service::process);
Now, all calls on the decorated service block conform, if necessary, to the rate limiter configuration.
We can configure parameters like:
- the period of the limit refresh
- the permissions limit for the refresh period
- the default wait for permission duration
5. Bulkhead
Here, weβll first need the resilience4j-bulkhead dependency.
Itβs possible to limit the number of concurrent calls to a particular service.
Letβs see an example of using the Bulkhead API to configure a maximum number of one concurrent call:
BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(1).build();
BulkheadRegistry registry = BulkheadRegistry.of(config);
Bulkhead bulkhead = registry.bulkhead("my");
Function<Integer, Integer> decorated
= Bulkhead.decorateFunction(bulkhead, service::process);
To test this configuration, weβll call a mock service method.
Then, we ensure that Bulkhead doesnβt allow any other calls:
CountDownLatch latch = new CountDownLatch(1);
when(service.process(anyInt())).thenAnswer(invocation -> {
latch.countDown();
Thread.currentThread().join();
return null;
});
ForkJoinTask<?> task = ForkJoinPool.commonPool().submit(() -> {
try {
decorated.apply(1);
} finally {
bulkhead.onComplete();
}
});
latch.await();
assertThat(bulkhead.tryAcquirePermission()).isFalse();
We can configure the following settings:
- the maximum amount of parallel executions allowed by the bulkhead
- the maximum amount of time a thread will wait when attempting to enter a saturated bulkhead
6. Retry
For this feature, weβll need to add the resilience4j-retry library to the project.
We can automatically retry a failed call using the Retry API:
RetryConfig config = RetryConfig.custom().maxAttempts(2).build();
RetryRegistry registry = RetryRegistry.of(config);
Retry retry = registry.retry("my");
Function<Integer, Void> decorated
= Retry.decorateFunction(retry, (Integer s) -> {
service.process(s);
return null;
});
Now letβs emulate a situation where an exception is thrown during a remote service call and ensure that the library automatically retries the failed call:
when(service.process(anyInt())).thenThrow(new RuntimeException());
try {
decorated.apply(1);
fail("Expected an exception to be thrown if all retries failed");
} catch (Exception e) {
verify(service, times(2)).process(any(Integer.class));
}
We can also configure the following:
- the max attempts number
- the wait duration before retries
- a custom function to modify the waiting interval after a failure
- a custom Predicate which evaluates if an exception should result in retrying the call
7. Cache
The Cache module requires the resilience4j-cache dependency.
The initialization looks slightly different than the other modules:
javax.cache.Cache cache = ...; // Use appropriate cache here
Cache<Integer, Integer> cacheContext = Cache.of(cache);
Function<Integer, Integer> decorated
= Cache.decorateSupplier(cacheContext, () -> service.process(1));
Here the caching is done by the JSR-107 Cache implementation used and Resilience4j provides a way to apply it.
Note that there is no API for decorating functions (like Cache.decorateFunction(Function)), the API only supports Supplier and Callable types.
8. TimeLimiter
For this module, we have to add the resilience4j-timelimiter dependency.
Itβs possible to limit the amount of time spent calling a remote service using the TimeLimiter.
To demonstrate, letβs set up a TimeLimiter with a configured timeout of 1 millisecond:
long ttl = 1;
TimeLimiterConfig config
= TimeLimiterConfig.custom().timeoutDuration(Duration.ofMillis(ttl)).build();
TimeLimiter timeLimiter = TimeLimiter.of(config);
Next, letβs verify that Resilience4j calls Future.get() with the expected timeout:
Future futureMock = mock(Future.class);
Callable restrictedCall
= TimeLimiter.decorateFutureSupplier(timeLimiter, () -> futureMock);
restrictedCall.call();
verify(futureMock).get(ttl, TimeUnit.MILLISECONDS);
We can also combine it with CircuitBreaker:
Callable chainedCallable
= CircuitBreaker.decorateCallable(circuitBreaker, restrictedCall);
9. Add-on Modules
Resilience4j also offers a number of add-on modules which ease its integration with popular frameworks and libraries.
Some of the more well-known integrations are:
- Spring Boot β resilience4j-spring-boot module
- Ratpack β resilience4j-ratpack module
- Retrofit β resilience4j-retrofit module
- Vertx β resilience4j-vertx module
- Dropwizard β resilience4j-metrics module
- Prometheus β resilience4j-prometheus module
10. Conclusion
In this article, we went through different aspects of the Resilience4j library and learned how to use it for addressing various fault-tolerance concerns in inter-server communications.
