In this article, we are going to present the
Circuit Breaker policy from the Failsafe library. Circuit breakers allow us to create an application that fails by temporarily disabling execution as a way of preventing system overload.
2. How it works
Circuit breakers have three states:
In close state executions are allowed. If a configurable number of failures occur, the circuit breaker changed to the open state. In the open state, a circuit breaker will fail executions with
CircuitBreakerOpenException. After a delay (configurable), the circuit breaker will transition to a half-open state. In this state, a configurable number of trial executions will be allowed. After that, the circuit breaker will transition to a closed or open state.
There are two types of circuit breaker:
- count based,
- time based.
A count-based circuit breaker will transition between states when recent execution results exceed a threshold. A time-based circuit breaker will transition between states when recent execution results exceed a threshold within a time. A minimum number of executions must be performed for a state transition to occur.
Time-based circuit breakers use a sliding window to aggregate execution results. The window is divided into 10-time slices, each representing 1/10th of the failureThresholdingPeriod. As time progresses, statistics for old time slices are gradually discarded, which smoothes the calculation of success and failure rates.
Circuit breakers can be easily configured to express when the breaker should be opened, half-opened, and closed.
A count-based circuit breaker can be configured to open when a successive number of executions have failed:
Or when, for example, 3 out of the last 5 executions have failed:
A time-based circuit breaker can be configured to open when several failures occur within a period:
Or when some failures occur out of a minimum number of executions within a period:
It can also be configured to open when the percentage rate of failures out of a minimum number of executions exceeds a threshold:
After opening, a breaker will delay for 1 minute by default before transitioning to half-open. We can configure a different delay:
The breaker can be configured to close again if many trial executions succeed, else it will re-open:
The breaker can also be configured to close again if, for example, 3 out of the last 5 executions succeed, else it will re-open:
If a success threshold is not configured, then the failure threshold is used to determine if a breaker should transition from half-open to either closed or open.
4. Event Listeners
CircuitBreaker can notify you when the state of the breaker changes:
5. JUnit test
This is a simple JUnit class that tests
In this article, we presented how to use the
Circuit Breaker policy in the Failsafe library. Circuit breakers allow us to prevent attacks on our server by disabling execution.