DEV Community

Bervianto Leo Pratama
Bervianto Leo Pratama

Posted on

11

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

๐Ÿ‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

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

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

๐Ÿ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay