How would you design a filter-based rate limiting solution before ASP.NET Core 7's built-in rate limiting middleware existed, and why is the built-in middleware now generally preferred?
Short answer
A hand-rolled filter-based approach would use an IAsyncActionFilter checking a request counter (backed by IMemoryCache or IDistributedCache, keyed by client identity) against a threshold, short-circuiting with a 429 Too Many Requests if exceeded -- while functional, this…
Advertisement
AModel answer
A hand-rolled filter-based approach would use an IAsyncActionFilter checking a request counter (backed by IMemoryCache or IDistributedCache, keyed by client identity) against a threshold, short-circuiting with a 429 Too Many Requests if exceeded -- while functional, this reimplements what the built-in AddRateLimiter middleware (introduced in .NET 7) now provides more robustly, with built-in support for multiple algorithms (fixed window, sliding window, token bucket) and better integration with the overall pipeline, making the built-in middleware the generally preferred choice for new development.
// Legacy hand-rolled filter approach (pre-.NET 7 built-in rate limiting)
public class RateLimitFilter(IMemoryCache cache) : IAsyncActionFilter {
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) {
var key = $"ratelimit-{context.HttpContext.Connection.RemoteIpAddress}";
var count = cache.GetOrCreate(key, e => { e.SlidingExpiration = TimeSpan.FromMinutes(1); return 0; });
if (count >= 100) { context.Result = new StatusCodeResult(429); return; }
cache.Set(key, count + 1);
await next();
}
}Real-world example
A team maintaining a legacy filter-based rate limiter migrates to the built-in AddRateLimiter middleware after upgrading to .NET 7+, immediately gaining access to more sophisticated algorithms (sliding window, token bucket) without maintaining custom counter logic themselves.
Likely follow-ups
- What rate limiting algorithms does the built-in middleware support that a simple hand-rolled filter typically lacks?
- When might a custom filter-based approach still be justified over the built-in middleware?
Related topics