nikolaposa / rate-limit
General purpose rate limiter implementation.
Installs: 1 042 752
Dependents: 4
Suggesters: 1
Security: 0
Stars: 270
Watchers: 13
Forks: 47
Open Issues: 6
Requires
- php: ^8.1
- beberlei/assert: ^3.2
Requires (Dev)
- ext-apcu: >=5.1.12
- ext-redis: *
- friendsofphp/php-cs-fixer: 3.44
- phpstan/phpstan: ^1.10
- phpstan/phpstan-beberlei-assert: ^1.1
- phpstan/phpstan-phpunit: ^1.3
- phpunit/phpunit: ^10.5
- predis/predis: ^1.1
Suggests
- ext-apcu: In order to use ApcuRateLimiter
- ext-memcached: In order to use MemcachedRateLimiter
- ext-redis: In order to use RedisRateLimiter
- predis/predis: In order to use PredisRateLimiter
This package is auto-updated.
Last update: 2024-11-04 10:42:00 UTC
README
General purpose rate limiter that can be used to limit the rate at which certain operation can be performed. Default implementation uses Redis as backend.
Installation
The preferred method of installation is via Composer. Run the following
command to install the latest version of a package and add it to your project's composer.json
:
composer require nikolaposa/rate-limit
Usage
Terminating rate limiter
use RateLimit\Exception\LimitExceeded; use RateLimit\Rate; use RateLimit\RedisRateLimiter; use Redis; $rateLimiter = new RedisRateLimiter(Rate::perMinute(100), new Redis()); $apiKey = 'abc123'; try { $rateLimiter->limit($apiKey); //on success } catch (LimitExceeded $exception) { //on limit exceeded }
Silent rate limiter
use RateLimit\Rate; use RateLimit\RedisRateLimiter; use Redis; $rateLimiter = new RedisRateLimiter(Rate::perMinute(100), new Redis()); $ipAddress = '192.168.1.2'; $status = $rateLimiter->limitSilently($ipAddress); echo $status->getRemainingAttempts(); //99
Practical usage with configuring multiple rate limiting strategies in a project
use RateLimit\Rate; use RateLimit\RedisRateLimiter; $container->set('rate_limiter.api', new RedisRateLimiter(Rate::perSecond(10), $container->get('redis'))); $container->set('rate_limiter.videos', new RedisRateLimiter(Rate::perDay(5), $container->get('redis')));
Supported drivers
Credits
License
Released under MIT License - see the License File for details.