❔ 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
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
.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.
its in .net 6 lol
anyways i'll just leave it as it should be fine
it's a nuget that you can install on 6 https://www.nuget.org/packages/System.Threading.RateLimiting/#readme-body-tab
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
actually any runtime supporting standard 2.0
ok ill give it a shot then
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
instead use something like https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch.gettimestamp?view=net-7.0
Stopwatch.GetTimestamp Method (System.Diagnostics)
Gets the current number of ticks in the timer mechanism.
info on what constitutes a tick https://learn.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=net-7.0#remarks
DateTime.Ticks Property (System)
Gets the number of ticks that represent the date and time of this instance.
thanks
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.