PHPackages                             bayfrontmedia/leaky-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. bayfrontmedia/leaky-bucket

ActiveLibrary

bayfrontmedia/leaky-bucket
==========================

Framework-agnostic throttling using the leaky bucket algorithm.

v2.3.0(2mo ago)0794↓100%11MITPHPPHP ^8.0

Since Sep 12Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/bayfrontmedia/leaky-bucket)[ Packagist](https://packagist.org/packages/bayfrontmedia/leaky-bucket)[ Docs](https://github.com/bayfrontmedia/leaky-bucket)[ RSS](/packages/bayfrontmedia-leaky-bucket/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (2)Versions (12)Used By (1)

Leaky Bucket
------------

[](#leaky-bucket)

Framework-agnostic throttling using the leaky bucket algorithm.

A bucket has a defined capacity and leak rate per minute. Buckets can also store additional arbitrary data.

- [License](#license)
- [Author](#author)
- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)

License
-------

[](#license)

This project is open source and available under the [MIT License](LICENSE).

Author
------

[](#author)

[![Bayfront Media](https://camo.githubusercontent.com/0c0163913b2092e97dbf9684970adaf86f2f25871298d3d28b2dff4bf75b2915/68747470733a2f2f63646e312e6f6e62617966726f6e742e636f6d2f62666d2f6272616e642f62666d2d6c6f676f2e737667)](https://camo.githubusercontent.com/0c0163913b2092e97dbf9684970adaf86f2f25871298d3d28b2dff4bf75b2915/68747470733a2f2f63646e312e6f6e62617966726f6e742e636f6d2f62666d2f6272616e642f62666d2d6c6f676f2e737667)

- [Bayfront Media homepage](https://www.bayfrontmedia.com?utm_source=github&utm_medium=direct)
- [Bayfront Media GitHub](https://github.com/bayfrontmedia)

Requirements
------------

[](#requirements)

- PHP `^8.0` (Tested up to `8.4`)
- PDO PHP extension
- JSON PHP extension

### Suggested

[](#suggested)

- Redis PHP extension

Installation
------------

[](#installation)

```
composer require bayfrontmedia/leaky-bucket
```

Usage
-----

[](#usage)

### Storage adapter

[](#storage-adapter)

A `Bayfront\LeakyBucket\ApadpterInterface` must be passed to the `Bayfront\LeakyBucket\Bucket` constructor. There are a variety of storage adapters available, each with their own required configuration.

**Flysystem**

The `Flysystem` adapter allows you to use a [Flysystem](https://github.com/thephpleague/flysystem) `League\Flysystem\Filesystem` v3 instance for bucket storage.

```
use Bayfront\LeakyBucket\Adapters\Flysystem;

$adapter = new Flysystem($filesystem, '/root_path');
```

**Local**

The `Local` adapter allows you to store buckets locally using native PHP.

```
use Bayfront\LeakyBucket\Adapters\Local;

$adapter = new Local('/root_path');
```

**PDO**

The `PDO` adapter allows you to use a `\PDO` instance for bucket storage into a database.

The `PDO` adapter will create/use a table named "buckets" unless otherwise specified in the constructor.

```
use Bayfront\LeakyBucket\Adapters\PDO;

$adapter = new PDO($dbh, 'table_to_use');
```

Use the `up` method to create the necessary database table to be used by this adapter. Use the `down` method to remove the database table.

These methods throw a `Bayfront\LeakyBucket\AdapterException` exception.

```
try {

    $adapter->up();

} catch (AdapterException $e) {
    die($e->getMessage());
}
```

**Redis**

The `Redis` adapter allows you to use a `\Redis` instance for bucket storage. The Redis PHP extension must be installed.

```
use Bayfront\LeakyBucket\Adapters\Redis;

$redis = new Redis();

try {
    $redis->pconnect('10.0.0.1', 6379, 2, 'cache');
} catch (RedisException $e) {
    $redis->connect('10.0.0.1', 6379, 2);
}

$redis->auth([
    'USERNAME',
    'PASSWORD'
]);

$adapter = new \Bayfront\LeakyBucket\Adapters\Redis($redis, 'bucket:prefix:', 3600);
```

The second argument allows a prefix to be defined for all bucket keys. The third argument allows a TTL to be defined (in seconds) for all buckets

A good TTL value can be calculated based on the bucket's capacity and leak rate. For example, if the capacity is 10 and the leak rate is 10 (drops per minute), the longest possible duration of a valid bucket is 1 minute. Therefore, a TTL of 60 seconds will ensure the bucket is automatically deleted once it has reached the longest possible measured duration.

The TTL is reset each time the bucket is saved.

### Start using Leaky Bucket

[](#start-using-leaky-bucket)

Once your adapter has been created, it can be used with Leaky Bucket. In addition, an optional settings array can be passed to the constructor. The default settings are shown below.

```
use Bayfront\LeakyBucket\AdapterException;
use Bayfront\LeakyBucket\BucketException;
use Bayfront\LeakyBucket\Bucket;

// Create/retrieve a bucket with a given ID

try {

    $bucket = new Bucket('bucket_id', $adapter, [
        'capacity' => 10, // Total drop capacity
        'leak' => 10 // Number of drops to leak per minute
    ]);

} catch (AdapterException | BucketException $e) {
    die($e->getMessage());
}

// Work with the bucket

$bucket->leak();

if ($bucket->hasCapacity()) {

    try {

        $bucket->fill()->save();

    } catch (AdapterException $e) {
        die($e->getMessage());
    }

}
```

**NOTE:**Be sure to `leak()` the bucket before attempting to do any calculations regarding its capacity. Also, the `save()` method must be used to store the current bucket settings for future use.

### Public methods

[](#public-methods)

- [exists](#exists)
- [save](#save)
- [get](#get)
- [reset](#reset)
- [delete](#delete)
- [isFull](#isfull)
- [getCapacity](#getcapacity)
- [getCapacityUsed](#getcapacityused)
- [getCapacityRemaining](#getcapacityremaining)
- [hasCapacity](#hascapacity)
- [getLeakPerSecond](#getleakpersecond)
- [getSecondsPerDrop](#getsecondsperdrop)
- [getSecondsUntilCapacity](#getsecondsuntilcapacity)
- [getSecondsUntilEmpty](#getsecondsuntilempty)
- [touch](#touch)
- [getLastTime](#getlasttime)
- [fill](#fill)
- [leak](#leak)
- [spill](#spill)
- [overflow](#overflow)
- [dump](#dump)
- [hasData](#hasdata)
- [setData](#setdata)
- [getData](#getdata)
- [forgetData](#forgetdata)

---

### exists

[](#exists)

**Description:**

Checks if this bucket ID already exists in storage.

**Parameters:**

- None

**Returns:**

- (bool)

**Example:**

```
if ($bucket->exists()) {
    // Do something
}
```

---

### save

[](#save)

**Description:**

Saves the bucket.

**Parameters:**

- None

**Returns:**

- (self)

**Throws:**

`Bayfront\LeakyBucket\AdapterException`

**Example:**

```
try {

    $bucket->save();

} catch (AdapterException $e) {
    die($e->getMessage());
}
```

---

### get

[](#get)

**Description:**

Returns entire bucket contents.

**Parameters:**

- None

**Returns:**

- (array)

**Example:**

```
$contents = $bucket->get();
```

---

### reset

[](#reset)

**Description:**

Reset all bucket information and data.

**Parameters:**

- None

**Returns:**

- (self)

**Example:**

```
$bucket->reset();
```

---

### delete

[](#delete)

**Description:**

Resets bucket and deletes the file in storage.

**Parameters:**

- None

**Returns:**

- (self)

**Throws:**

`Bayfront\LeakyBucket\AdapterException`

**Example:**

```
try {

    $bucket->delete();

} catch (AdapterException $e) {
    die($e->getMessage());
}
```

---

### isFull

[](#isfull)

**Description:**

Checks if bucket is full.

**Parameters:**

- None

**Returns:**

- (bool)

**Example:**

```
if ($bucket->isFull()) {
    // Do something
}
```

---

### getCapacity

[](#getcapacity)

**Description:**

Returns the total bucket capacity.

**Parameters:**

- None

**Returns:**

- (int)

**Example:**

```
echo $bucket->getCapacity();
```

---

### getCapacityUsed

[](#getcapacityused)

**Description:**

Returns the number of drops in the bucket.

**Parameters:**

- None

**Returns:**

- (float)

**Example:**

```
echo $bucket->getCapacityUsed();
```

---

### getCapacityRemaining

[](#getcapacityremaining)

**Description:**

Returns the remaining bucket capacity.

**Parameters:**

- None

**Returns:**

- (float)

**Example:**

```
echo $bucket->getCapacityRemaining();
```

---

### hasCapacity

[](#hascapacity)

**Description:**

Checks if bucket has the capacity fo fill by a given number of drops.

**Parameters:**

- `$drops = 1` (int)

**Returns:**

- (bool)

**Example:**

```
if ($bucket->hasCapacity(5)) {
    // Do something
}
```

---

### getLeakPerSecond

[](#getleakpersecond)

**Description:**

Returns the number of drops per second the bucket will leak.

**Parameters:**

- None

**Returns:**

- (float)

**Example:**

```
echo $bucket->getLeakPerSecond();
```

---

### getSecondsPerDrop

[](#getsecondsperdrop)

**Description:**

Returns the number of seconds required to leak one drop.

**Parameters:**

- None

**Returns:**

- (float)

**Example:**

```
echo $bucket->getSecondsPerDrop();
```

---

### getSecondsUntilCapacity

[](#getsecondsuntilcapacity)

**Description:**

Returns the number of seconds until bucket has capacity for number of drops. Returns `0` if bucket has capacity.

**Parameters:**

- `$drops = 1` (int)

**Returns:**

- (float)

**Example:**

```
echo $bucket->getSecondsPerDrop();
```

---

### getSecondsUntilEmpty

[](#getsecondsuntilempty)

**Description:**

Returns the number of seconds until bucket would be empty.

**Parameters:**

- None

**Returns:**

- (float)

**Example:**

```
echo $bucket->getSecondsUntilEmpty();
```

---

### touch

[](#touch)

**Description:**

Manually update the bucket's timestamp.

The bucket's timestamp is automatically updated when any of the following methods are called:

- [fill](#fill)
- [leak](#leak)
- [spill](#spill)
- [dump](#dump)

**Parameters:**

- None

**Returns:**

- (self)

**Example:**

```
$bucket->touch();
```

---

### getLastTime

[](#getlasttime)

**Description:**

Returns the bucket's last timestamp.

**Parameters:**

- None

**Returns:**

- (int)

**Example:**

```
echo $bucket->getLastTime();
```

---

### fill

[](#fill)

**Description:**

Fills the bucket with a given number of drops.

If not allowed to overflow, and the bucket does not have the required capacity, a `Bayfront\LeakyBucket\BucketException` will be thrown. Otherwise, the bucket will be allowed to overflow.

**Parameters:**

- `$drops = 1` (int)
- `$allow_overflow = false` (bool)

**Returns:**

- (self)

**Throws:**

- `Bayfront\LeakyBucket\BucketException`

**Example:**

```
try {

    $bucket->fill();

} catch (BucketException $e) {
    die($e->getMessage());
}
```

---

### leak

[](#leak)

**Description:**

Updates the bucket by calculating how many drops to leak since it's last timestamp.

**Parameters:**

- None

**Returns:**

- (self)

**Example:**

```
$bucket->leak();
```

---

### spill

[](#spill)

**Description:**

Spills a given number of drops from the bucket.

**Parameters:**

- `$drops = 1` (int)

**Returns:**

- (self)

**Example:**

```
$bucket->spill(5);
```

---

### overflow

[](#overflow)

**Description:**

Dumps (empties) all drops from the bucket in excess of its capacity.

**Parameters:**

- None

**Returns:**

- (self)

**Example:**

```
$bucket->overflow();
```

---

### dump

[](#dump)

**Description:**

Dumps (empties) all drops from the bucket.

**Parameters:**

- None

**Returns:**

- (self)

**Example:**

```
$bucket->dump();
```

---

### hasData

[](#hasdata)

**Description:**

Checks if this bucket contains any additional data, or a specific key in dot notation.

**Parameters:**

- `$key = NULL` (string|null): If `NULL`, checks if any additional data exists

**Returns:**

- (bool)

**Example:**

```
if ($bucket->hasData('client_id')) {
    // Do something
}
```

---

### setData

[](#setdata)

**Description:**

Sets additional data for this bucket in dot notation.

**Parameters:**

- `$key` (string)
- `$value` (mixed)

**Returns:**

- (self)

**Example:**

```
$bucket->setData('client_id', 5);
```

---

### getData

[](#getdata)

**Description:**

Returns this bucket's additional data key in dot notation, or an optional default value if not found.

**Parameters:**

- `$key = NULL` (string|null): Returns the entire data array when `NULL`
- `$default = NULL` (mixed)

**Returns:**

- (mixed)

**Example:**

```
$client_id = $bucket->getData('client_id');
```

---

### forgetData

[](#forgetdata)

**Description:**

Removes additional data key in dot notation for this bucket.

**Parameters:**

- `$key = NULL` (string|null): Removes the entire data array when `NULL`

**Returns:**

- (self)

**Example:**

```
$bucket->forgetData('client_id');
```

###  Health Score

47

—

FairBetter than 94% of packages

Maintenance86

Actively maintained with recent releases

Popularity15

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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

Every ~194 days

Recently: every ~247 days

Total

11

Last Release

70d ago

Major Versions

v1.2.1 → v2.0.02023-01-27

PHP version history (2 changes)1.0.0PHP &gt;=7.1.0

v2.0.0PHP ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/5ad62c8d0e69358fd63b16fdaa71d5359231cd0cf660bbc3419071dc705c63a8?d=identicon)[bayfrontmedia](/maintainers/bayfrontmedia)

---

Top Contributors

[![robinsonjohn](https://avatars.githubusercontent.com/u/24327848?v=4)](https://github.com/robinsonjohn "robinsonjohn (23 commits)")

---

Tags

leaky-bucketphprate-limitthrottlephprate limitthrottleleaky bucket

### Embed Badge

![Health badge](/badges/bayfrontmedia-leaky-bucket/health.svg)

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

###  Alternatives

[graham-campbell/throttle

Throttle Is A Rate Limiter For Laravel

7112.3M10](/packages/graham-campbell-throttle)[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

2537.5M9](/packages/davedevelopment-stiphle)[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

53511.9k1](/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

45584.2k2](/packages/maba-gentle-force)[sunspikes/php-ratelimiter

A framework agnostic rate limiter for PHP

76667.7k1](/packages/sunspikes-php-ratelimiter)

PHPackages © 2026

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