razonyang / token-bucket
PHP Token Bucket
Installs: 18 885
Dependents: 2
Suggesters: 0
Security: 0
Stars: 6
Watchers: 3
Forks: 1
Open Issues: 0
Requires
- php: ^7.1
- psr/log: ^1.1
Requires (Dev)
- phpunit/phpunit: ^7
Suggests
- ext-memcached: MemcachedManager require memcached extension
- ext-redis: RedisManager require redis extension
This package is auto-updated.
Last update: 2024-12-21 21:26:03 UTC
README
It is an implementation of Token Bucket algorithm that for HTTP rate limiter.
Installation
$ composer require razonyang/token-bucket
Integration
You can also build your own, let's take 5000 requests per hours as example:
// create a token bucket manager $capacity = 5000; // each bucket capacity, in other words, maximum number of tokens. $rate = 0.72; // 3600/5200, how offen the token will be added to bucket $logger = new \Psr\Log\NullLogger(); // PSR logger $ttl = 3600; // time to live. $prefix = 'rateLimiter:'; // prefix. $manager = new \RazonYang\TokenBucket\Manager\RedisManager($capacity, $rate, $logger, $redis, $ttl, $prefix); // implements rate limiter, comsumes a token from the bucket which called $name. $name = 'uid:route'; // the name of bucket. $comsumed = $manager->consume($name, $remaining, $reset); // set header header('X-Rate-Limit-Limit: ' . $manager->getLimit()); header('X-Rate-Limit-Remaining: ' . $remaining); // remaining number of tokens. header('X-Rate-Limit-Reset: ' . $reset); if (!$comsumed) { throw new \Exception('Too many requests', 429); } // continue handling
Credit
It was inspired from the follow documents and code: