ASP.NET Rate Limiting middleware simple examples

Since .NET 7, ASP.NET has built-in middleware for rate limiting our API endpoints.

Once we understand the different rate limiting algorithms, the middleware is super easy to use. The simple examples (code on Gist) below will help you get started.

Click on the image for a larger view.


Does it work in a multi instance environment?

When we are in multi instance mode we have different and extra considerations. Since this middleware provides app-level rate limiting the request counters are stored in-memory on each instance so this solution won’t work effectively when we need to scale out.

There’s an open issue to support a Redis backed implementation which would work with load balanced scenarios and there’s also a third party Nuget which already supports this.

For the most robust option and one which protects us from a DDOS attack as it won’t allow traffic to our app in the first place we can rate limit on the edge at infrastructural level using something like Azure API gateway.

There is valid use cases for both infrastructural and app level rate limiting and indeed many devs combine both for maximum flexibility and control.

Leave a Reply

Your email address will not be published. Required fields are marked *