Skip to content

Instantly share code, notes, and snippets.

@SaahilClaypool
Last active February 17, 2023 15:18
Show Gist options
  • Save SaahilClaypool/33be96ddf78b31654b2e87c99c39a626 to your computer and use it in GitHub Desktop.
Save SaahilClaypool/33be96ddf78b31654b2e87c99c39a626 to your computer and use it in GitHub Desktop.
Polly Rate Limiting with Retry
using Polly;
using Polly.RateLimit;
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
var task = (int i) => Console.WriteLine($"Firing {i}");
var rateLimit = Policy.RateLimitAsync(10, TimeSpan.FromMinutes(1), 5);
var retry = Policy
.Handle<RateLimitRejectedException>()
.WaitAndRetryAsync(
1000,
sleepDurationProvider: (_, ex, _) => ex switch
{
RateLimitRejectedException r => r.RetryAfter,
_ => TimeSpan.FromSeconds(1)
},
onRetryAsync: (_, ts, _, ctx) => {
Console.WriteLine($"Rate limiting {ts}...");
return Task.CompletedTask;
}
);
foreach (var i in Enumerable.Range(0, 100))
{
await retry.WrapAsync(rateLimit).ExecuteAsync(() => { task(i); return Task.CompletedTask; });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment