.NET Polly Retry &Circuit Breaker Resilience Library

Cem Yasar
2 min readJul 17, 2022

Recently I have used Polly Lib. It is very elegant libary to wrap any method execution with Polly Library’s retry, circuit breaker, timeout and other policies. You can also wrap policies together. For instance at the same time you can wrap retry and circuit breaker policies together to create more effective resilient behaviour.

It has two main starting points. Policy and Policy<T>. They do not share same ancestor however you can switch between two different non generic and generic Pollys by PolicyBuilder object which is created by fluent method calls. Polly is mainly used to handle exceptions and Policy<T> is mainly used to handle custom conditions as well as exceptions. If you want to handle only exceptions so there is no need to use generic Polly. Therefore if you want to wrap Polly structure you must care about this aspect and I will share my solution after this article :) Moreover you can look at the details of Polly library by this address: http://www.thepollyproject.org/

One important tip :) You can create Retry policy locally however you should create circuit breaker policy in a more global scope. For instance, one method is tried couple of times and if there is no successful execution of that method then circuit breaker policy may intervene if you wrap with retry policy and circuit breaker policy will prevent execution of the method for a specific amount time, which is set when create circuit breaker policy is created. However if the circuit breaker policy is created also locally, after execution of the method the local scope will be lost and the objects, datas within will be lost and the policies also. You should be careful to design.

You can find simple retry policy and timeout policy examples from this simple github project:

You can download the simple project by this github link:

I will share the more complex example which creates handlers in a more dynamic way.

--

--