Overview
Apivalk provides a robust and flexible rate limiting system. It consists of several components working together to identify, track, and enforce limits on API requests. The rate limiting logic is decoupled from the routing itself, allowing you to define limits per route and enforce them using a dedicated middleware.Core Components
The rate limiting system is located in theapivalk\apivalk\Router\RateLimit namespace:
RateLimitInterface: The contract for all rate limit definitions. It defines the name, maximum attempts, window duration, and how the cache key is generated.IpRateLimit: A built-in implementation that limits requests based on the client’s IP address.RateLimiter: The engine that checks if a request is allowed. It interacts with aCacheInterfaceto track usage.RateLimitContext: A data object containing information about the current request (IP, identity, route, method) used to evaluate the rate limit.RateLimitResult: A result object returned by theRateLimiter, containing details like remaining attempts and reset time.
Defining a Rate Limit
You can define a rate limit on aRoute by passing an implementation of RateLimitInterface to its constructor.
Using IpRateLimit
TheIpRateLimit class takes three parameters:
- Name: A unique identifier for the limit (e.g., ‘login_limit’).
- Max Attempts: The maximum number of requests allowed within the window.
- Window Seconds: The duration of the rate limiting window in seconds.
Custom Rate Limits
You can create custom rate limiting strategies by implementingRateLimitInterface. For example, you might want to limit by authenticated user ID or by a specific request header.
Enforcement
Rate limits defined on routes are not enforced automatically. You must add theRateLimitMiddleware to your middleware stack to enable enforcement.
See the Rate Limit Middleware documentation for more details.