Lesson 5 of 8
Rate Limiting Middleware (.NET 7+)
ASP.NET Core 7 includes built-in rate limiting with four algorithms: Fixed Window, Sliding Window, Token Bucket, and Concurrency. Rate limiting protects APIs from abuse, brute force attacks, and DDoS while keeping legitimate users unaffected.
Built-in Rate Limiter Policies
using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;
builder.Services.AddRateLimiter(options =>
{
// ━━ Policy 1: Fixed Window - N requests per time window ━━
// Resets entirely at window boundary. Simple but allows burst at boundary edges.
options.AddFixedWindowLimiter("api", cfg =>
{
cfg.PermitLimit = 100; // 100 requests
cfg.Window = TimeSpan.FromMinutes(1); // per minute
cfg.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
cfg.QueueLimit = 10; // queue 10 requests before rejecting
});
// ━━ Policy 2: Sliding Window - smoother, no boundary bursts ━━
options.AddSlidingWindowLimiter("auth", cfg =>
{
cfg.PermitLimit = 5; // max 5 attempts
cfg.Window = TimeSpan.FromMinutes(15); // per 15-minute window
cfg.SegmentsPerWindow = 3; // divide window into 3 segments
cfg.QueueLimit = 0; // no queue - reject immediately
});
// ━━ Policy 3: Token Bucket - allows bursting up to bucket capacity ━━
options.AddTokenBucketLimiter("download", cfg =>
{
cfg.TokenLimit = 10; // bucket capacity
cfg.ReplenishmentPeriod = TimeSpan.FromSeconds(1);
cfg.TokensPerPeriod = 2; // refill 2 tokens/second
cfg.AutoReplenishment = true;
});
// ━━ Policy 4: Per-user rate limiting (keyed by user ID or IP) ━━
options.AddPolicy("per-user", context =>
{
var userId = context.User?.FindFirst("sub")?.Value
?? context.Connection.RemoteIpAddress?.ToString()
?? "anonymous";
return RateLimitPartition.GetFixedWindowLimiter(userId, _ => new()
{
PermitLimit = 1000,
Window = TimeSpan.FromHours(1)
});
});
// ━━ Rejection response ━━
options.RejectionStatusCode = 429;
options.OnRejected = async (ctx, token) =>
{
ctx.HttpContext.Response.Headers["Retry-After"] = "60";
await ctx.HttpContext.Response.WriteAsJsonAsync(new
{
error = "Too many requests",
retryAfterSeconds = 60,
correlationId = ctx.HttpContext.Items["CorrelationId"]
}, token);
};
});
// Register middleware in pipeline:
app.UseRateLimiter();
// ━━ Apply to controllers/actions ━━
[EnableRateLimiting("api")]
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() => Ok();
[EnableRateLimiting("auth")] // stricter limit on auth endpoints
[HttpPost("login")]
public IActionResult Login() => Ok();
[DisableRateLimiting] // internal health-like endpoint
[HttpGet("ping")]
public IActionResult Ping() => Ok("pong");
}Tip
Tip
Practice Rate Limiting Middleware NET 7 in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Rate Limiting Middleware NET 7 from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Rate Limiting Middleware NET 7 is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?