Creating a Resiliant API call with Retry

Polly-Logo@2x.pngSometimes when we call an API over HTTP it fails and needs to be re-tried. Using Polly I’ll show you a simple way to implement a retry strategy.

Here’s a simple API call that will fail half the time.

public class Api
{
    Random rnd = new Random(DateTime.Now.Millisecond);
    public async Task<stringGetHtml(string url)
    {
        if (rnd.Next(1,10)<5)
        {
            url = "http://sdsdfsdfsdfsdfsdfsdfsdf.com";
        }
        return await new HttpClient().GetStringAsync(url);
    }
}

Let’s add the Polly Nuget package and then change the API to this:

public class Api
{
    public async Task<stringGetHtml(string url)
    {
        var policyResult = await Policy<string>
            .Handle<HttpRequestException>()
            .WaitAndRetryAsync(5, retryNumber => TimeSpan.FromSeconds(.5))
            .ExecuteAndCaptureAsync(async () => await DoTheActualWork(url));
 
        return policyResult.Result;
    }
 
    Random rnd = new Random(DateTime.Now.Millisecond);
    public async Task<stringDoTheActualWork(string url)
    {
        if (rnd.Next(1,10)<5)
        {
            url = "http://asdfasdfasdfsdf.com";
        }
        return await new HttpClient().GetStringAsync(url);
    }
}

We added a wrapper around GetHtml() It will retry the call 5 times if it gets a HttpRequestException.

In actual implementation you’ll want to check for Status codes or other failure conditions.

There’s a lot more you can add with Polly like checking for values in the result:

var policyResult = await Policy<string>
    .Handle<HttpRequestException>()
    .Or<ArgumentException>()
    .OrResult(s=>s.Contains("We are sorry, the page you requested cannot be found."))
    .WaitAndRetryAsync(16, retryNumber => TimeSpan.FromSeconds(.5))
    .ExecuteAndCaptureAsync(async () => await DoTheActualWork(url));

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s