PHP Token Bucket

PHP Token Bucket

Build Status
Scrutinizer Code Quality
Code Coverage
Latest Stable Version
Total Downloads

It is an implementation of Token Bucket algorithm that for HTTP rate limiter.


$ composer require razonyang/token-bucket


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


It was inspired from the follow documents and code:


电子邮件地址不会被公开。 必填项已用*标注