Customizing Retry Logic in the .NET Azure Storage SDK

In my post on the Retry pattern I mentioned the .NET Azure Storage SDK has retry logic built-in to it. The default retry logic is usually sufficient for overcoming transient failures but sometimes it is useful to customize it further. This post gives a quick overview of how to tweak the retry strategy used by the .NET Azure Storage SDK.

There are several different retry strategies built-in to the library. They can be found in the Microsoft.WindowsAzure.Storage.RetryPolicies namespace. You can customize the policy by setting the DefaultRequestOptions.RetryPolicy property on the storage client instance. For the code samples in this post I am using a CloudBlobClient but the same property exists on the file, table, and queue classes as well. Let’s look at each of the available retry options.

ExponentialRetry

This is the default retry policy. ExponentialRetry performs a set number of retries using a randomized exponential back off to determine the interval between retries. By default it retries 3 times with an initial interval of 4 seconds. A different constructor allows you to override the defaults.

var blobClient1 = storageAccount.CreateCloudBlobClient();
// Use ExponentialRetry strategy. Initial time is 10 seconds with a maximum of 5 retry attempts.
blobClient1.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(10), 5);
view raw Program.cs hosted with ❤ by GitHub

LinearRetry

The LinearRetry policy retries a certain number of times with a fixed interval between each retry. It defaults to 3 retries with 30 second intervals, though this can also be customized during the instantiation.

var blobClient2 = storageAccount.CreateCloudBlobClient();
// Use LinearRetry strategy. Retry failed operations every 5 seconds a maximum of 10 times.
blobClient2.DefaultRequestOptions.RetryPolicy = new LinearRetry(TimeSpan.FromSeconds(5), 10);
view raw Program.cs hosted with ❤ by GitHub

NoRetry

This one is pretty self explanatory. If the process encounters an error it will fail immediately without retrying.

var blobClient3 = storageAccount.CreateCloudBlobClient();
// Use NoRetry strategy. Fail immediately on all errors.
blobClient3.DefaultRequestOptions.RetryPolicy = new NoRetry();
view raw Program.cs hosted with ❤ by GitHub

Roll Your Own

If for some reason none of the built-in policies work for you you can create your own by implementing the IRetryPolicy interface. You can check the library’s source on Github to see how the built-in policies are implemented for ideas.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.