lucamilan
1/18/2016 - 10:18 AM

Azure DocumentDB .Net SDK example of executing an Async method with retry to handle RequestRateTooLargeException or HTTP 429 errors

Azure DocumentDB .Net SDK example of executing an Async method with retry to handle RequestRateTooLargeException or HTTP 429 errors

/// <summary>
/// Execute the function with retries on throttle
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="client"></param>
/// <param name="function"></param>
/// <returns></returns>
private static async Task<V> ExecuteWithRetries<V>(DocumentClient client, Func<Task<V>> function)
{
        TimeSpan sleepTime = TimeSpan.Zero;

        while (true)
        {
                try
                {
                    return await function();
                }
                catch (DocumentClientException de)
                {
                    if ((int)de.StatusCode != 429)
                    {
                        throw;
                    }
                    sleepTime = de.RetryAfter;
                }
                catch (AggregateException ae)
                {
                    if (!(ae.InnerException is DocumentClientException))
                    {
                        throw;
                    }

                    DocumentClientException de = (DocumentClientException)ae.InnerException;
                    if ((int)de.StatusCode != 429)
                    {
                        throw;
                    }
                    sleepTime = de.RetryAfter;
                }

                await Task.Delay(sleepTime);
        }
}
        
/// <summary>
/// Async method for inserting a single document, with retries
/// </summary>
/// <param name="student"></param>
/// <returns></returns>
private async Task InsertDocumentAsync(Student student)
{

        ResourceResponse<Document> response = await ExecuteWithRetries(client, () => client.CreateDocumentAsync(colSelfLink, student));
            
}