Circuit Breaker Pattern Spring Boot
This article will tell you how to handle faulty services in spring boot microservice :

In this blog, i will try to share exactly how to implement circuitbreaker patterns in spring boot Microservice.
Before Practical implementation of the Circuit breaker Pattern, We should aware of why we want it.
Fault Tolerance: In a Microservices architecture-based project Fault tolerance is a way to handle the unavailability of a particular service by using some kind of stability patterns.
There are many stability patterns which have been used to achieve robustness and resilience including Circuit Breaker Pattern, Timeout Pattern, and Retry.
Circuit breaker is a pattern: The circuit breaker allows developers to prevent cascading failures in microservices, In Leamon terms, we can say that This circuit breaker design pattern says, that unless all interdependent services are open, the request should return a query, otherwise services which is dependent on downed services it should wait until that service to up.
Libraries to implement circuit breaker(hysterix,resillience4j).
A circuit breaker is implemented via a finite state machine there are mainly three states (open closed half-open).
Two special states (disabled and forced_open) .
Open state :
When the Circuit breaker moves to the “Open” state, requests from the Microservices will fail immediately, and an exception will be returned. However, after a timeout, the Circuit Breaker will go to the “Half-Open” state. We can say that as in an open electrical circuit current will never flow similar scenario is occurring here.
When the circuit is open the failure rate is above threshold value .
Half Open :
Half-Open state In this state, Based on the availability of Services the Circuit Breaker allows only a limited number of requests from the Microservice, to pass through and invoke the operation. If these requests are successful, the Circuit Breaker will go back to the “Closed” state. However, if any request fails again, it goes back to the “Open” state.
After wait duration the request goes to half open state of circuit breaker .
Closed state:
It is the state where all request by the user returns a successful response. That means it works without any failures. But if the number of failures in a certain period exceeds a threshold, the circuit will trip and will move to an “Open” state.
When the circuit is closed failure rate is always below threshold.
Depedencies to import in pom.xml file .
So use this dependency in the service where you want to use circuit breaker :
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-aop</artifactId></dependency>
Note: Below is screeshot of my application.yml file copy as it is Except fallback method name :
application.yml file :

This is going to be response of actuator :When dependent service i.e coursePayment is up:

Response When coursePayments Service is down :
it will return below object with reason of failures :

Controller Class :
@GetMapping("/{studentId}") @CircuitBreaker(name="coursePaymentsBreaker", fallbackMethod = "coursePaymentsFallback")
public ResponseEntity getSingleStudent(@PathVariable String studentId)
{
Student studnet = studentService.getStudentById(studentId);
log.info("Get Single studnet");
return ResponseEntity.ok(student);
}
//creating fallback method for circuitbreaker:
public ResponseEntity coursePaymentsFallback(String studentId,Exception ex)
{
Student s = userRepository.findById(studentId).orElseThrow(() -> new ResourceNotFoundException("Student Not found with Id" + studentId));
log.info("Fallback excecuted because service is down ",ex.getMessage());
Student stud = Users.builder().
email(s.getEmail()) .
name(s.getName()) .
about("failed because rating service is down") .userId(s.getStudentId()).build();
return new ResponseEntity<>(stud,HttpStatus.OK);
}
Hope it will work for you also :
