It is unusual for the modern applications to be disconnected from the outside world. Remote servers, distributed databases, external services – all those technologies enrich the application. However, networks split, databases crush and servers reboot. When introduced without an adequate control, these services may become an additional point of failure.
Polly is a .NET library that helps to handle transient errors such us described above. In the .NET applications these issues usually lead to exceptions and Polly provides a way to define exception handling policies.
For example, HttpClient may throw HttpRequestException when network is temporary unavailable. In this case Polly can be configured to retry the request. Here is how.
First, we need to install Poly NuGet package by executing the following commang in the Package Management Console
PM> Install-Package Polly
Next step is to define a policy: provide a list of exceptions to handle and the policy behavior
var policy = Polly.Policy.Handle
() .WaitAndRetryAsync(5, i=>TimeSpan.FromSeconds(i));
This sample policy instructs Polly to retry failed operation five times, waiting before the each retry with the increasing time interval. After the five retries any new exception will be re-thrown to the caller.
When policy is defined, it can be used any number of times to execute similar operations
var result = await policy.ExecuteAsync(() => httpClient.GetStringAsync("http://lunarfrog.com/blog"));
As you can see from the example, Polly supports async/await semantics, but it also can be called in a fully synchronous way, if needed. Policies can be nested and support filtering on the exception properties.
In addition to the simple Retry, WaitAndRetry and RetryForever patterns, Polly also support mode advanced patterns such as Circuit Braker. This patterns allows to handle the situations of real (non-transient) failures and prevent the system from spending cycles on useless retries.
Current version of Polly supports .NET 3.0 to 4.6 and .NET Core / .NET Standard support coming shortly.blog comments powered by Disqus