Explain Circuit Breaker Pattern in microservices with an example

By | March 16, 2023

The Circuit Breaker pattern is a design pattern used in distributed systems to prevent cascading failures when a microservice is unable to handle requests due to an external dependency being unavailable or experiencing high latency. The Circuit Breaker pattern acts as a barrier between the microservice and the external dependency, and if the external dependency fails or experiences high latency, the Circuit Breaker trips and provides a fallback mechanism.

In Java microservices, the Circuit Breaker pattern can be implemented using libraries such as Hystrix or Resilience4j. Here’s an example of how the Circuit Breaker pattern can be implemented in Java using Hystrix:
public class MyService {

private final HystrixCommand.Setter config = HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(“MyService”))
.andCommandKey(HystrixCommandKey.Factory.asKey(“myServiceCommand”))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(“MyServiceThreadPool”))
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter()
.withCircuitBreakerEnabled(true)
.withCircuitBreakerRequestVolumeThreshold(10)
.withCircuitBreakerErrorThresholdPercentage(50)
.withCircuitBreakerSleepWindowInMilliseconds(5000)
);

@HystrixCommand(fallbackMethod = “fallback”)
public String callExternalService() {
// Code to call external service
}

public String fallback() {
// Fallback mechanism
}
}
In this example, the HystrixCommand is used to wrap the call to the external service. The Circuit Breaker is enabled by setting the circuitBreakerEnabled property to true. The circuitBreakerRequestVolumeThreshold property is set to 10, which means that if there are fewer than 10 requests in a rolling window, the Circuit Breaker will not trip. The circuitBreakerErrorThresholdPercentage property is set to 50, which means that if 50% or more of the requests in a rolling window result in an error, the Circuit Breaker will trip. The circuitBreakerSleepWindowInMilliseconds property is set to 5000, which means that the Circuit Breaker will stay open for 5 seconds before allowing another request to go through.

The fallback method is called if the Circuit Breaker trips and the call to the external service fails. The fallback method provides a fallback mechanism for handling the failure, which could be to return a default value or to retry the call after a delay.

By using the Circuit Breaker pattern, the microservice is protected from cascading failures caused by external dependencies that are unavailable or experiencing high latency. The Circuit Breaker provides a fallback mechanism that allows the microservice to continue functioning even if the external dependency fails.

Leave a Reply

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