Rate limiting middleware in ASP.NET Core
.NET 7 provides a rate limiter middleware for setting rate limiting policies. Web apps can configure these policies in Program.cs and then use them with API endpoints.
There are a several different rate limiter options, including:
- Fixed window
- Sliding window
- Token bucket
- Concurrency
Looking at the fixed window option in more detail, it uses a fixed amount of time to limit requests. Once the time has elapsed, the request limit is reset.
In the example below, we've created a TestPolicy fixed window limiter. The policy permits one request every 12 seconds.
We've also set a queue limit of 3, meaning that 3 requests will be left hanging until they can be processed. If more than 3 requests are queued, subsequent requests return a 503 Service Unavailable error.
To use this policy with an API endpoint, the EnableRateLimiting attribute can be assigned to it. It expects the policy name as a parameter of that attribute. As the policy is called TestPolicy, that's the parameter that we will pass into the attribute.
The [EnableRateLimiting] and [DisableRateLimiting] attributes can be applied to a Controller, action method, or Razor Page.
The [DisableRateLimiting] attribute disables rate limiting to the Controller, action method, or Razor Page regardless of named rate limiters or global limiters applied.
-
Publish Date:
Dec. 25, 2022 -
Author:
-
Category:
ASP .NET CORE