C
C#2y ago
PatrickG

❔ feedback on clientside api request limiter

Hello I just want to know if this is a good way of limiting requests made by a client to a public API. Is there a better way to do it ?? public static class Limit { static List<DateTime> requests = new List<DateTime>(); static public bool WaitForConstraint() { requests = requests.Where(x => x >= DateTime.Now.AddSeconds(-10)).ToList(); while (requests.Count > 150) { requests = requests.Where(x => x >= DateTime.Now.AddSeconds(-10)).ToList(); Console.WriteLine("throttleing requests."); } requests.Add(DateTime.Now); return true; } }
11 Replies
Kays
Kays2y ago
Maybe using  AspNetCoreRateLimit nugget package, and add configurations into your Program.cs could be a better solution. Search for it, there is a lot documentation
jcotton42
jcotton422y ago
.NET Blog
Announcing Rate Limiting for .NET - .NET Blog
Announcing built-in Rate Limiting support in .NET 7. Rate limiting provides a way to protect a resource to avoid overwhelming your app.
PatrickG
PatrickGOP2y ago
its in .net 6 lol anyways i'll just leave it as it should be fine
jcotton42
jcotton422y ago
System.Threading.RateLimiting 7.0.0
APIs to help manage rate limiting. Commonly Used Types: System.Threading.RateLimiting.RateLimiter System.Threading.RateLimiting.ConcurrencyLimiter System.Threading.RateLimiting.TokenBucketRateLimiter System.Threading.RateLimiting.RateLimitLease
jcotton42
jcotton422y ago
actually any runtime supporting standard 2.0
PatrickG
PatrickGOP2y ago
ok ill give it a shot then
jcotton42
jcotton422y ago
also if you do decide to keep your design, you should move away from DateTime it is not monotonic, meaning system clock changes can cause issue
jcotton42
jcotton422y ago
DateTime.Ticks Property (System)
Gets the number of ticks that represent the date and time of this instance.
PatrickG
PatrickGOP2y ago
thanks
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?