PHPackages                             nikolaposa/rate-limit-middleware - 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. nikolaposa/rate-limit-middleware

ActiveLibrary[HTTP &amp; Networking](/categories/http)

nikolaposa/rate-limit-middleware
================================

PSR-15 middleware for rate limiting API or other application endpoints.

2.0.0(4y ago)1312.0k↓44.8%MITPHPPHP ^7.4 || ^8.0

Since Mar 22Pushed 4y ago2 watchersCompare

[ Source](https://github.com/nikolaposa/rate-limit-middleware)[ Packagist](https://packagist.org/packages/nikolaposa/rate-limit-middleware)[ RSS](/packages/nikolaposa-rate-limit-middleware/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (9)Versions (4)Used By (0)

Rate Limit Middleware
=====================

[](#rate-limit-middleware)

[![Build Status](https://github.com/nikolaposa/rate-limit-middleware/workflows/Build/badge.svg?branch=master)](https://github.com/nikolaposa/rate-limit-middleware/actions)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/5da56aee10de07d4abf2da811760e823ca35e0f326b9f14dd6ed311cdd1f3b77/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e696b6f6c61706f73612f726174652d6c696d69742d6d6964646c65776172652f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/nikolaposa/rate-limit-middleware/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/9a8ae91562a5a8806b9ada549092802682d40d8ab58318d2aace563d12e90d52/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e696b6f6c61706f73612f726174652d6c696d69742d6d6964646c65776172652f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/nikolaposa/rate-limit-middleware/?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/12b566bc7ca67bd3aa4eb06a0f80fa245197de064f9a673b10139f4da8d152b0/68747470733a2f2f706f7365722e707567782e6f72672f6e696b6f6c61706f73612f726174652d6c696d69742d6d6964646c65776172652f762f737461626c65)](https://packagist.org/packages/nikolaposa/rate-limit-middleware)[![PDS Skeleton](https://camo.githubusercontent.com/a8ce1f2a7b71f101b18fc0393ba5bf89b7a5b1f9d08a31b658ca0eab0064c0f6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7064732d736b656c65746f6e2d626c75652e737667)](https://github.com/php-pds/skeleton)

PSR-15 middleware for rate limiting API or other application endpoints. Sits on top of general purpose [Rate Limiter](https://github.com/nikolaposa/rate-limit).

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

[](#installation)

The preferred method of installation is via [Composer](http://getcomposer.org/). Run the following command to install the latest version of a package and add it to your project's `composer.json`:

```
composer require nikolaposa/rate-limit-middleware
```

Usage
-----

[](#usage)

Rate Limit middleware is designed to be used per route, so that you can set up a rate limiting strategies for each individual endpoint or group of endpoints. This is accomplished through a mechanism for composing middleware known as *piping*.

### Full example

[](#full-example)

Following examples demonstrate how `RateLimitMiddleware` can be used in a [Mezzio](https://docs.mezzio.dev/mezzio/)-based application, but the same principle applies to any middleware framework.

**dependencies.php**

```
use Laminas\Diactoros\Response\JsonResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RateLimit\Middleware\RateLimitMiddleware;
use RateLimit\Middleware\ResolveIpAddressAsUserIdentity;
use RateLimit\Middleware\ResolveUserIdentity;
use RateLimit\Rate;
use RateLimit\RateLimiter;
use RateLimit\RedisRateLimiter;

return [
    'dependencies' => [
        'invokables' => [
            ResolveUserIdentity::class => ResolveIpAddressAsUserIdentity::class,
        ],
        'factories'  => [
            'RateLimit\\Strategy\\Api' => function (ContainerInterface $container) {
                return new RedisRateLimiter(Rate::perSecond(5), $container->get(Redis::class), 'rate_limit:api:');
            },
            'RateLimit\\Strategy\\CreatePost' => function (ContainerInterface $container) {
                return new RedisRateLimiter(Rate::perDay(20), $container->get(Redis::class), 'rate_limit:web:post');
            },
            // default limit exceeded handler; anonymous class is used only for the sake
            // of simplicity of the example
            'RateLimit\\LimitExceededRequestHandler' => function () {
                return new class implements RequestHandlerInterface {
                    public function handle(ServerRequestInterface $request): ResponseInterface
                    {
                        return new JsonResponse(['error' => 'Too many requests']);
                    }
                };
            },
            // rate limit middleware for different endpoints
            'RateLimit\\ApiRateLimitMiddleware' => function (ContainerInterface $container) {
                return new RateLimitMiddleware(
                   $container->get('RateLimiter\\Strategy\\Api'),
                   'api',
                   $container->get(ResolveUserIdentity::class),
                   $container->get('RateLimit\\LimitExceededRequestHandler')
               );
            },
            'RateLimit\\CreatePostRateLimitMiddleware' => function (ContainerInterface $container) {
                return new RateLimitMiddleware(
                   $container->get('RateLimiter\\Strategy\\CreatePost'),
                   'post.create',
                   $container->get(ResolveUserIdentity::class),
                   $container->get('RateLimit\\LimitExceededRequestHandler')
               );
            },
        ],
    ],
];
```

**index.php**

```
$app->get('/', App\Handler\HomePageHandler::class, 'home');

$app->get('/posts', [
    App\Handler\ListPostsHandler::class,
], 'post.list');
$app->post('/posts', [
    'RateLimit\\CreatePostRateLimitMiddleware',
    App\Handler\CreatePostHandler::class,
], 'post.create');
$app->put('/posts/:id', App\Handler\UpdatePostHandler::class, 'post.edit');

$app->route('/api/resource[/{id:[a-f0-9]{32}}]', [
    AuthenticationMiddleware::class,
    'RateLimit\\ApiRateLimitMiddleware',
    ApiResource::class,
], ['GET', 'POST', 'PATCH', 'DELETE'], 'api-resource');
```

Credits
-------

[](#credits)

- [Nikola Poša](https://github.com/nikolaposa)
- [All Contributors](../../contributors)

License
-------

[](#license)

Released under MIT License - see the [License File](LICENSE) for details.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity32

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity63

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 ~293 days

Total

3

Last Release

1660d ago

Major Versions

1.1.0 → 2.0.02021-10-31

PHP version history (3 changes)1.0.0PHP ^7.2

1.1.0PHP ^7.2 || ^8.0

2.0.0PHP ^7.4 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/af5242d5454968c532cb32c3855f182f92ea1f833a67c03088aca866ddfb6ef6?d=identicon)[nikolaposa](/maintainers/nikolaposa)

---

Top Contributors

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

---

Tags

middlewarepsr-15rate-limitrate-limitingmiddlewarepsr-15rate limit

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/nikolaposa-rate-limit-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/nikolaposa-rate-limit-middleware/health.svg)](https://phpackages.com/packages/nikolaposa-rate-limit-middleware)
```

###  Alternatives

[mezzio/mezzio

PSR-15 Middleware Microframework

3883.6M97](/packages/mezzio-mezzio)[tuupola/slim-basic-auth

PSR-7 and PSR-15 HTTP Basic Authentication Middleware

4442.0M26](/packages/tuupola-slim-basic-auth)[relay/relay

A PSR-15 server request handler.

3302.1M86](/packages/relay-relay)[tuupola/cors-middleware

PSR-7 and PSR-15 CORS middleware

1331.8M24](/packages/tuupola-cors-middleware)[laminas/laminas-stratigility

PSR-7 middleware foundation for building and dispatching middleware pipelines

586.6M81](/packages/laminas-laminas-stratigility)[middlewares/utils

Common utils for PSR-15 middleware packages

503.4M92](/packages/middlewares-utils)

PHPackages © 2026

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