DEV Community

Bervianto Leo Pratama
Bervianto Leo Pratama

Posted on

Exploring Rate Limit Web API in .NET 8

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.

Implement Rate Limit

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.

Rate Limit

Rate Limit

Blog

Part of this blog




We can start the project using dotnet run --project RateLimitDotNet.

Code Explanation

We need to focus on some codes.

  • We should register the Rate Limit policies. In this case, we add a Fixed Rate Limit with a configuration that the maximum request is 3 with a time range of 3 seconds globally.
  builder.Services.AddRateLimiter(options => {
    options.AddFixedWindowLimiter("Fixed", opt => {
        opt.Window = TimeSpan.FromSeconds(3);
        opt.PermitLimit = 3;
    });
  });
Enter fullscreen mode Exit fullscreen mode
  • After, we add the Rate Limit as middleware.
app.UseRateLimiter();
Enter fullscreen mode Exit fullscreen mode
  • Finally, we should tell the controller or minimal Web API handler which Rate Limit policy/algorithm that should be used. Here is an example when using minimal Web API. Please focus on 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");
Enter fullscreen mode Exit fullscreen mode
  • Finished! You have completed all of your tasks. It's time to test. :)

Test Rate Limit

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:

Bulk Request

We can say that the package still works as expected.

Thank you

Thank you for reading. I am also open to any feedback or ideas for the next topics.

Limit

References

Top comments (2)

Collapse
 
tetri profile image
Tetri Mesquita

How can I change de 503 result to 429 to return that has too many requests?

Collapse
 
berviantoleo profile image
Bervianto Leo Pratama

You may try to add this line of code

options.RejectionStatusCode = 429;

A code like this

builder.Services.AddRateLimiter(options => {
    options.AddFixedWindowLimiter("Fixed", opt => {
        opt.Window = TimeSpan.FromSeconds(3);
        opt.PermitLimit = 3;
    });
    options.RejectionStatusCode = 429;
});
Enter fullscreen mode Exit fullscreen mode