Rate Limiting in Minimal APIs in .NET 8

Chaitanya (Chey) Penmetsa
CodeNx
Published in
2 min readMar 27, 2024

In this blog let us see how we can configure Rate Limiting in Minimal APIs in .NET 8. We have seen what Rate Limiting is, why we need Rate Limiting etc. You can read that blog using below link:

Image created by author

Now let us see how we can add Rate Limiting to Minimal API using Microsoft.AspNetCore.RateLimiting NuGet package. First set up an empty ASP.NET Core project and add below NuGet packages for demonstrating Rate Limiting in Minimal API.

dotnet add package Microsoft.AspNetCore.RateLimiting
dotnet add package Swashbuckle.AspNetCore

We are adding swagger as well so that it will be easy to demonstrate rate limiting example. Then add the Rate Limiting and Swagger middlewares as shown below, as well as see how we can set minimal api endpoint to have rate limiting enabled.

using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Adding Rate Limiting
builder.Services.AddRateLimiter(options => {
options.AddFixedWindowLimiter("Fixed", opt => {
opt.Window = TimeSpan.FromSeconds(10);
opt.PermitLimit = 3;
});
options.RejectionStatusCode = 429;
});

var app = builder.Build();

app.UseSwagger();

app.UseRateLimiter();

app.MapGet("/", () => "Hello World!").RequireRateLimiting("Fixed");

app.UseSwaggerUI();

app.Run();

We have configured the Minimal API hello world endpoint to have rate limiting of 3 calls in 10 seconds, once the number of requests exceeds endpoint will return 429 as configured above.

With this we conclude this blog and in future blogs we will see how to implement different Rate Limiting Algorithms with Minimal APIs.

Source code can be found below:

🙏Thanks for taking the time to read the article. If you found it helpful and would like to show support, please consider:

  1. 👏👏👏👏👏👏Clap for the story and bookmark for future reference
  2. Follow me on Chaitanya (Chey) Penmetsa for more content
  3. Stay connected on LinkedIn.

Wishing you a happy learning journey 📈, and I look forward to sharing new articles with you soon.

--

--

Chaitanya (Chey) Penmetsa
CodeNx
Editor for

👨🏽‍💻Experienced and passionate software enterprise architect helping solve real-life business problems with innovative, futuristic, and economical solutions.