Polly – A Framework for Policy Based Retries of Transient Errors in C#
In the last few posts we looked at two ways of handling Transient Errors. The first post showed how we can write a custom retry logic for transient errors with exponential back-off. The second post showed how we can customize the Microsoft Azure Transient Fault Handling Block for dealing with transient errors.
In this final post, we’re going to look at Polly – a library that allows developers to express transient exception handling policies in a fluent manner. The Library provides many out of the box options for retrying transient errors, including Retry, Retry Forever, Retry and Wait, Wait and Retry Forever, and Circuit Breaker. This is really cool because you can just express your intention to use one of the retry mechanics in a fluent manner and trust the underlying framework to do the heavy lifting for you. No custom loops or try/catch block is needed !!!
The Goal
Our task remains unchanged from the previous posts, which is making an unauthenticated request to https://microsoft.sharepoint.com which throws an webexception. The code snippet is below:
static void ExecuteHTTPGetWithFlowThroughException(string requestUri)
{
Console.WriteLine(DateTime.Now);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.KeepAlive = false;
request.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
int requestStatus = (int)webResponse.StatusCode;
webResponse.Close();
}
System Requirements
- We need to Retry only on WebExceptions
- We need to retry three times
- We need to use Exponential Back-off
Polly will take care of all the requirements out of the box.
Step By Step Guide To Integrating Polly
Step # 1 Get the Nuget Package
Open VS2012(or later) -> Right Click on your Solution -> Select “Manage Nuget Packages for Solution” -> Search For “Polly” (screenshot below) -> click “Install”
Step # 2: Add a using directive for Polly to the beginning of your code file
using Polly;
Step # 3: Define the detection policy and retry policy
You’ll need to specify which type of exceptions needs to be retried and how the retry should be handled. In this case we’re interested in retrying for webexceptions only. We also want to retry 3 times and increase the wait time between retries exponentially.
The code snippet below accomplishes that. The highlighted parts reflect the implementation of our requirements.
var policy = Policy.Handle()
.WaitAndRetry(
3,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
(exception, timeSpan, context) =>
{
Console.WriteLine("Encountered exception {0}", exception.Message);
});
Step 4: Execute the Policy
Finally, execute the policy by passing it your custom function to run.
policy.Execute(() => ExecuteHTTPGetWithFlowThroughException("https://microsoft.sharepoint.com"));
So should I use Polly or the Transient Fault Handling Block or use a custom retry logic?
I personally liked Polly because it’s super easy to use and makes the programmer’s intent very clear. You can also chain all of the actions pretty easily in a fluent manner.
Use the Transient Fault Handling Application Block if you like more structured interface faced programming model. Also, If you’re dealing with Azure services, this is the way to go.
If you just need an one off retry action, feel free to copy paste the code from my previous post.