Latest Replies
Tuesday
Nov182008

Cloudy RetryPolicy from the Azure framework

While studying the sources of .NET StorageClient project (sample that comes with the Windows Azure SDK download) I've found really interesting implementation of the reliability layer.

Basically, the definition of the policy is as simple as this:

/// <summary> This delegate defines the shape of a retry policy. 
/// A retry policy will invoke the given action" as many times as 
//// it wants to in the face of retriable StorageServerExceptions.
/// </summary>
public delegate void RetryPolicy(Action action);

It is simple and beautiful, is not it?

And then you can declare specific policy implementations by just having method groups that match this signature like this one:

public static void NoRetry(Action action)
{
  try
  {
    action();
  }
  catch (TableRetryWrapperException e)
  {
      throw e.InnerException;
  }
}

// referencing the policy:
RetryPolicy retry = RetryPolicies.NoRetry;

or have more elaborate scenarios that actually compose the retry policy delegate from the passed arguments (simplified scenario below):

static void RetryNTimesImpl(Action action, int retryCount)
{
  for (int i=0; i< retryCount; i++)
  {
    try
    {
      action();
      return;          
    }
    catch (RetriableException ex)
    {
    }
  } 
}

public static RetryPolicy RetryNTimes(int count)
{
  return action => RetryNTimesImpl(action, count);
}

// referencing the policy:
RetryPolicy retry = RetryPolicies.RetryNTimes(3);

And the policy could be used just like:

retry(() =>
{
  // some failing operation   
});

C# is turning to be quite a functional language here.

We've got same style of composition in Lokad Shared Libraries for the validation rules. But for some strange reason I didn't even think about applying this line-saving development pattern to the exception handling policies in the same library (these exception policies happen to host the retry/reliability rules as well).

Well, kudos to the Cloud Computing at Microsoft for sharing this little gem.

« Using Windows Azure for the continuous integration | Main | System.TypeLoadException »