PHPackages                             bvtterfly/sliding-window-rate-limiter - 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. [Security](/categories/security)
4. /
5. bvtterfly/sliding-window-rate-limiter

AbandonedArchivedLibrary[Security](/categories/security)

bvtterfly/sliding-window-rate-limiter
=====================================

a sliding window rate limiter for laravel

0.1.0(4y ago)2111[3 PRs](https://github.com/bvtterfly/sliding-window-rate-limiter/pulls)MITPHPPHP ^8.0

Since Apr 14Pushed 2y ago1 watchersCompare

[ Source](https://github.com/bvtterfly/sliding-window-rate-limiter)[ Packagist](https://packagist.org/packages/bvtterfly/sliding-window-rate-limiter)[ Docs](https://github.com/bvtterfly/sliding-window-rate-limiter)[ RSS](/packages/bvtterfly-sliding-window-rate-limiter/feed)WikiDiscussions main Synced 1mo ago

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

🚨 THIS PACKAGE HAS BEEN ABANDONED 🚨

I no longer use Laravel and cannot justify the time needed to maintain this package. That's why I have chosen to abandon it. Feel free to fork my code and maintain your own copy.

Laravel Sliding Window Rate Limiter
===================================

[](#laravel-sliding-window-rate-limiter)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c92324db5b4a73209eee68fb5d58e20afa7d41ff13c6075b13cfdcde0fa38f1d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f627674746572666c792f736c6964696e672d77696e646f772d726174652d6c696d697465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/bvtterfly/sliding-window-rate-limiter)[![GitHub Tests Action Status](https://camo.githubusercontent.com/bdb46b3749c25ef3913adf8bfb1f33dc7d1e824397f0bca5420063565f34a9a6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f627674746572666c792f736c6964696e672d77696e646f772d726174652d6c696d697465722f72756e2d74657374733f6c6162656c3d7465737473)](https://github.com/bvtterfly/sliding-window-rate-limiter/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/a56837b5b1ee212556d6b8417a53c75f13b5502d92c48990e0926eaee5f25e04/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f627674746572666c792f736c6964696e672d77696e646f772d726174652d6c696d697465722f436865636b253230262532306669782532307374796c696e673f6c6162656c3d636f64652532307374796c65)](https://github.com/bvtterfly/sliding-window-rate-limiter/actions?query=workflow%3A%22Check+%26+fix+styling%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/5f3bfa3baa184cb0805f5ad0725333279fa6dbe56b50e677427a18cd10f92154/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f627674746572666c792f736c6964696e672d77696e646f772d726174652d6c696d697465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/bvtterfly/sliding-window-rate-limiter)

This package provides an easy way to limit any action during a specified time window. You may be familiar with Laravel's Rate Limiter, It has a similar API, but it uses the Sliding Window algorithm and requires Redis.

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

[](#installation)

You can install the package via composer:

```
composer require bvtterfly/sliding-window-rate-limiter
```

You can publish the config file with:

```
php artisan vendor:publish --tag="sliding-window-rate-limiter-config"
```

This is the contents of the published config file:

```
return [
    'use' => 'default',
];
```

The package relies on Redis and requires a Redis connection, and you choose which Redis connection to use.

Usage
-----

[](#usage)

The `Bvtterfly\SlidingWindowRateLimiter\Facades\SlidingWindowRateLimiter` facade may be used to interact with the rate limiter.

The simplest method offered by the rate limiter is the `attempt` method, which rate limits an action for a given number of seconds. The `attempt` method returns a result object that specifies if an attempt was successful and how many attempts remain. If the attempt is unsuccessful, you can get the number of seconds until the action is available again.

```
use Bvtterfly\SlidingWindowRateLimiter\Facades\SlidingWindowRateLimiter;

$result = SlidingWindowRateLimiter::attempt(
    'send-message:'.$user->id,
    $maxAttempts = 5,
    $decayInSeconds = 60
);

if ($result->successful()) {
    // attempt is successful, do awesome thing...
} else {
    // attempt is failed, you can get when you can retry again
    // use $result->retryAfter for getting the number of seconds until the action is available again
    // or use $result->availableAt() for getting UNIX timestamp instead.

}
```

You can call the following methods on the `SlidingWindowRateLimiter`:

### tooManyAttempts

[](#toomanyattempts)

```
/**
 * Determine if the given key has been "accessed" too many times.
 *
 * @param  string  $key
 * @param  int  $maxAttempts
 * @param  int  $decay
 *
 * @return bool
 */
public function tooManyAttempts(string $key, int $maxAttempts, int $decay = 60): bool
```

### attempts

[](#attempts)

```
/**
 * Get the number of attempts for the given key for decay time in seconds.
 *
 * @param  string  $key
 * @param  int  $decay
 *
 * @return int
 */
public function attempts(string $key, int $decay = 60): int
```

### resetAttempts

[](#resetattempts)

```
/**
 * Reset the number of attempts for the given key.
 *
 * @param  string  $key
 *
 * @return mixed
 */
public function resetAttempts(string $key): mixed
```

### remaining

[](#remaining)

```
/**
 * Get the number of retries left for the given key.
 *
 * @param  string  $key
 * @param  int  $maxAttempts
 * @param  int  $decay
 *
 * @return int
 */
public function remaining(string $key, int $maxAttempts, int $decay = 60): int
```

### clear

[](#clear)

```
/**
 * Clear the number of attempts for the given key.
 *
 * @param  string  $key
 *
 * @return void
 */
public function clear(string $key)
```

### availableIn

[](#availablein)

```
/**
 * Get the number of seconds until the "key" is accessible again.
 *
 * @param  string  $key
 * @param  int  $maxAttempts
 * @param  int  $decay
 *
 * @return int
 */
public function availableIn(string $key, int $maxAttempts, int $decay = 60): int
```

### retriesLeft

[](#retriesleft)

```
/**
* Get the number of retries left for the given key.
*
* @param  string  $key
* @param  int  $maxAttempts
* @param  int  $decay
*
* @return int
*/
public function retriesLeft(string $key, int $maxAttempts, int $decay = 60): int
```

Route Rate Limiting
-------------------

[](#route-rate-limiting)

This package comes with a `throttle` middleware for Route Rate Limiting. It can replace the default Laravel's `throttle` middleware to use this package rate limiter. The only difference is it tries to get a named rate limiter from the `SlidingWindowRateLimiter` or, as a fallback, it will take them from Laravel RateLimiter.

You may wish to change the mapping of `throttle` middleware in your application's HTTP kernel(`App\Http\Kernel`) to use `\Bvtterfly\SlidingWindowRateLimiter\Http\Middleware\ThrottleRequests` class.

Rate Limiters must be configured for route rate-limiting to work. Laravel Rate Limiter comes with a RateLimiting class(`Illuminate\Cache\RateLimiting\Limit`) that works in a minutes-based system. But This package is designed to allow rate limit actions in a seconds-based system, so it comes with its rate limiters classes and lets you configure rate limiters for less than a minute. Still, for ease of usage of this package, It supports default Laravel's Rate Limiters.

Defining Rate Limiters
----------------------

[](#defining-rate-limiters)

> `SlidingWindowRateLimiter` rate limiters are heavily based on Laravel's rate limiters. It only differs in the fact that it is seconds-based. So, before getting started, be sure to read about them on [Laravel docs](https://laravel.com/docs/routing#defining-rate-limiters).

Limit configurations are instances of the `Bvtterfly\SlidingWindowRateLimiter\RateLimiting\Limit` class, and It contains helpful "builder" methods to define your rate limits quickly. The rate limiter name may be any string you wish.

For limiting to 500 requests in 45 seconds:

```
use Bvtterfly\SlidingWindowRateLimiter\RateLimiting\Limit;
use Bvtterfly\SlidingWindowRateLimiter\Facades\SlidingWindowRateLimiter;

/**
 * Configure the rate limiters for the application.
 *
 * @return void
 */
protected function configureRateLimiting()
{
    SlidingWindowRateLimiter::for('global', function (Request $request) {
        return Limit::perSeconds(45, 500);
    });
}
```

If the incoming request exceeds the specified rate limit, a response with a 429 HTTP status code will automatically be returned by Laravel. If you would like to define your response that a rate limit should return, you may use the `response` method:

```
SlidingWindowRateLimiter::for('global', function (Request $request) {
    return Limit::perSeconds(45, 500)->response(function () {
        return response('Custom response...', 429);
    });
});
```

You can have multiple rate limits. This configuration will limit only 100 requests per 30 seconds and 1000 requests per day:

```
SlidingWindowRateLimiter::for('global', function (Request $request) {
    return [
        Limit::perSeconds(30, 100),
        Limit::perDay(1000)
    ];
});
```

Incoming HTTP request instances are passed to rate limiter callbacks, and the rate limit may be calculated dynamically depending on the user or request:

```
SlidingWindowRateLimiter::for('uploads', function (Request $request) {
    return $request->user()->vipCustomer()
                ? Limit::none()
                : Limit::perMinute(100);
});
```

There may be times when you wish to segment rate limits by some arbitrary value. For example, you may want to allow users to access a given route with 100 requests per minute per authenticated user ID and 10 requests per minute per IP address for guests. Using the `by` a method, you can create your rate limit as follows:

```
SlidingWindowRateLimiter::for('uploads', function (Request $request) {
    return $request->user()
                ? Limit::perMinute(100)->by($request->user()->id)
                : Limit::perMinute(10)->by($request->ip());
});
```

Attaching Rate Limiters To Routes
---------------------------------

[](#attaching-rate-limiters-to-routes)

Rate limiters can be attached to routes or route groups using the `throttle` middleware. The `throttle` middleware accepts the name of the rate limiter you wish to assign to the route:

```
Route::middleware(['throttle:media'])->group(function () {

    Route::post('/audio', function () {
        //
    })->middleware('throttle:uploads');

    Route::post('/video', function () {
        //
    })->middleware('throttle:uploads');

});
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Ari](https://github.com/bvtterfly)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

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

1489d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/99682351?v=4)[Λгi](/maintainers/bvtterfly)[@bvtterfly](https://github.com/bvtterfly)

---

Top Contributors

[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (8 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (8 commits)")[![bvtterfly](https://avatars.githubusercontent.com/u/99682351?v=4)](https://github.com/bvtterfly "bvtterfly (5 commits)")

---

Tags

laravelbvtterflysliding-window-rate-limiter

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/bvtterfly-sliding-window-rate-limiter/health.svg)

```
[![Health](https://phpackages.com/badges/bvtterfly-sliding-window-rate-limiter/health.svg)](https://phpackages.com/packages/bvtterfly-sliding-window-rate-limiter)
```

###  Alternatives

[spatie/laravel-ciphersweet

Use ciphersweet in your Laravel project

416718.4k1](/packages/spatie-laravel-ciphersweet)[vormkracht10/laravel-mails

Laravel Mails can collect everything you might want to track about the mails that has been sent by your Laravel app.

24149.7k](/packages/vormkracht10-laravel-mails)

PHPackages © 2026

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