It is predominant that most of the front end depends on the back end service calls. In this blog,
we will learn how you can implement the retry pattern in C# using Polly.
What is Polly?
Polly is a library that allows developers to express resilience and transient fault handling policies such as Retry, Circuit Breaker,
Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner.
Polly targets .NET 4.6.1, .NET 4.7.2 and .Net Standard 1.1 and 2.0.
It is been around for a while.
Now Polly is adopted by
.Net Foundation.
So it is a fairly safe bet that this package will be nontoxic to use and will be supported by .Net Foundation.
Typically when we want to get the data from API, the service could be slow, could not respond or just down.
Retry Policy?
Polly offers multiple ways to build resilience services. We are building resilience on our service call by wait and retry policy.
As it is showed in below diagram. The Retry Pattern will retry in case of API exception. We can put the artificial delay between the retry.

I assume that you already have a Visual studio/ Vs Code installed on your machine.
- Create a new Console application project and name it as PollyRetryConsoleApp.
- Install nuget package Polly
- Copy paste below progam.cs.
- Create another class named waitAndRetryPolicy.
- Copy paste below waitAndRetryPolicy.cs.
Download Code
In this demo I am passing a bad url to a function.
In real example you can create your own API and throw exception to play with Polly.
WaitAndRetryAsync
In the below code look at the line number 18. We are creating a waitAndRetryAsync policy. To implement the retry policy with Polly, we need to tell Polly to handle
HttpResponseMessage result. Based on the result it will determine request was successful or not.
Line no.21
waitAndRetryAsync method instruct Polly to retry 3 times and wait for 2 seconds.
We specified Console.write to print message on retry parameter.
I ran the application where the application had to perform retries. As you can see Polly retried 3 times and waited for 2 seconds each time before retrying the request.
Conclusion
The approach of my blog is to always provide information for kick start. In this blog I demonstrated how we can use Polly to wait and retry.
This approach will self-heal in case of intermittent network glitch.
Posted On:03/20/2020