Thoughts on technology and life

Transient Exception Handling Circuit Breaker Pattern and Polly

Circuit Breaker pattern is a rather interesting pattern which was discussed in the Release It book. This pattern provides a mechanism to wrap “unpredictable code” i.e. calls to external services within a fabric that manages the execution of the actual code and takes certain actions if a certain pre-defined failure rate has been reached or a particular condition is met (for e.g. DividByZeroException happens)

The circuit breaker pattern has three states

1. Closed State – When the pattern is in closed state each call to the underlying resource is allowed or in other words the risky code is executed as it normally would. However on each failure an internal counter is incremembted and once the count hits a certain threshold the pattern moves to the Open state.
2. Open State – In this state the pattern sets an internal timer to elapse at a configured value. Until such time the timeout is reached no calls to the underlying resource are allowed. In some implementations of the pattern and as it was originally discussed dring this time the pattern throws an exception to indiciate that it is not allowing calls at this moment. I personally do not see much merit in this approach. Once the timeout is elapsed the pattern moves to Half Open state.
3. Half Open State – In this state the pattern allows one call to the underlying resource or the risky code. If this call succeeds the pattern immediately switches back to Closed state however if the call fails the pattern resets the timer and moves to Open state.

An open source project titled Polly brings this pattern beautifully to the .NET world along with a really structured way to allow developers to express transient exception handling policies such as Retry, Retry Forver, Circuit Breaker etc . Polly has complete async, await support. In a nutshell the approach constitutes of setting up “Policies” in the calling code where the code configures the Polly framework on how the developer wants to handle a particular situation if it happens. Next an instance of this policy is created and it is used to execute the code. Here are some details (taken from the Github page directly)