Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DocumentDB TransientFaultHandling Best Practice

I've been writing very verbose retry logic for throttled DocumentDB client calls.

The example below is a common example of this with 10 retry attempts.

My question is two fold: Is this best practice, and is there a less verbose way to handle this? I see that there is a Microsoft.Azure.Documents.Client.TransientFaultHandling nuget package that is supposed to achieve the same results with less code, but I cannot find any examples on StackOverflow or Google and there does not seem to be any clear documentation available from Microsoft.

int maxRetryAttempts = 10;

while (maxRetryAttempts > 0)
{
    try
    {
        // Attempt to call DocumentDB Method
        // ---[DocumentDB Method Here]---
    }
    catch (DocumentClientException de)
    {
        if (de.StatusCode.HasValue)
        {
            var statusCode = (int)de.StatusCode;

            if (statusCode == 429 || statusCode == 503)
            {
                //Sleep for retry amount
                Thread.Sleep(de.RetryAfter);

                //Decrement max retry attempts 
                maxRetryAttempts--;
            }

        }
    }
    catch (AggregateException ae)
    {                    
        foreach (Exception ex in ae.InnerExceptions)
        {
            if (ex is DocumentClientException)
            {
                var documentClientException = ex as DocumentClientException;
                var statusCode = (int)documentClientException.StatusCode;
                if (statusCode == 429 || statusCode == 503)
                {
                    //Sleep for retry amount
                    Thread.Sleep(documentClientException.RetryAfter);

                    //Decrement max retry attempts 
                    maxRetryAttempts--;
                }
                else
                {
                    throw;
                }
            }
        }
    }
}

if (maxRetryAttempts < 0)
{
    //Max retry attempts reached
}
like image 362
INNVTV Avatar asked Jun 26 '15 05:06

INNVTV


1 Answers

You can find sample code using the TransientFaultHandling Nuget package in the Github repo for the DocumentDB Data Migration Tool:

https://github.com/Azure/azure-documentdb-datamigrationtool/blob/master/DocumentDb/Microsoft.DataTransfer.DocumentDb.FunctionalTests/DocumentDbHelper.cs

Which looks something like this:

private static IReliableReadWriteDocumentClient CreateClient(IDocumentDbConnectionSettings connectionSettings)
{
    return new DocumentClient(new Uri(connectionSettings.AccountEndpoint), connectionSettings.AccountKey)
        .AsReliable(new FixedInterval(10, TimeSpan.FromSeconds(1)));
}
like image 91
Andrew Liu Avatar answered Nov 08 '22 23:11

Andrew Liu