Most of the enterprise application uses external services to make an external operation like sending Email or SMS to send notification or external API, external resources to add functionality to our application. Whenever we are making a call to those external services, there may be a chance that those services are down. Our application should be prepared to handle that kind of scenario. We can handle this kind of scenario using retry pattern but retry pattern assumes that external service is available and continues to make a request
The circuit breaker pattern has different than a retry pattern. The circuit breaker prevents an application to perform an external services call that is likely to fail.
This pattern has three operation state:
- Close state
- Open state
- Half Open state
Close State: Operation are executed as usual (whenever we are making the first call to the external services at the time it will be in the closed state)
- If a call to external service fails: The failure count is incremented and an OperationFailedException is thrown. If the failure count exceeds the threshold, the circuit breaker trips into the “open” state.
- If a call to external service succeeds: if calls succeed before the threshold is reached, the failure counter is reset and operation are executed as usual
Open state: whenever circuit breaker is in open state all calls to the external services will fail and In this state, it will not make an actual call to the external services instead of it will throw an exception OpenStateException. A timeout is started when the circuit breaker trips.
Once the timeout is reached, the circuit breaker enter into the half state
Half state: In “half state” circuit breaker allows one operation to execute.
- If a call to external service fails: the circuit breaker re-enter into open state and timeout is reset.
- If a call to external service succeeds: circuit broker enters into close state and operations are executed as usual
Below sample code will be used to implement circuit breaker with Polly. Here we are creating the Polly handler for circuit breaker when WebException occurred during an external call. This policy will break the circuit with two consecutive exceptions of WebExcption type and the circuit will remain a broker
//creating policy object for handle webexception using circuit breaker Policy policy = Policy.Handle() .CircuitBreaker( exceptionsAllowedBeforeBreaking: 2, durationOfBreak: TimeSpan.FromMinutes(1) ); //To Excute external service call policy.Execute(action);
For a better understanding of the circuit breaker using Polly, you can check it out on below link
I have also created sample repo in GitHub to provide you a basic understanding to implement circuit breaker with Polly nuget package. GitHub demo-application-circuit-breaker