🛡️ Key Takeaways: Built-in rate limiting is finally here! Protect your endpoints from abuse with fixed window, sliding window, token bucket, and concurrency policies.
Your API is public, and attackers are relentless. .NET 8 brings native rate limiting to the party – no third-party libraries needed!
🔥 Quick Setup
// Program.cs - Add rate limiting
using System.Threading.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRateLimiter(options =>
{
// 1. Fixed Window: 100 requests per minute
options.AddFixedWindowLimiter("Fixed", opt =>
{
opt.PermitLimit = 100;
opt.Window = TimeSpan.FromMinutes(1);
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = 5;
});
// 2. Sliding Window: 200 requests per 30 seconds
options.AddSlidingWindowLimiter("Sliding", opt =>
{
opt.PermitLimit = 200;
opt.Window = TimeSpan.FromSeconds(30);
opt.SegmentsPerWindow = 3;
opt.QueueLimit = 10;
});
// 3. Token Bucket: Burst handling
options.AddTokenBucketLimiter("Token", opt =>
{
opt.TokenLimit = 100;
opt.QueueLimit = 5;
opt.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
opt.TokensPerPeriod = 10;
opt.AutoReplenishment = true;
});
// 4. Concurrency: 10 concurrent requests
options.AddConcurrencyLimiter("Concurrency", opt =>
{
opt.PermitLimit = 10;
opt.QueueLimit = 5;
});
});
// Use the middleware
app.UseRateLimiter();
🎯 Applying to Endpoints
// ✅ Apply globally
app.UseRateLimiter();
// ✅ Apply to specific endpoints
app.MapGet("/api/public", () => "Public")
.RequireRateLimiting("Fixed");
app.MapGet("/api/premium", () => "Premium")
.RequireRateLimiting("Sliding");
// ✅ Apply to controllers
[ApiController]
[Route("api/[controller]")]
[EnableRateLimiting("Token")]
public class OrdersController : ControllerBase
{
[HttpGet]
[DisableRateLimiting] // Disable for this endpoint
public IActionResult Get() { }
}
// ✅ Custom partitioner (per user)
options.AddFixedWindowLimiter("PerUser", opt =>
{
opt.PermitLimit = 50;
opt.Window = TimeSpan.FromMinutes(1);
})
.PartitionedHttpRequestLimiter = (context) =>
{
var userId = context.User.FindFirst("sub")?.Value ?? "anonymous";
return RateLimitPartition.GetFixedWindowLimiter(
userId,
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 50,
Window = TimeSpan.FromMinutes(1)
});
};
📊 Rate Limiting Strategies Comparison
| Strategy | Use Case | Burst Handling | Complexity |
|---|---|---|---|
| Fixed Window | Simple API limits | ❌ No bursts | Low |
| Sliding Window | Traffic smoothing | ✅ Partial | Medium |
| Token Bucket | Premium APIs | ✅ Yes | Medium |
| Concurrency | DB heavy ops | N/A | Low |
💡 Pro Tip: Custom Response
options.OnRejected = async (context, cancellationToken) =>
{
var response = context.HttpContext.Response;
response.StatusCode = StatusCodes.Status429TooManyRequests;
response.Headers["Retry-After"] = "60";
await response.WriteAsJsonAsync(new
{
status = 429,
message = "Rate limit exceeded. Please try again in 60 seconds.",
retryAfter = 60
});
};
