How it Works
TheRateLimitMiddleware inspects the matched route for any defined rate limit. If a rate limit exists, it uses the RateLimiter and the provided CacheInterface to track and validate the request frequency.
Key features:
- Automated Enforcement: If a route has a rate limit definition, the middleware handles the tracking and response automatically.
- Standard Headers: It automatically adds
X-RateLimit-*headers to the response, informing the client about their current status. - Retry-After: When a limit is exceeded, it includes a
Retry-Afterheader indicating when the client can try again.
Mandatory Cache Integration
Rate limiting requires a persistent storage to track request counts across multiple requests and processes. Therefore, providing aCacheInterface implementation is mandatory when instantiating the middleware.
Usage
To enable rate limiting for your application, add the middleware to your configuration. It is generally recommended to place it early in the stack, but after authentication if you want to use identity-based rate limiting.Response
When a client exceeds the defined rate limit, the middleware short-circuits the request and returns aTooManyRequestsApivalkResponse (HTTP 429).