Introduction
Modern APIs are frequently exposed to the internet and may receive thousands of requests every minute. While this is expected for popular applications, excessive requests from a single user, bot, or malicious actor can negatively impact performance and availability.
Rate Limiting helps protect applications by controlling how many requests a client can make within a specific time period.
Common benefits include:
Preventing API abuse
Protecting against brute-force attacks
Improving application stability
Reducing server load
Ensuring fair resource usage
In this article, you'll learn how to implement Rate Limiting in ASP.NET Core applications using the built-in Rate Limiting middleware.
What Is Rate Limiting?
Rate Limiting restricts the number of requests a client can make during a defined time window.
Example:
Limit:
100 Requests
Per:
1 Minute
If the client exceeds the limit:
HTTP 429
Too Many Requests
The request is rejected until the limit resets.
Why Use Rate Limiting?
Consider a public API.
Without rate limiting:
User
↓
10,000 Requests
↓
Server Overload
Potential issues:
High CPU usage
Slow responses
Denial-of-Service attacks
Increased hosting costs
With rate limiting:
User
↓
100 Requests/Minute
↓
Controlled Traffic
The application remains stable and responsive.
Built-In Rate Limiting in ASP.NET Core
Starting with .NET 7, Microsoft introduced built-in Rate Limiting middleware.
Install the package if required:
dotnet add package
Microsoft.AspNetCore.RateLimiting
Most modern ASP.NET Core templates already include the necessary support.
Configure Rate Limiting
In Program.cs, add the service.
using System.Threading.RateLimiting;
builder.Services.AddRateLimiter(
options =>
{
options.AddFixedWindowLimiter(
"fixed",
config =>
{
config.PermitLimit = 100;
config.Window =
TimeSpan.FromMinutes(1);
});
});
This configuration allows:
100 Requests
Per Minute
for each client.
Enable the Middleware
Register the middleware.
app.UseRateLimiter();
This activates rate limiting for the application.
Apply Rate Limiting to Endpoints
Apply the policy to specific endpoints.
app.MapGet("/products", () =>
{
return Results.Ok("Products");
})
.RequireRateLimiting("fixed");
Now the endpoint follows the configured limit.
Global Rate Limiting
You can apply a policy globally.
builder.Services.AddRateLimiter(
options =>
{
options.GlobalLimiter =
PartitionedRateLimiter.Create<
HttpContext, string>(
context =>
RateLimitPartition
.GetFixedWindowLimiter(
"global",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 100,
Window = TimeSpan.FromMinutes(1)
}));
});
Join the conversation! Your thoughts help the community grow.