I have the following code which calls contentful cms. This is the code called by my webhook. So now since I'm new to this retry mechanism in C#.
How to achieve retry when the rate limiting error occurs from contentful? Contentful cms has tech limitation of 10 calls per second. If any calls has been failed then we need to retry them with the retry policy.
Any idea on how to start it.
public async Task HandleRedirectAsync(string slug, string previousSlug, string contentTypeId, string entryId)
{
var endpoint = "entries";
if (!string.IsNullOrEmpty(slug))
{
var isPreviousSlugNotEmpty = !String.IsNullOrEmpty(previousSlug);
var isSlugAndPreviousSlugSame = slug == previousSlug;
if (isPreviousSlugNotEmpty && isSlugAndPreviousSlugSame)
{
return;
}
//Delete API call to cms
await DeleteRedirectLoopsAsync(slug, contentTypeId, endpoint);
if (isPreviousSlugNotEmpty && !isSlugAndPreviousSlugSame)
{
await CreateAndPublishRedirectEntryAsync(entryId, previousSlug, slug);
}
await UpdateEntryAsync(contentTypeId, entryId);
}
}
You could have a look at how this is handled in the .NET SDK: https://github.com/contentful/contentful.net
Basically if there's a 429 result returned the request is cloned, a wait task is executed for the specified number of milliseconds and then the request is sent again.
Here's the relevant code:
if((int)response.StatusCode == 429 && _options.MaxNumberOfRateLimitRetries > 0)
{
//Limit retries to 10 regardless of config
for (var i = 0; i < _options.MaxNumberOfRateLimitRetries && i < 10; i++)
{
try
{
await CreateExceptionForFailedRequest(response).ConfigureAwait(false); ;
}
catch (ContentfulRateLimitException ex)
{
await Task.Delay(ex.SecondsUntilNextRequest * 1000).ConfigureAwait(false);
}
var clonedMessage = await CloneHttpRequest(response.RequestMessage);
response = await _httpClient.SendAsync(clonedMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
return response;
}
}
}