PHP PSR Rate Limiter Middleware

PSR Rate Limiter Middleware

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

It was built on top of Token Bucket.


composer require razonyang/psr-rate-limiter


Let's take 5000 requests every hours as example:

// creates a token bucket manager, redis or memcached(built-in)
$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);

// PSR HTTP response factory
$responseFactory = new \Nyholm\Psr7\Factory\Psr17Factory();

// bucket name callback, let's we treat ip:path as bucket name here
$nameCallback = function (\Psr\Http\Message\ServerRequestInterface $request): string {
    $parameters = $request->getServerParams();
    $path = '';
    foreach ($ipKeys as $key) {
        if (!empty($parameters[$key])) {
            return $parameters[$key] . ':' . $request->getUri()->getPath();

    // rate limiting will be skipped when an empty bucket name returned
    return '';

$rateLimiter = new \RazonYang\Psr\RateLimiter\Middleware($manager, $responseFactory, $nameCallback);


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