Introduction to Circuit Breaker

Reading Time: 3 minutes

Resilience4j is a lightweight, fault tolerance library for Java-based applications. It provides a set of simple and easy-to-use APIs to help developers build resilient and fault-tolerant applications. Resilience4j is built on the principles of the circuit breaker, bulkhead, and retry patterns, and is designed to help developers handle and recover from failures in distributed systems.

Resilience4j is designed to be modular and extensible, so developers can easily add and configure the resilience features they need. The library provides several modules, including:

  1. Circuit Breaker: Provides a way to stop requests to an external system when it is failing, and to fall back to a fallback mechanism.
  2. Rate Limiter: Provides a way to limit the rate of requests sent to an external system to prevent overloading.
  3. Retry: Provides a way to retry failed requests to an external system with configurable retries and delays between retries.
  4. Bulkhead: Provides a way to isolate different parts of the system from each other to prevent a failure in one part from affecting other parts.
  5. TimeLimiter: Provides a way to limit the time a request can take to prevent it from blocking the system for too long.

Circuit breaker

In distributed systems, applications often communicate with external services to get data or perform some action. However, these services can fail or become unresponsive, causing your application to hang or slow down. To prevent this, you can use the Circuit Breaker pattern.

The Circuit Breaker pattern is a design pattern that provides fault tolerance and resilience in distributed systems. It prevents cascading failures and allows your application to gracefully handle failures when communicating with external services.

In this blog, we will explore how to implement the Circuit Breaker pattern in a Spring Boot application using the Spring Cloud Circuit Breaker project.

Prerequisites: Before we start, make sure you have a basic understanding of Spring Boot, REST APIs, and how to build a simple Spring Boot application.

Steps to implement Circuit Breaker pattern in a Spring Boot application:

Step 1

Add dependencies The first step is to add the required dependencies to your project. For implementing the Circuit Breaker pattern, we will use the Spring Cloud Circuit Breaker project. You can add the following dependency to your pom.xml or build.gradle file

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>

Step 2

Create a Circuit Breaker instance The next step is to create a Circuit Breaker instance using the CircuitBreakerFactory class provided by Spring Cloud Circuit Breaker. You can create a Circuit Breaker instance like this

@Autowired

private CircuitBreakerFactory circuitBreakerFactory;

private CircuitBreaker circuitBreaker = circuitBreakerFactory.create(“myCircuitBreaker”);

In this example, we create a Circuit Breaker instance named myCircuitBreaker using the Resilience4j implementation.

Step 3

Wrap your method call with Circuit Breaker Once you have a Circuit Breaker instance, you can wrap your method call with the Circuit Breaker instance using the run method. For example, suppose you have a method that communicates with an external service to get data. You can wrap this method call with the Circuit Breaker instance like this

public String getData() {

return circuitBreaker.run(() -> {

// Call the external service to get the data

String data = externalService.getData();

return data;

}, throwable -> {

// Handle the fallback response

return “Fallback data”;

}); }

In this example, if the external service call fails, the Circuit Breaker will execute the fallback logic and return “Fallback data” instead of throwing an exception.

Step 4

Configure the Circuit Breaker You can configure the Circuit Breaker behavior by setting properties in your application’s configuration file. For example, to set the failure threshold to 3 and the timeout period to 5 seconds for a Resilience4j Circuit Breaker, you can add the following properties to your application.properties file

spring.cloud.circuitbreaker.resilience4j.configs.myCircuitBreaker.failureRateThreshold=0.3 spring.cloud.circuitbreaker.resilience4j.configs.myCircuitBreaker.waitDurationInOpenState=5000

Steps to implement Circuit Breaker pattern in a Spring Boot application using annotations

Step1

Similarly add dependency of circuit breaker

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>

Step 2

Create a class that contains the method you want to protect with a circuit breaker. Annotate this method with @CircuitBreaker to enable the circuit breaker behavior.

@Service

public class MyService {

@CircuitBreaker(name = “myCircuitBreaker” , fallbackMethod =” fallbackmethod”)

public String myMethod()

{ // your implementation here } }

public String fallbackmethod(Exception e)

{ // your implementation here }

fallbackmethod will came in picture when the external service will be down

Step 3

Add configuration to application.yml file

resilience4j:
  circuitbreaker:
    instances:
      userService:
        registerHealthIndicator: true
        eventConsumerBufferSize: 10
        failureRateThreshold: 50
        minimumNumberOfCalls: 5
        automaticTransitionFromOpenToHalfOpenEnabled: true
        waitDurationInOpenState: 5s
        permittedNumberOfCallsInHalfOpenState: 3
        slidingWindowSize: 10
        slidingWindowType: COUNT_BASED

Conclusion

In this blog we learned about the circuit breaker and also go through the basic is implementation

For a more technical blog, you can refer to the Knoldus bloghttps://blog.knoldus.com/

Written by 

Chiranjeev kumar is a Software intern at Knoldus. He is passionate about the java programming . He is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. He is a quick learner & curious to learn new technologies. His hobbies include listening music , playing video games.