Spring Cloud Circuit Breaker using Resilience4j

Spring Cloud Circuit Breaker Using Resilience4j | Assume person A went to withdraw cash from the ATM, the amount was deducted but money was not given. He files a complaint about it. Similarly, person B also went to the ATM, the amount was deducted but the money was not given. The same happens to multiple people. Since the ATM is failing to provide cash for many users. In this case, instead of giving error & malfunction to every user, it is better to display some message like “Service Unavailable”, so that the user won’t try to withdraw money for some time. Instead of malfunctioning/causing problems, not giving the service is still better.

Circuit Breaker: If the microservice is throwing exceptions in a continuous manner (default 20) then stop executing the actual method for the request for some time (like 5 sec), go to the dummy method directly, also provide notifications on the dashboard to the support team. We should provide values for max exception count and break time.

Fallback Method: If the actual microservice is throwing any exception, then it is redirected to one dummyService() method which gives output to the user. Such a dummy method is called as Fallback Method.

Circuit Breaker
  1. CLOSED CIRCUIT: When a request is made to the microservice, if it is sent to the actual method then it is called as CLOSED CIRCUIT.
  2. OPEN CIRCUIT: When a request is made to microservice, if it is sent to a fallback method then it is called OPEN CIRCUIT.
  • When we start microservice the CIRCUIT STATUS is CLOSED.
  • If 20 continuous requests got failed then CIRCUIT STATUS is OPEN for 5 sec.
  • Meanwhile, if any request comes (before 5 sec) directly send it to the fallback method.
  • After 5 sec if any request comes then try to execute actual Logic, still failed OPEN, else success CLOSED.

The Spring Cloud Netflix Hystrix project is deprecated. Netflix no longer supports the Hystrix core library, and as a result, Spring Cloud has also deprecated its Hystrix integration. New applications should avoid using Hystrix and instead consider alternative solutions for resilience and fault tolerance, such as Resilience4j.

Spring Cloud Circuit Breaker Example with Eureka Registry

  1. Create a Spring starter project “SpringCloudPaymentResilience4j”, and add dependencies:- Resilience4j (spring-cloud-starter-circuitbreaker-resilience4j), Eureka Discovery Client, Spring Web.

Also add Spring AOP dependencies:-

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  1. In application.yml:-
resilience4j.circuitbreaker:
  instances:
    paymentService:
      registerHealthIndicator: true
      slidingWindowSize: 5
      failureRateThreshold: 50
      waitDurationInOpenState: 5s
      permittedNumberOfCallsInHalfOpenState: 3
      minimumNumberOfCalls: 3
server:
  port: 9690
spring:
  application:
    name: SpringCloudPaymentResilience4j
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
  1. Create Controller class:-
package com.example.demo.controller;

import java.util.Random;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;

@RestController
@RequestMapping("/payment")
public class PaymentRestController {

    @GetMapping("/pay")
    @CircuitBreaker(name = "paymentService", fallbackMethod = "doPaymentFallback")
    public String doPayment() {
        System.out.println("From Actual Method");
        if (new Random().nextInt(99) < 100) {
            throw new RuntimeException("From Dummy Exception");
        }
        return "SUCCESS!!";
    }

    public String doPaymentFallback(Throwable t) {
        System.out.println("Fallback response due to exception: " + t.getMessage());
        return "FAILED! Try after some time!!";
    }
}

Execution order

  1. Start Eureka Server
  2. Start the Microservice application, and make a request to the URL:- http://192.168.31.151:9690/payment/pay

Explanation of the keys:-

  • registerHealthIndicator: true: Exposes Circuit Breaker health status via Spring Boot’s /actuator/health.
  • slidingWindowSize: 5: Considers the last 5 calls to calculate the failure rate.
  • failureRateThreshold: 50: Opens the Circuit Breaker if 50% of the last calls fail.
  • waitDurationInOpenState: 5s: Time the Circuit Breaker stays open before transitioning to a half-open state.
  • permittedNumberOfCallsInHalfOpenState: 3: Number of test calls allowed when in the half-open state.
  • minimumNumberOfCalls: 3: Minimum calls required before calculating the failure rate.
  • recordExceptions: - java.lang.RuntimeException: Treats RuntimeException as a failure to trigger the Circuit Breaker.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *