fustundag / tokenbucket
PHP TokenBucket implementation for rate limit
Installs: 458 685
Dependents: 0
Suggesters: 0
Security: 0
Stars: 6
Watchers: 1
Forks: 3
Open Issues: 1
Requires
- php: >=5.6.0
- ext-memcached: *
Requires (Dev)
- phpmd/phpmd: 2.4.*@stable
- phpunit/dbunit: 2.0.*@stable
- phpunit/php-code-coverage: 4.0.*@stable
- phpunit/phpunit: 5.5.*@stable
- squizlabs/php_codesniffer: 2.*@stable
This package is auto-updated.
Last update: 2024-11-12 03:46:42 UTC
README
TokenBucket is an algorithm for rate limit
You can check algorithm from http://en.wikipedia.org/wiki/Token_bucket
Usage
Basic usage
<?php use TokenBucket\TokenBucket; use TokenBucket\Storage\Memcached as MemcachedStorage; $storage = new MemcachedStorage(); // Define the bucket $options = array( 'capacity' => 20, 'fillRate' => 5 ); // Create the bucket $bucket = new TokenBucket('key-for-bucket', $storage, $options); // Check if token is avaible if ($bucket->consume()===false) { //Not allowed!! exit; } // ...
Options
capacity : Max token count of bucket.
fillRate : Token count to fill per second. For example if capacity is 20 and fillRate is 5, 5 tokens will added to bucket every second. But, total token cannot be exceed 20.
ttl : Time to live for bucket in seconds. If not given or zero given, it will be calculated automatically according to capacity and fillRate. ttl can be used to reset bucket with capacity. For example: if capacity is 100 and fillRate is zero and ttl is 300, 100 token can be consumed at 300 seconds. After 300 seconds, bucket will be reset to capacity.
Rate Limit Http Headers
You can get http headers for rate limit with getRateLimitHttpHeaders method:
X-RateLimit-Limit : gives capacity of bucket
X-RateLimit-Remaining : allowed token count of bucket
X-RateLimit-Reset : time to live of bucket
Contributing
You can contribute by forking the repo and creating pull requests. You can also create issues or feature requests.
License
This project is licensed under the MIT license. LICENSE
file can be found in this repository.