An implementation of the Leaky Bucket algorithm.

0.1.5 2017-05-03 10:21 UTC

This package is not auto-updated.

Last update: 2024-05-11 14:37:16 UTC


Leaky Bucket is an algorithm which works as follows:

  1. There is a bucket.
  2. The bucket has a defined leak and defined capacity.
  3. The bucket leaks at a constant rate.
  4. Overflows when full, will not add other drops to the bucket.


Basic usage


use LeakyBucket\LeakyBucket;
use LeakyBucket\Storage\RedisStorage;

// Define which storage to use
$storage = new RedisStorage();

// Define the bucket
$settings = [
    'capacity' => 10,
    'leak'     => 1

// Create the bucket
$bucket = new LeakyBucket('example-bucket', $storage, $settings);

// Fill the bucket

// Check if it's full
if ($bucket->isFull()) {
    header('HTTP/1.1 429 Too Many Requests');
    exit '<!doctype html><html><body><h1>429 Too Many Requests</h1><p>You seem to be doing a lot of requests. You\'re now cooling down.</p></body></html>';

// ...

Other functionality

You can also do great stuff with it through the methods that LeakyBucket provides.

// Get capacity information
$capacityTotal = $bucket->getCapacity();
$capacityLeft  = $bucket->getCapacityLeft();
$capacityUsed  = $bucket->getCapacityUsed();

// Get the drops/second that the bucket leaks
$leakPerSecond = $bucket->getLeak();

// Get the last timestamp from when the bucket was updated
$timestamp = $bucket->getLastTimestamp();

// Set additional data
        'timeout' => 3600

// Get additional data
$data = $bucket->getData();

// Update the bucket with the leaked drops

// Remove excess drops

// Update the bucket's timestamp manually

// Fill the bucket with one drop

// Fill the bucket with 5 drops

// Spill one drop from the bucket

// Spill 5 drops from the bucket

// Remove the bucket's content

// Force save


You can contribute by forking the repo and creating pull requests. You can also create issues or feature requests.


  1. Your code complies with the PSR-2 standards. (check using the php-cs-checker)
  2. Your code is fully tested and PHPUnit tests are also supplied.
  3. Your code passes in TravisCI build.
  4. By contributing your code, you agree to license your contribution under the MIT license.

Boring legal stuff

This project is licensed under the MIT license. LICENSE file can be found in this repository.