A simple Polly example with WebApi 2

Download full source code.

Want to learn more about Polly? Check out my Pluralsight course on it.

If you are calling APIs and you haven’t heard about The Polly Project, you should check it out. It helps take care of many common problems like unreliable connections, retries and circuit breaking. It can also be used to wrap code where other forms of transient exception may occur.

In this blog post I’m going to show the wait and retry policy when calling an unreliable Web Api endpoint.

When using Polly there are two pieces that need you need to code - the policy and the execution of code wrapped by the policy.

In this example the policy is created in the constructor of the controller, this is NOT what you should do in a real application. For an example using DI to share policies see “Reusing Polly Policies with Dependency Injection”.

1readonly RetryPolicy<HttpResponseMessage> _httpRequestPolicy;
2
3public ValuesController()
4{
5    _httpRequestPolicy = Policy.HandleResult<HttpResponseMessage>(
6            r => r.StatusCode == HttpStatusCode.InternalServerError)
7        .WaitAndRetryAsync(3,
8            retryAttempt => TimeSpan.FromSeconds(retryAttempt));
9}

This policy states that in the event that a HttpResponseMessage has a of InternalServerError, the request should be tried up to three times with a back off increasing by one second each time.

That’s the policy in place, now we need to call the web service endpoint.

 1public async Task<IHttpActionResult> Get()
 2{
 3   var httpClient = GetHttpClient();
 4   string requestEndpoint = "numbers/"; // numbers is the name of the controller being called
 5
 6   HttpResponseMessage httpResponse = await _httpRequestPolicy.ExecuteAsync(() => httpClient.GetAsync(requestEndpoint));
 7
 8   IEnumerable<int> numbers = await httpResponse.Content.ReadAsAsync<IEnumerable<int>>();
 9   
10   return Ok(numbers);
11}

If you execute the code it makes a GET request to http://localhost:2351/api/values, despite two failures when calling the NumbersController you will get a 200 response and a list of numbers.

If you want to verify this, step through the provided solution with the debugger. You’ll see that the first two requests to the NumbersContoller return 500 errors and that the third succeeds and returns an array of ints.

With just a few lines of code Polly provided us with a robust wait and retry mechanism for web requests.

In another blog I’ll show a better way of defining policies so they can be used in any controller.

Download full source code.

comments powered by Disqus

Related