PHPackages                             eforce/throttle - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. eforce/throttle

ActiveCakephp-plugin[HTTP &amp; Networking](/categories/http)

eforce/throttle
===============

(API) Rate limiting requests in CakePHP

1.0(2y ago)05MITPHP

Since Sep 14Pushed 2y ago1 watchersCompare

[ Source](https://github.com/kamleshethos/throttle)[ Packagist](https://packagist.org/packages/eforce/throttle)[ Docs](https://github.com/kamleshethos/throttle)[ RSS](/packages/eforce-throttle/feed)WikiDiscussions main Synced 1mo ago

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

Throttle
========

[](#throttle)

[![Build Status](https://camo.githubusercontent.com/923ed48dca28e7bdac94c60ff987d4f72810dba2a0405af037134aeb70f18b6f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f5573654d756666696e2f5468726f74746c652f43492f6d61737465723f7374796c653d666c61742d737175617265)](https://github.com/UseMuffin/Throttle/actions?query=workflow%3ACI+branch%3Amaster)[![Coverage Status](https://camo.githubusercontent.com/cb947cbb2644676605ddab717fe916e379cbeaea6828e31e389e8ea4f87770df/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f5573654d756666696e2f5468726f74746c652e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/github/UseMuffin/Throttle)[![Total Downloads](https://camo.githubusercontent.com/d7e2ba1ef1286c8c0548a385f01974950556ac9e9f30baf07a639e8ae1e346c6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d756666696e2f7468726f74746c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/muffin/throttle)[![License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](LICENSE)

(API) Rate limiting requests in CakePHP

This plugin allows you to limit the number of requests a client can make to your app in a given time frame.

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

[](#installation)

```
composer require muffin/throttle
```

To make your application load the plugin either run:

```
./bin/cake plugin load Muffin/Throttle
```

Configuration
-------------

[](#configuration)

In your `config/app.php` add a cache config named `throttle` under the `Cache` key with required config. For e.g.:

```
'throttle' => [
    'className' => 'Apcu',
    'prefix' => 'throttle_'
],
```

### Using the Middleware

[](#using-the-middleware)

Add the middleware to the queue and pass your custom configuration:

```
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
    // Various other middlewares for error handling, routing etc. added here.

    $throttleMiddleware = new \Muffin\Throttle\Middleware\ThrottleMiddleware([
        // Data used to generate response with HTTP code 429 when limit is exceeded.
        'response' => [
            'body' => 'Rate limit exceeded',
        ],
        // Time period as number of seconds
        'period' => 60,
        // Number of requests allowed within the above time period
        'limit' => 100,
        // Client identifier
        'identifier' => function ($request) {
            if (!empty($request->getHeaderLine('Authorization'))) {
                return str_replace('Bearer ', '', $request->getHeaderLine('Authorization'));
            }

            return $request->clientIp();
        }
    ]);

    $middlewareQueue->add($throttleMiddleware);

    return $middlewareQueue;
}
```

The above example would allow 100 requests/minute/token and would first try to identify the client by JWT Bearer token before falling back to (Throttle default) IP address based identification.

### Events

[](#events)

The middleware also dispatches following event which effectively allows you to have multiple rate limits:

#### `Throttle.beforeThrottle`

[](#throttlebeforethrottle)

This is the first event that is triggered before a request is processed by the middleware. All rate limiting process will be bypassed if this event is stopped.

```
\Cake\Event\EventManager::instance()->on(
    \Muffin\Throttle\Middleware\ThrottleMiddleware::EVENT_BEFORE_THROTTLE,
    function ($event, $request) {
        if (/* check for something here, most likely using $request */) {
            $event->stopPropogation();
        }
    }
);
```

#### `Throttle.getIdentifier`

[](#throttlegetidentifier)

Instead of using the `indentifer` config you can also setup a listener for the `Throttle.getIdentifier` event. The event's callback would receive a request instance as argument and must return an identifier string.

#### `Throttle.getThrottleInfo`

[](#throttlegetthrottleinfo)

The `Throttle.getThrottleInfo` event allows you to customize the `period` and `limit`configs for a request as well as the cache key used to store the rate limiting info.

This allows you to set multiple rate limit as per your app's needs.

Here's an example:

```
\Cake\Event\EventManager::instance()->on(
    \Muffin\Throttle\Middleware\ThrottleMiddleware::EVENT_GET_THROTTLE_INFO,
    function ($event, $request, \Muffin\Throttle\ValueObject\ThrottleInfo $throttle) {
        // Set a different period for POST request.
        if ($request->is('POST')) {
            // This will change the cache key from default "{identifer}" to "{identifer}.post".
            $throttle->appendToKey('post');
            $throttle->setPeriod(30);
        }

        // Modify limit for logged in user
        $identity = $request->getAttribute('identity');
        if ($identity) {
            $throttle->appendToKey($identity->get('role'));
            $throttle->setLimit(200);
        }
    }
);
```

#### Throtttle.beforeCacheSet

[](#throtttlebeforecacheset)

The `Throtttle.beforeCacheSet` event allows you to observe result of middleware configuration and previous `Throtttle.getIdentifier` and `Throttle.getThrottleInfo` events results.

You can also use this event to modify cached `$rateLimit` and `$ttl` values, modifying `$throttleInfo` in this event has no effect.

Example:

```
\Cake\Event\EventManager::instance()->on(
    \Muffin\Throttle\Middleware\ThrottleMiddleware::EVENT_BEFORE_CACHE_SET,
    function ($event, \Muffin\Throttle\ValueObject\RateLimitInfo $rateLimit, int $ttl, \Muffin\Throttle\ValueObject\ThrottleInfo $throttleInfo) {
        \Cake\Log\Log::debug(sprintf("key(%s) remaining(%d) resetTimestamp(%d) ttl(%d)", $throttleInfo->getKey(), $rateLimit->getRemaining(), $rateLimit->getResetTimestamp(), $ttl));
    }
);
```

### X-headers

[](#x-headers)

By default Throttle will add X-headers with rate limiting information to all responses:

```
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 7
X-RateLimit-Reset: 1438434161

```

To customize the header names simply pass (all of them) under `headers` key in your configuration array:

```
'headers' => [
    'limit' => 'X-MyRateLimit-Limit',
    'remaining' => 'X-MyRateLimit-Remaining',
    'reset' => 'X-MyRateLimit-Reset',
]
```

To disable the headers set `headers` key to `false`.

### Customize response object

[](#customize-response-object)

You may use `type` and `headers` subkeys of the `response` array (as you would do with a `Response` object) if you want to return a different message as the default one:

```
new \Muffin\Throttle\Middleware\ThrottleMiddleware([
    'response' => [
        'body' => json_encode(['error' => 'Rate limit exceeded']),
        'type' => 'json',
        'headers' => [
            'Custom-Header' => 'custom_value',
        ]
    ],
    'limit' => 300,
]);
```

Patches &amp; Features
----------------------

[](#patches--features)

- Fork
- Mod, fix
- Test - this is important, so it's not unintentionally broken
- Commit - do not mess with license, todo, version, etc. (if you do change any, bump them into commits of their own that I can ignore when I pull)
- Pull request - bonus point for topic branches

To ensure your PRs are considered for upstream, you MUST follow the CakePHP coding standards.

Bugs &amp; Feedback
-------------------

[](#bugs--feedback)

License
-------

[](#license)

Copyright (c) 2015-Present, \[Use Muffin\] and licensed under [The MIT License](http://www.opensource.org/licenses/mit-license.php).

###  Health Score

20

—

LowBetter than 14% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 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

Unknown

Total

1

Last Release

974d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6b683dccb1a1cad6f1008ab9596e6e2e03f7be58ca98d8878563d9063fe52b64?d=identicon)[kamleshethos](/maintainers/kamleshethos)

---

Top Contributors

[![kamleshethos](https://avatars.githubusercontent.com/u/15361242?v=4)](https://github.com/kamleshethos "kamleshethos (6 commits)")

---

Tags

cakephplimitRatemuffinthrottle

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/eforce-throttle/health.svg)

```
[![Health](https://phpackages.com/badges/eforce-throttle/health.svg)](https://phpackages.com/packages/eforce-throttle)
```

###  Alternatives

[muffin/throttle

(API) Rate limiting requests in CakePHP

62286.8k](/packages/muffin-throttle)[rtheunissen/guzzle-rate-limiter

Guzzle 6 middleware used to delay requests dynamically

52177.2k1](/packages/rtheunissen-guzzle-rate-limiter)[bandwidth-throttle/bandwidth-throttle

Bandwidth throttle at application layer

87139.3k](/packages/bandwidth-throttle-bandwidth-throttle)[mixerapi/mixerapi

Streamline development of API-first applications in CakePHP

4441.8k](/packages/mixerapi-mixerapi)[cakedc/cakephp-api

Api plugin for CakePHP

61100.6k](/packages/cakedc-cakephp-api)[andrej-griniuk/cakephp-fractal-transformer-view

CakePHP view builder utilizing Fractal library for entities transformation

1890.7k](/packages/andrej-griniuk-cakephp-fractal-transformer-view)

PHPackages © 2026

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