question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

RateLimiting with RetryAfter not compiling

See original GitHub issue

Greetings 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:closed
  • Created a year ago
  • Comments:5

github_iconTop GitHub Comments

2reactions
Queenfernocommented, May 27, 2022

Thank you! I applied the second snippet and it worked like a charm!

2reactions
PeterCsalaHbocommented, May 27, 2022

Let me try to rephrase it. If you want to / need to provide retyrAfterFactory you can’t return with an IAsyncPolicy.

So, you can’t combine an IAsyncPolicy<HttpResponseMessage> (your retry) with an IAsyncPolicy<TimeSpan> (your ratelimit)

IAsyncPolicy<TimeSpan> limit = Policy
    .RateLimitAsync(mps, TimeSpan.FromSeconds(1), mps,
        (retryAfter, context) => retryAfter.Add(TimeSpan.FromSeconds(2)));

IAsyncPolicy<HttpResponseMessage> retry =  Policy
    .HandleResult<HttpResponseMessage>(result => result.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
    .Or<RateLimitRejectedException>()
    .WaitAndRetryForeverAsync((retryNum) => { Console.WriteLine($"Retrying. Num: {retryNum}"); return TimeSpan.FromTicks(1); });

var resilienceStrategy = Policy.WrapAsync<HttpResponseMessage>(retry, limit); //limit is not compatible

If you want to make it compatible then you need to change the return type of the rate limiter to HttpResponseMessage something like this

IAsyncPolicy<HttpResponseMessage> limit = Policy
    .RateLimitAsync(mps, TimeSpan.FromSeconds(1), mps,
        (retryAfter, context) => {
            var response = new HttpResponseMessage(System.Net.HttpStatusCode.TooManyRequests);
            response.Headers.Add("Retry-After", retryAfter.Add(TimeSpan.FromSeconds(2)).TotalSeconds.ToString());
            return response;
        });

IAsyncPolicy<HttpResponseMessage> retry =  Policy
    .HandleResult<HttpResponseMessage>(result => result.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
    .Or<RateLimitRejectedException>()
    .WaitAndRetryForeverAsync((retryNum) => { Console.WriteLine($"Retrying. Num: {retryNum}"); return TimeSpan.FromTicks(1); });

var resilienceStrategy = Policy.WrapAsync(retry, limit);
Read more comments on GitHub >

github_iconTop Results From Across the Web

Implementing 429 retries and throttling for API rate-limits - Anvil
The first thing we need to nail down is how to handle the error responses when the API limits are exceeded. If you...
Read more >
Rate limiting WebCient requests after certain number of ...
Is it possible to rate limit webclient requests for a url or any requests after a defined number of retries using resilience4j or...
Read more >
Rate limiting retries · Issue #1565 · resilience4j ...
One limitation that we've found in R4J that we had in our old library was the ability to rate-limit retry calls (e.g. only...
Read more >
Implementing Rate Limiting with Resilience4j
A deep dive into the Resilience4j ratelimiter module. This article shows why, when and how to use it to build resilient applications.
Read more >
Rate-Limiting with Spring Boot and Resilience4j
A deep dive into the Spring Boot Resilience4j RateLimiter module, this article shows why, when and how to use it to build resilient ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found