Per-key rate limits on the public API
C# · ASP.NET Core · advanced · modification
Adds per-key rate limiting to the public API with the built-in `Microsoft.AspNetCore.RateLimiting` middleware. `RateLimiting/ApiRateLimits.cs` (new) registers a `per-api-key` policy, one token bucket per authenticated key id (bursts of 60, refilled at one request per second, no queue), and a rejection handler that answers a 429 problem with `Retry-After` taken from the limiter's lease. `Program.cs` registers it, adds `UseRateLimiter()` to the pipeline and applies the policy to the `/v1` group. `RateLimitTests.cs` (new) covers the burst and the 429, two keys, 401s and the health check.
Public REST API of Parcelly, a shipment-tracking service for merchants: ASP.NET Core 10 minimal API on .NET 10 (C# 14, nullable reference types enabled, implicit usings), xUnit tests. Existing and unchanged: `AddApiKeyAuthentication()` registers the `ApiKey` authentication scheme, which reads `Authorization: Bearer <secret>`, looks the secret up through `IApiKeyStore` and, for a known key, signs the request in with the claims `key_id` (the key's id: a non-empty, server-generated string, not the secret, unique across all organizations) and `org_id`. A request without the header gets no result and an unknown secret fails; either way the `/v1` group's `RequireAuthorization()` answers 401. Every endpoint `MapShipmentEndpoints` maps requires an API key, and none allows anonymous access. There are at most 20,000 API keys. `AddProblemDetails`, `UseExceptionHandler` and `UseStatusCodePages` make every error `application/problem+json`, and an unhandled exception becomes a generic 500. `/healthz` is the load balancer's health check. The API runs as a single instance behind a load balancer that already limits requests per client IP. `tests/Parcelly.Api.Tests/ApiFactory.cs` is the existing `WebApplicationFactory<Program>` fixture: `CreateClientWithKey(secret)` returns a client that sends that bearer secret (none for `null`), with the test keys `SecretA` (id `key_a`) and `SecretB` (id `key_b`).
Requirements
- Every request to a `/v1` endpoint (a route the `/v1` group maps) is limited per API key: a key can send a burst of up to 60 requests, and its allowance refills at one request per second, never above 60. A key that starts with a full allowance gets at most 60 requests through plus one per second elapsed, however many arrive at once.
- The limit belongs to the API key that authenticated the request (its id); nothing else the client sends selects or shares a key's allowance. All `/v1` endpoints share a key's allowance. Requests answered 401 (no key, unknown key) are never counted, and `/healthz` is not limited. A path under `/v1` that matches no endpoint gets the framework's 404 problem (405 for a method the route does not map), with or without a key, and is neither limited nor counted.
- A request over the limit is not queued and its endpoint does not run: it gets `429 Too Many Requests` as `application/problem+json`, like the API's other errors, with a `Retry-After` header in whole seconds (at least 1) giving the limiter's estimate of when the key has room again. It uses none of the allowance. A request that is let through counts even if its endpoint then answers an error.
- Limits live in memory. The API runs as a single instance, and every key starting with a full allowance after a restart or deploy is acceptable. Traffic without a valid key stays limited per client IP by the load balancer (unchanged, out of scope).
- Use the built-in ASP.NET Core rate limiting middleware (no new package). Ship tests for the burst and the 429, separate keys, uncounted 401s and the health check.
Files touched
- src/Parcelly.Api/Program.cs
- src/Parcelly.Api/RateLimiting/ApiRateLimits.cs
- tests/Parcelly.Api.Tests/RateLimitTests.cs