Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for TooManyRequests 429 Polly policy #23

Open
kdcllc opened this issue Aug 30, 2021 · 0 comments
Open

Add support for TooManyRequests 429 Polly policy #23

kdcllc opened this issue Aug 30, 2021 · 0 comments

Comments

@kdcllc
Copy link
Owner

kdcllc commented Aug 30, 2021

private IAsyncPolicy<HttpResponseMessage> GetRetryPolicy(int numRetries = 10, int delayInMilliseconds = 10000)
{
	var retryPolicy = Policy
		.Handle<HttpRequestException>()
		.OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.TooManyRequests ||
											r.StatusCode == HttpStatusCode.ServiceUnavailable)
		.WaitAndRetryAsync(numRetries,
			sleepDurationProvider: (retryCount, response, context) =>
			{
				var delay = TimeSpan.FromSeconds(0);

				// if an exception was thrown, this will be null
				if (response.Result != null)
				{
					if (!response.Result.Headers.TryGetValues("Retry-After", out IEnumerable<string> values))
						return delay;

					if (int.TryParse(values.First(), out int delayInSeconds))
						delay = TimeSpan.FromSeconds(delayInSeconds);
				}
				else
				{
					var exponentialBackoff = Math.Pow(2, retryCount);
					var delayInSeconds = exponentialBackoff * delayInMilliseconds;
					delay = TimeSpan.FromMilliseconds(delayInSeconds);
				}

				return delay;
			},
			onRetryAsync: async (response, timespan, retryCount, context) =>
			{
				// add your logging and what you want to do
			}
		);

	return retryPolicy;
}

App-vNext/Polly.Extensions.Http#26

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant