Skip to content

Instantly share code, notes, and snippets.

@AzimUddin
Last active January 18, 2016 10:18
Show Gist options
  • Save AzimUddin/d0613cbb6f852a57e05d to your computer and use it in GitHub Desktop.
Save AzimUddin/d0613cbb6f852a57e05d to your computer and use it in GitHub Desktop.
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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment