Rate Limit
Rate Limit
Blog
Part of this blog
If you use Twitter, I believe you have heard about Rate Limit. There are many types of Rate Limit algorithms. However, I don't want to explain those algorithms. You may check here. I will try to add Rate Limit in .NET 8 Web API.
Please download .NET 8 SDK before running through the code.
I will use the Microsoft.AspNetCore.RateLimiting
and System.Threading.RateLimiting
packages. If you check on the Nuget package web page, those libraries target .NET 7. We don't need to worry. Let's try, hopefully, it is still compatible.
Please "clone" or download the code below.
We can start the project using dotnet run --project RateLimitDotNet
.
We need to focus on some codes.
builder.Services.AddRateLimiter(options => {
options.AddFixedWindowLimiter("Fixed", opt => {
opt.Window = TimeSpan.FromSeconds(3);
opt.PermitLimit = 3;
});
});
app.UseRateLimiter();
RequireRateLimiting("Fixed")
.
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi()
.RequireRateLimiting("Fixed");
How to test the Rate Limit? Since we use Fixed Rate Limit. We can try to request more than three times before 3 seconds. After that, the API will return status code 503. Please note that the API will not give status code 429 as explained in the comment.
Example of bulk requests:
We can say that the package still works as expected.
Thank you for reading. I am also open to any feedback or ideas for the next topics.