Last active
February 17, 2023 15:18
-
-
Save SaahilClaypool/33be96ddf78b31654b2e87c99c39a626 to your computer and use it in GitHub Desktop.
Polly Rate Limiting with Retry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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