Skip to main content

Retry module - Resilience4j

as we discussed about circuit breaker module from resilience4j earlier, let's see what Retry module actually offers What is Retry in Resilience4j? this module offers ways of handling failure transaction by automatically retrying those transactions as per properties we configure. let's check how it works in this article. below code shows, how we can add retry annotation to our feign client Note: There is no need to add a fallbackMethod in the @Retry annotation if it is already defined in @CircuitBreaker . @GetMapping("/users/{userId}/albums") @Retry(name="album-service") @CircuitBreaker(name = "album-service", fallbackMethod = "getAlbumsFallbackMethod") public List<AlbumResponseModel> getAlbums(@PathVariable String userId); default List<AlbumResponseModel> getAlbumsFallbackMethod(String userId, Throwable exception) { System.out.println("user id" + userId); System.out.println("exc...

circuit breaker and its events - resilience4j

In this article, let's discuss about circuit breaker, its properties, and some of its events.

What is a Circuit Breaker?

It is a fault tolerance mechanism used in microservices. It is a part of Resilience4j. Circuit breaker is used to avoid multiple calls to non-responding microservices, preventing cascading failures.

How to Use Circuit Breaker

To use circuit breaker, add the below dependencies in your pom.xml:


<dependency>
    <groupId>io.github.resilience4j<groupId>
    <artifactId>resilience4j-spring-boot2<artifactId>
<dependency>

<dependency>
    <groupId>org.springframework.boot<groupId>
    <artifactId>spring-boot-starter-aop<artifactId>
<dependency>

Assuming we are using Feign Client for communication between microservices, here's an example from a user microservice calling an album microservice:


@FeignClient(name = "album-service")
public interface AlbumClientService {

    @GetMapping("/users/{userId}/albums")
    @CircuitBreaker(name = "album-service", fallbackMethod = "getAlbumsFallbackMethod")
    public List<AlbumResponseModel> getAlbums(@PathVariable String userId);

    default List<AlbumResponseModel> getAlbumsFallbackMethod(String userId, Throwable exception) {
        System.out.println("user id: " + userId);
        System.out.println("exception took place: " + exception.getMessage());
        return new ArrayList<>();
    }
}

Note: The @CircuitBreaker annotation uses a name attribute, which should match the configuration in application.properties.

Properties of Circuit Breaker


resilience4j.circuitbreaker.instances.album-service.failure-rate-threshold=50
resilience4j.circuitbreaker.instances.album-service.automatic-transition-from-open-to-half-open-enabled=true
resilience4j.circuitbreaker.instances.album-service.wait-duration-in-open-state=10000ms
resilience4j.circuitbreaker.instances.album-service.sliding-window-type=COUNT_BASED
resilience4j.circuitbreaker.instances.album-service.sliding-window-size=2
resilience4j.circuitbreaker.instances.album-service.minimum-number-of-calls=1
resilience4j.circuitbreaker.instances.album-service.event-consumer-buffer-size=10

Let's Discuss Each Property:

Property Description
failure-rate-threshold This is a percentage value. If more than 50% of calls fail, the circuit transitions to open state, and fallback method is called.
automatic-transition-from-open-to-half-open-enabled A boolean to allow automatic transition from open to half-open state.
wait-duration-in-open-state this is configured in seconds and milliseconds, such that the state will change to close state after the number of seconds we configured, if the other microservice still doesn't responds, it will change back to open state automatically(check the second property , we configured as true)
sliding-window-size this property is related to failure rate thresold, if the failure rate crosses the thresold, then the circuit state will be changed example, sliding window size is 2 and failure rate thresold is 50% , meaning so if 1 calls fails out of 2 , then the circuite state changes
sliding-window-type this property can be count based or time based, it will count the calls in our example in the window size
minimum-number-of-calls this tells to calculate the failure rate after minimum number of calls, for example, if minimum number of calls are mentioned as 7 and if sliding window size is 10 and lets say the failed calls are 6, as per failure rate thresold , failure calls actually crossed 5 calls, here it will not change the circuit state immediately, it will wait till 7 calls and then it will calculate the failure rate and changes the state.
event-consumer-buffer-size event consumer buffer size" determines how many circuit breaker events (like state transitions, successful calls, or errors) are stored before being processed. This buffer size is typically configurable, allowing you to control the amount of historical data the circuit breaker tracks.

Testing Circuit breaker

there few things to add in application properties, before testing circuit breaker

  
    management.endpoints.web.exposure.include=*
    management.endpoint.health.enabled=true
    management.endpoint.health.show-details=ALWAYS
    management.health.circuitbreakers.enabled=true
    management.endpoint.circuitbreakerevents.enabled=true
  

the above actuator properties should be added, we will test the circuit breaker by calling '/actuator/circuitbreakerevents'

assuming both microservices are up and when we make a call to album microservice, and check the aboveendpoint, the response will be as below


{
    "circuitBreakerEvents": [
        {
            "circuitBreakerName": "album-service",
            "type": "SUCCESS",
            "creationTime": "2025-05-24T08:35:21.444080200+05:30[Asia/Calcutta]",
            "errorMessage": null,
            "durationInMs": 313,
            "stateTransition": null
        }
    ]
}

to simulate the real time events, let's turn off album microservice and try to make call to it from usermicroservice. check the circuit breaker event url again

check the below response now


  {
    "circuitBreakerEvents": [
        {
            "circuitBreakerName": "album-service",
            "type": "SUCCESS",
            "creationTime": "2025-05-24T08:35:21.444080200+05:30[Asia/Calcutta]",
            "errorMessage": null,
            "durationInMs": 313,
            "stateTransition": null
        },
        {
            "circuitBreakerName": "album-service",
            "type": "ERROR",
            "creationTime": "2025-05-24T08:45:07.425775800+05:30[Asia/Calcutta]",
            "errorMessage": "feign.RetryableException: album-service executing GET http://album-service/users/c2eac55e-e996-464b-81f1-76aa3723e529/albums",
            "durationInMs": 2743,
            "stateTransition": null
        },
        {
            "circuitBreakerName": "album-service",
            "type": "FAILURE_RATE_EXCEEDED",
            "creationTime": "2025-05-24T08:45:07.426776500+05:30[Asia/Calcutta]",
            "errorMessage": null,
            "durationInMs": null,
            "stateTransition": null
        },
        {
            "circuitBreakerName": "album-service",
            "type": "STATE_TRANSITION",
            "creationTime": "2025-05-24T08:45:07.429458900+05:30[Asia/Calcutta]",
            "errorMessage": null,
            "durationInMs": null,
            "stateTransition": "CLOSED_TO_OPEN"
        }
    ]
}

let's understand the response, starting from second response in the reponse array, it says error, because the album microservice is down ,the third response says FAILURE_RATE_EXCEEDED , because we made two calls , minimum number of calls to be recorded to calculate the failure rate is 2 and failure rate thresold is 50%, out of 2 calls one is already failed. as the fourth response says STATE_TRANSITION which is as expected it will change the state to open and calls the fall back method

hit the endpoint again you will se the below response


 {
            "circuitBreakerName": "album-service",
            "type": "STATE_TRANSITION",
            "creationTime": "2025-05-24T08:45:17.435172300+05:30[Asia/Calcutta]",
            "errorMessage": null,
            "durationInMs": null,
            "stateTransition": "OPEN_TO_HALF_OPEN"
        }

this is because as configured automatic-transition-from-open-to-half-open-enabled as true after 10s(wait duration in open state)

finally , let's start the album microservice and get the last reponse

as you can see the circuit state is not closed and the call to album microservice from user microservice is success


 {
            "circuitBreakerName": "album-service",
            "type": "SUCCESS",
            "creationTime": "2025-05-24T09:07:45.515498800+05:30[Asia/Calcutta]",
            "errorMessage": null,
            "durationInMs": 265,
            "stateTransition": null
        },
        {
            "circuitBreakerName": "album-service",
            "type": "STATE_TRANSITION",
            "creationTime": "2025-05-24T09:07:45.516501800+05:30[Asia/Calcutta]",
            "errorMessage": null,
            "durationInMs": null,
            "stateTransition": "HALF_OPEN_TO_CLOSED"
        }

Comments

Popular posts from this blog

Retry module - Resilience4j

as we discussed about circuit breaker module from resilience4j earlier, let's see what Retry module actually offers What is Retry in Resilience4j? this module offers ways of handling failure transaction by automatically retrying those transactions as per properties we configure. let's check how it works in this article. below code shows, how we can add retry annotation to our feign client Note: There is no need to add a fallbackMethod in the @Retry annotation if it is already defined in @CircuitBreaker . @GetMapping("/users/{userId}/albums") @Retry(name="album-service") @CircuitBreaker(name = "album-service", fallbackMethod = "getAlbumsFallbackMethod") public List<AlbumResponseModel> getAlbums(@PathVariable String userId); default List<AlbumResponseModel> getAlbumsFallbackMethod(String userId, Throwable exception) { System.out.println("user id" + userId); System.out.println("exc...

Mastering Java Streams: Smart Ways to Handle Strings Like a Pro

Working with strings is a daily task for Java developers. But if you're still stuck in loops and if-else blocks, it’s time to level up! ๐Ÿ’ช Java Streams offer a clean, expressive, and functional way to process strings—whether you're transforming, filtering, or analyzing them. In this blog, we’ll explore: ๐Ÿ› ️ Different ways to use streams on strings in Java ๐Ÿ’ผ Popular interview questions involving Java strings and streams Whether you're a beginner or an experienced developer preparing for interviews, this guide has you covered. ✨ Section 1: Different Approaches to Use Streams on Strings in Java Let’s look at how to apply Java Streams on strings using various real-world examples. 1. Convert a String to a List of Characters List<Character> characters = str.chars() .mapToObj(c -> (char) c) .collect(Collectors.toList()); ๐Ÿงพ Explanation: str.chars() returns an IntStream of character codes. .mapToObj(c -> (char) c) casts each int...