Rate Limiting
RateLimitMiddleware uses Atom's cache to count requests in fixed time windows. Attach it where an endpoint needs a quota, such as a report export.
Route or group usage
Attach the middleware to an individual route. Here $createExport is your existing handler.
use Atom\Http\RateLimitMiddleware;
use Atom\Router\Route;
Route::post("/exports", $createExport)
->middleware(RateLimitMiddleware::class);
Attach it to a group when several routes use the same settings. With the default path-based counting, each path still has its own quota.
Route::group("/reports", static function () use ($createExport, $refreshReport): void {
Route::post("/exports", $createExport);
Route::post("/refresh", $refreshReport);
})->middleware(RateLimitMiddleware::class);
Configuration
Set the request quota and the window length in seconds. This example allows 10 requests per 60-second window.
RATE_LIMIT_MAX_ATTEMPTS=10
RATE_LIMIT_WINDOW_SECONDS=60
The default is 60 requests per 60 seconds, counted by effective client IP and path. Set RATE_LIMIT_INCLUDE_PATH=false to share a quota across paths, or RATE_LIMIT_INCLUDE_METHOD=true to count methods separately. A limit of 0 disables the middleware.
When the limit is reached
The last request within the quota still reaches the handler and has zero remaining. The next request in the same window receives 429 Too Many Requests with the plain-text body Too many requests. The handler does not run for that request.
| Header | Meaning |
|---|---|
X-RateLimit-Limit |
Request quota for the window. |
X-RateLimit-Remaining |
Requests still available in the current window. |
X-RateLimit-Reset |
Unix timestamp when the next window starts. |
Retry-After |
On a 429 response, seconds to wait before retrying. |
Global usage and order
If you register the limiter globally, put Trusted Proxies first when applicable so the limiter sees the effective client IP. Put CORS before the limiter so preflights handled by CORS do not count against the quota.