Rate Limiting in in .Net Framework 7.0
Rate limiting in .NET Core is a standard way to limit the number of requests a client may make to an API or service in a certain amount of time. This helps stop people from abusing the system, makes sure everyone uses it fairly, and keeps services from being overloaded.
- Middlware: - Microsoft.AspNetCore.RateLimiting middleware.
- Third-party libraries for earlier version (earlier to 7.0) like AspNetCoreRateLimit
Package in .Net 7.0 - dotnet add package Microsoft.AspNetCore.RateLimiting
Register in Program.cs file
using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("fixed", opt =>
{
opt.PermitLimit = 5;
opt.Window = TimeSpan.FromSeconds(10);
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = 2;
});
});var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/", () => "Hello, world!").RequireRateLimiting("fixed");
app.Run();
Policy Option - Rules:
- Fixed Window: Lets a certain number of requests through in a certain amount of time.
- Sliding Window: Like fixed, but the window moves with each request.
- Token Bucket: Allows bursts of traffic up to a limit, and refills tokens over time.
- Concurrency Limiter: Sets a limit on how many concurrent requests can be processed at the same time.
Before Framework 7.0 use package
- dotnet add package AspNetCoreRateLimit