raneomik / nette-rate-limiter
🚦 Nette Rate Limiter Extension: nette wrapper around https://github.com/symfony/rate-limiter
Requires
- php: >=8.3
- nette/application: ^3.2
- nette/di: ^3.2
- nette/http: ^3.3
- nette/schema: ^1.3
- symfony/lock: ^7.4 || ^8.0
- symfony/rate-limiter: ^7.4 || ^8.0
Requires (Dev)
- infection/infection: ^0.35.8
- latte/latte: ^3.1
- nette/bootstrap: ^3.3
- nette/security: ^3.2
- nette/tester: ^2.6
- phpro/grumphp: ^2.23
- phpstan/extension-installer: ^1.4
- phpstan/phpdoc-parser: ^2.3
- phpstan/phpstan-nette: ^2.0
- psr/cache: ^3.0
- raneomik/infection-tester-adapter: ^0.3.3
- rector/rector: ^2.7
- symplify/easy-coding-standard: ^13.3
- tomasvotruba/type-coverage: ^2.2.0|^2.3
- tracy/tracy: ^2.12
Suggests
- ext-apcu: Default storage: counters shared by every thread/worker of one PHP instance; without it, files in %tempDir%
- ext-sysvsem: Default lock (semaphore); without it, the lock falls back to files in %tempDir%
- nette/security: To count per logged-in user (key: user)
- tracy/tracy: To see the limiters hit by a request in the Tracy panel
Provides
None
Conflicts
None
Replaces
None
README
Work In Progress
🚦 Rate limiting for Nette, on top of symfony/rate-limiter.
- Limits are declared in neon; code only refers to them by name.
#[RateLimit('name')]on presenter methods, orRateLimiter::enforce('name').- Fixed window, sliding window, token bucket.
- APCu storage by default (files where APCu is inactive), any shared storage otherwise.
- Fails open: a broken storage never blocks requests.
Requirements
- PHP 8.3+,
nette/application,nette/di,nette/http symfony/rate-limiterandsymfony/lock7.4 or 8.x- Optional:
ext-apcu(default storage, faster than its file fallback),ext-sysvsem(default lock),nette/security(key: user),tracy/tracy(panel)
Usage
composer require raneomik/nette-rate-limiter
extensions: rateLimiter: Raneomik\NetteRateLimiter\Bridge\DI\RateLimiterExtension(%debugMode%) rateLimiter: limiters: search: {policy: sliding_window, limit: 60, interval: 1 minute} search-slow: {extends: search, limit: 10} login: {policy: fixed_window, limit: 5, interval: 10 minutes} signup-all: {policy: fixed_window, limit: 100, interval: 1 hour, key: global} api: {policy: token_bucket, limit: 20, rate: {interval: 1 minute, amount: 10}, key: user}
#[RateLimit('login')] public function handleLogin(): void { /* ... */ } // elsewhere (a hook, a conditional limit): $this->rateLimiter->enforce('api');
Limiters
| Option | Values |
|---|---|
policy |
fixed_window, sliding_window, token_bucket |
limit |
int ≥ 1 (bucket size for token_bucket) |
interval |
10 seconds, 1 minute… (windows) |
rate |
{interval: …, amount: 1} (token_bucket) |
key |
client (default: IP, IPv6 per /64), user (falls back to client), global |
extends |
another limiter: copied, then overridden; it keeps its own counter |
An invalid configuration fails at container compilation, naming the limiter.
Counters
| Where | Counter |
|---|---|
#[RateLimit] |
limiter + presenter + key |
enforce() |
limiter + key |
- The attribute is repeatable and works on
action*,render*andhandle*; a request counts once per limiter. - On a component's signal, the component's class is read from the return type of its
createComponent<Name>()factory, without creating it. Declare that return type; components added withaddComponent()are not seen, useenforce()in theirhandle*method. - An undeclared name throws
UnknownLimiterException, in every environment.
Limit exceeded
A TooManyRequestsException (429, Retry-After set) is thrown and rendered by the error presenter.
To answer otherwise from an attribute, point onExceeded to a presenter method:
#[RateLimit('login', onExceeded: 'loginLimited')] public function handleLogin(): void { /* ... */ } public function loginLimited(TooManyRequestsException $exception): void { $this->flashMessage(sprintf('Retry in %d s.', $exception->getRetryAfter()), 'error'); if ($this->isAjax()) { $this->redrawControl('flashes'); $this->sendTemplate(); } $this->redirect('this'); }
- It runs at presenter startup, before the action, the signal and
beforeRender(). - It must end the request; if it returns, the 429 is thrown anyway.
- Keep it public or protected; a missing method fails on the first request.
With enforce(), catch the exception around the call.
Storage and lock
| Option | Default | Otherwise |
|---|---|---|
storage |
apcu, files in %tempDir% where APCu is inactive: one machine |
@service: a Symfony StorageInterface or a PSR-6 pool |
lock |
semaphore (files in %tempDir% without ext-sysvsem): one machine |
@service: a Symfony LockFactory; false: none |
Several instances need a shared storage and a shared lock, e.g. with symfony/cache and Redis:
services: rateLimiterPool: Symfony\Component\Cache\Adapter\RedisAdapter(@redis) rateLimiterLock: Symfony\Component\Lock\LockFactory(Symfony\Component\Lock\Store\RedisStore(@redis)) rateLimiter: storage: @rateLimiterPool lock: @rateLimiterLock
The Tracy panel shows which storage counts, APCu or its file fallback.
If the storage or the lock throws, the request goes through and the exception is logged.
Tracy panel
With debugger: true (default %debugMode%): limiters hit by the request, their state, the backends in use.
Development
composer ci # rector, ecs, phpstan, tests (APCu tests need apc.enable_cli=1) composer complete # + mutation testing