razonyang/token-bucket

PHP Token Bucket

1.0.0 2019-08-21 05:02 UTC

This package is auto-updated.

Last update: 2024-11-21 21:05:19 UTC


README

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

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: