Circuit Breaker is a design pattern used in microservices architecture where different services interacting with each other over a network, and circuit breaker protects them from cascading failures to enhance the resiliency and fault tolerance of a distributed system.
In simple terms, a Circuit Breaker is a protective and safety mechanism that prevents your application from continuously making requests to a service that has problems or is down.
This pattern is inspired by the electrical circuit breaker, which automatically opens the circuit if the current flow exceeds a certain threshold. This prevents the circuit from overheating and causing a fire.
In a microservices architecture, it works the same way, monitors the health of a microservice and automatically blocks requests from that service if it becomes unhealthy.
Closed: In this state, the circuit breaker allows normal service communication, and requests go through to the service. Circuit breaker monitors the responses from the service for errors. If the responses are successful with no issues, it remains in the closed state.
Open: When the number of failures reaches a threshold, the circuit breaker switches to the open state, preventing requests from reaching the service and providing a fallback response. (Threshold Value like 5 failures within 10 seconds)
Half-Open: Once the timeout or reset interval passes, the circuit breaker goes to the “Half-Open” state. It allows a limited number of test requests to pass through to the service to see if the service has recovered or not. If the test requests succeed, it means the service has recovered and the circuit breaker goes back to “Closed” state. If any of the test requests fails, it means the service has still issues and the circuit breaker goes to “Open” state to block further requests.
There are several tools and frameworks implementing the circuit breaker pattern. Here are some popular options:
1. Netflix Hystrix:
Hystrix is an open-source Java library that provides an implementation of the circuit breaker pattern to handle faults tolerance and latency in distributed systems and microservices architectures.
2. Resilience4j:
Resilience4j is a lightweight, easy-to-use library, which offers a powerful circuit breaker implementation inspired by Netflix Hystrix but designed with functional programming approach.