RateLimiting with RetryAfter not compiling
See original GitHub issueGreetings all. I’m trying to create a RateLimiter using the examples provided here: https://github.com/App-vNext/Polly#rate-limit
Specifically, I’m trying to build a Policy using the (retryAfter, context) predicate as stated in the example:
// Allow up to 20 executions per second with a burst of 10 executions,
// with a delegate to return the retry-after value to use if the rate
// limit is exceeded.
Policy.RateLimit(20, TimeSpan.FromSeconds(1), 10, (retryAfter, context) =>
{
return retryAfter.Add(TimeSpan.FromSeconds(2));
});
This is my code and it doesn’t compile because:
- The Policy.RateLimit must return a IAsyncPolicy
- I’m returning an IAsyncPolicy-TimeSpan
This is my code:
return Policy .HandleResult<HttpResponseMessage>(result => { return result.StatusCode == System.Net.HttpStatusCode.TooManyRequests; }) .Or<Polly.RateLimit.RateLimitRejectedException>() .WaitAndRetryForeverAsync((retryNum) => { Console.WriteLine($"Retrying. Num: {retryNum}"); return TimeSpan.FromTicks(1); }).WrapAsync( Policy.RateLimitAsync(mps, TimeSpan.FromSeconds(1), mps, (retryAfter, context) => { return retryAfter.Add(TimeSpan.FromSeconds(2)); }));
Is this a bug, or am I writing my policy incorrectly?
Issue Analytics
- State:
- Created a year ago
- Comments:5
Top GitHub Comments
Thank you! I applied the second snippet and it worked like a charm!
Let me try to rephrase it. If you want to / need to provide
retyrAfterFactory
you can’t return with anIAsyncPolicy
.So, you can’t combine an
IAsyncPolicy<HttpResponseMessage>
(your retry) with anIAsyncPolicy<TimeSpan>
(your ratelimit)If you want to make it compatible then you need to change the return type of the rate limiter to
HttpResponseMessage
something like this