PHPackages                             marianperca/token-bucket - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. marianperca/token-bucket

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

marianperca/token-bucket
========================

Implementation of the Token Bucket algorithm.

v2.0.2(2y ago)0129WTFPLPHPPHP &gt;=5.6

Since Aug 24Pushed 2y agoCompare

[ Source](https://github.com/marianperca/token-bucket)[ Packagist](https://packagist.org/packages/marianperca/token-bucket)[ Docs](https://github.com/marianperca/token-bucket)[ RSS](/packages/marianperca-token-bucket/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (5)Versions (3)Used By (0)

Token Bucket
============

[](#token-bucket)

This is a threadsafe implementation of the [Token Bucket algorithm](https://en.wikipedia.org/wiki/Token_bucket)in PHP. You can use a token bucket to limit an usage rate for a resource (e.g. a stream bandwidth or an API usage).

The token bucket is an abstract metaphor which doesn't have a direction of the resource consumption. I.e. you can limit a rate for consuming or producing. E.g. you can limit the consumption rate of a third party API service, or you can limit the usage rate of your own API service.

Installation
============

[](#installation)

Use [Composer](https://getcomposer.org/):

```
composer require bandwidth-throttle/token-bucket
```

Usage
=====

[](#usage)

The package is in the namespace [`bandwidthThrottle\tokenBucket`](http://bandwidth-throttle.github.io/token-bucket/api/namespace-bandwidthThrottle.tokenBucket.html).

Example
-------

[](#example)

This example will limit the rate of a global resource to 10 requests per second for all requests.

```
use bandwidthThrottle\tokenBucket\Rate;
use bandwidthThrottle\tokenBucket\TokenBucket;
use bandwidthThrottle\tokenBucket\storage\FileStorage;

$storage = new FileStorage(__DIR__ . "/api.bucket");
$rate    = new Rate(10, Rate::SECOND);
$bucket  = new TokenBucket(10, $rate, $storage);
$bucket->bootstrap(10);

if (!$bucket->consume(1, $seconds)) {
    http_response_code(429);
    header(sprintf("Retry-After: %d", floor($seconds)));
    exit();
}

echo "API response";
```

Note: In this example `TokenBucket::bootstrap()` is part of the code. This is not recommended for production, as this is producing unnecessary storage communication. `TokenBucket::bootstrap()` should be part of the application's bootstrap or deploy process.

Scope of the storage
--------------------

[](#scope-of-the-storage)

First you need to decide the scope of your resource. I.e. do you want to limit it per request, per user or amongst all requests? You can do this by choosing a [`Storage`](http://bandwidth-throttle.github.io/token-bucket/api/class-bandwidthThrottle.tokenBucket.storage.Storage.html)implementation of the desired scope:

- The [`RequestScope`](http://bandwidth-throttle.github.io/token-bucket/api/class-bandwidthThrottle.tokenBucket.storage.scope.RequestScope.html)limits the rate only within one request. E.g. to limit the bandwidth of a download. Each requests will have the same bandwidth limit.
- The [`SessionScope`](http://bandwidth-throttle.github.io/token-bucket/api/class-bandwidthThrottle.tokenBucket.storage.scope.SessionScope.html)limits the rate of a resource within a session. The rate is controlled over all requests of one session. E.g. to limit the API usage per user.
- The [`GlobalScope`](http://bandwidth-throttle.github.io/token-bucket/api/class-bandwidthThrottle.tokenBucket.storage.scope.GlobalScope.html)limits the rate of a resource for all processes (i.e. requests). E.g. to limit the aggregated download bandwidth of a resource over all processes. This scope permits race conditions between processes. The TokenBucket is therefore synchronized on a shared mutex.

TokenBucket
-----------

[](#tokenbucket)

When you have your storage you can finally instantiate a [`TokenBucket`](http://bandwidth-throttle.github.io/token-bucket/api/class-bandwidthThrottle.tokenBucket.TokenBucket.html). The first parameter is the capacity of the bucket. I.e. there will be never more tokens available. This also means that consuming more tokens than the capacity is invalid.

The second parameter is the token-add-[`Rate`](http://bandwidth-throttle.github.io/token-bucket/api/class-bandwidthThrottle.tokenBucket.Rate.html). It determines the speed for filling the bucket with tokens. The rate is the amount of tokens added per unit, e.g. `new Rate(100, Rate::SECOND)`would add 100 tokens per second.

The third parameter is the storage, which is used to persist the token amount of the bucket. The storage does determine the scope of the bucket.

### Bootstrapping

[](#bootstrapping)

A token bucket needs to be bootstrapped. While the method [`TokenBucket::bootstrap()`](http://bandwidth-throttle.github.io/token-bucket/api/class-bandwidthThrottle.tokenBucket.TokenBucket.html#_bootstrap)doesn't have any side effects on an already bootstrapped bucket, it is not recommended do call it for every request. Better include that in your application's bootstrap or deploy process.

### Consuming

[](#consuming)

Now that you have a bootstrapped bucket, you can start consuming tokens. The method [`TokenBucket::consume()`](http://bandwidth-throttle.github.io/token-bucket/api/class-bandwidthThrottle.tokenBucket.TokenBucket.html#_consume)will either return `true` if the tokens were consumed or `false` else. If the tokens were consumed your application can continue to serve the resource.

Else if the tokens were not consumed you should not serve the resource. In that case `consume()` did write a duration of seconds into its second parameter (which was passed by reference). This is the duration until sufficient tokens would be available.

BlockingConsumer
----------------

[](#blockingconsumer)

In the first example we did either serve the request or fail with the HTTP status code 429. This is actually a very resource efficient way of throtteling API requests as it doesn't reserve resources on your server.

However sometimes it is desirable not to fail but instead wait a little bit and then continue serving the requests. You can do this by consuming the token bucket with a [`BlockingConsumer`](http://bandwidth-throttle.github.io/token-bucket/api/class-bandwidthThrottle.tokenBucket.BlockingConsumer.html).

```
use bandwidthThrottle\tokenBucket\Rate;
use bandwidthThrottle\tokenBucket\TokenBucket;
use bandwidthThrottle\tokenBucket\BlockingConsumer;
use bandwidthThrottle\tokenBucket\storage\FileStorage;

$storage  = new FileStorage(__DIR__ . "/api.bucket");
$rate     = new Rate(10, Rate::SECOND);
$bucket   = new TokenBucket(10, $rate, $storage);
$consumer = new BlockingConsumer($bucket);
$bucket->bootstrap(10);

// This will block until one token is available.
$consumer->consume(1);

echo "API response";
```

This will effectively limit the rate to 10 requests per seconds as well. But in this case the client has not to bother with the 429 error. Instead the connection is just delayed to the desired rate.

License and authors
===================

[](#license-and-authors)

This project is free and under the WTFPL. This project is forked from Markus Malkusch . [Here is the original repo](https://github.com/bandwidth-throttle/token-bucket)

###  Health Score

22

—

LowBetter than 23% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 Bus Factor1

Top contributor holds 92.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

989d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/67f8cf48a101d25f308fda73747b75bdbc179ac37ab6a3ea8d3747a3be36a29a?d=identicon)[marianperca](/maintainers/marianperca)

---

Top Contributors

[![malkusch](https://avatars.githubusercontent.com/u/1623984?v=4)](https://github.com/malkusch "malkusch (89 commits)")[![marianperca](https://avatars.githubusercontent.com/u/673596?v=4)](https://github.com/marianperca "marianperca (3 commits)")[![austinpray](https://avatars.githubusercontent.com/u/2192970?v=4)](https://github.com/austinpray "austinpray (1 commits)")[![deefour](https://avatars.githubusercontent.com/u/14762?v=4)](https://github.com/deefour "deefour (1 commits)")[![drsect0r](https://avatars.githubusercontent.com/u/9106228?v=4)](https://github.com/drsect0r "drsect0r (1 commits)")[![lloy0076](https://avatars.githubusercontent.com/u/1174532?v=4)](https://github.com/lloy0076 "lloy0076 (1 commits)")

---

Tags

rate limitthrottlethrottlingrate limitingbandwidthtoken bucket

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/marianperca-token-bucket/health.svg)

```
[![Health](https://phpackages.com/badges/marianperca-token-bucket/health.svg)](https://phpackages.com/packages/marianperca-token-bucket)
```

###  Alternatives

[bandwidth-throttle/token-bucket

Implementation of the Token Bucket algorithm.

5121.9M10](/packages/bandwidth-throttle-token-bucket)[davedevelopment/stiphle

Simple rate limiting/throttling for php

2567.7M9](/packages/davedevelopment-stiphle)[sunspikes/php-ratelimiter

A framework agnostic rate limiter for PHP

76674.1k1](/packages/sunspikes-php-ratelimiter)[graham-campbell/throttle

Throttle Is A Rate Limiter For Laravel

7102.3M11](/packages/graham-campbell-throttle)[maba/gentle-force-bundle

Symfony bundle that integrates gentle-force library for limiting both brute-force attempts and ordinary requests, using leaky/token bucket algorithm, based on Redis

53517.6k1](/packages/maba-gentle-force-bundle)[maba/gentle-force

Library for limiting both brute-force attempts and ordinary requests, using leaky/token bucket algorithm, based on Redis

45591.0k2](/packages/maba-gentle-force)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
