WHAT is Retry Logic ?
When we use Azure storage, then it is advised to have a transient fault handling implemented with all the Azure related operations. We can create a Retry logic which will take care of that. Lets say we are downloading a really big file or updating huge records to DB. In that case, it may timeout or fails for other reasons. Why not have a mechanism that, lets say, tries 5 times, 60 seconds apart if it fails? This is Retry Logic.
WHY Retry Logic ? As stated, if we are working on Azure related operations, retry strategy needs to be implemented.
There are various such reasons why the request may fail: Basically, Azure maintains some mechanisms, by which it prevents virtual machines from becoming overloaded and unresponsive. Load balancers are there for maintaining VM overloads, timeouts, number of connections to DB etc. It monitors resource consumption and slows down or aborts if the consumption metrics exceeds a threshold. So connection loss is not so uncommon as it monitors and rebalances active and online databases in data centers automatically, and also terminates connections if necessary. And there’s the need of retry logic in Azure.
HOW to Implement ?
First, create a class like the following:
/// /// Contains method for retry logic /// public static class RetryLogic { /// /// A delegate to use the RetryLogic /// public delegate void VoidCaller(); /// /// Retry logic and execute plan for a delegate /// /// delegate public static void RetryExecute(Delegate code) { // Define your retry strategy: retry 5 times, 60 seconds apart. var retryStrategy = new FixedInterval(5, TimeSpan.FromSeconds(60)); // Define your retry policy using the retry strategy // and the Windows Azure storage // transient fault detection strategy. var retryPolicy = new RetryPolicy(retryStrategy); // Receive notifications about retries. retryPolicy.Retrying += (sender, args) => { // Log details of the retry. var msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}", args. CurrentRetryCount, args.Delay, args.LastException); Trace.WriteLine("Application", msg); }; try { // Do some work that may result in a transient fault. retryPolicy.ExecuteAction( () => { code.DynamicInvoke(); }); } catch (Exception ex) { Trace.TraceError(ex.TraceInformation()); throw; } } }
And use the retry logic like:
try { // Lets download a really big blob RetryLogic.VoidCaller downloadBlob = () => DownloadBlob(url, fileName, userName, password, downloadedFilePath); // This code may cause a failure, so add a retry logic to it RetryLogic.RetryExecute(downloadFile); } catch (Exception ex) { Trace.WriteLine("Application", "Exception while downloading the blob, Error Message: " + ex.Message); }
NOTE: You need to have a method to download a blob
void DownloadBlob(string url, string fileName, string userName, string password, string downloadedFilePath)