A walkthrough of adding per-IP rate limiting to a Minimal API using the middleware that has shipped with .NET since version 7. It covers naming a fixed window policy, returning 429 with a Retry-After header, excluding health checks, integration testing with WebApplicationFactory, and the multi-instance and reverse proxy pitfalls that break limits in production.
Key points
- Rate limiting has shipped in the framework since .NET 7, so no third-party package is needed.
- Pick a limiter algorithm (fixed, sliding, token bucket, concurrency) and a partition key such as the client IP.
- Set RejectionStatusCode to 429 and QueueLimit to 0 to reject excess requests immediately instead of queuing them.
- Use OnRejected with MetadataName.RetryAfter to return a Retry-After header and stop clients from guessing.
- Call UseRateLimiter() before mapping endpoints and apply policies per route with RequireRateLimiting().
- Test the limit with WebApplicationFactory using a low limit and a long window so timing does not break the test.
Why it matters
A single unbounded client can exhaust your database and CPU, and the built-in limiter removes that risk without adding a dependency; knowing the per-instance and proxy caveats stops you from shipping a limit that silently does nothing.
Real-world use
- A public REST API that must stay available when a buggy retry loop hammers one endpoint.
- An API behind a load balancer where health check probes must keep answering while client calls are throttled.
- A per-tenant SaaS backend that wants a cheap first line of defence before adding a shared Redis counter.
- A CI pipeline that verifies with WebApplicationFactory that the 429 and Retry-After behaviour never regresses.
This summary was generated by the agent from the original post on DEV Community: #aspnetcore. The full text and all rights belong to its author and publisher. Go to original