Laravel Sliding Window Rate Limiter

Overview

Laravel Sliding Window Rate Limiter

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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

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

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

/**
 * 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

/**
 * 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

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

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 the number of attempts for the given key.
 *
 * @param  string  $key
 *
 * @return void
 */
public function clear(string $key)

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

/**
* 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

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

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.

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

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

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
Releases(0.1.0)
Owner
Λгi
💼 Freelance Laravel Back-End Developer
Λгi
The GUI bandwidth limiter for iptables-mod-hashlimit

MulImiter OpenWrt bandwidth limiter through iptables firewall with PHP GUI Features Limit download speed per client/IP Limit upload speed per client/I

Teguh Santoso 13 Sep 15, 2022
Library download currency rate and save in database, It's designed to be extended by any available data source.

Library download currency rate and save in database, It's designed to be extended by any available data source.

Flexmind. Krzysztof Bielecki 2 Oct 6, 2021
Standardized wrapper for popular currency rate APIs. Currently supports FixerIO, CurrencyLayer, Open Exchange Rates and Exchange Rates API.

?? Wrapper for popular Currency Exchange Rate APIs A PHP API Wrapper to offer a unified programming interface for popular Currency Rate APIs. Dont wor

Alexander Graf 24 Nov 21, 2022
Ip2region is a offline IP location library with accuracy rate of 99.9% and 0.0x millseconds searching performance. DB file is ONLY a few megabytes with all IP address stored. binding for Java,PHP,C,Python,Nodejs,Golang,C#,lua. Binary,B-tree,Memory searching algorithm

Ip2region是什么? ip2region - 准确率99.9%的离线IP地址定位库,0.0x毫秒级查询,ip2region.db数据库只有数MB,提供了java,php,c,python,nodejs,golang,c#等查询绑定和Binary,B树,内存三种查询算法。 Ip2region特性

Lion 12.6k Dec 30, 2022
Laravel Blog Package. Easiest way to add a blog to your Laravel website. A package which adds wordpress functionality to your website and is compatible with laravel 8.

Laravel Blog Have you worked with Wordpress? Developers call this package wordpress-like laravel blog. Give our package a Star to support us ⭐ ?? Inst

Binshops 279 Dec 28, 2022
A Simple Linode SDK built for Laravel with @JustSteveKing laravel-transporter package

linode client A Simple Linode client built for Laravel with @JustSteveKing laravel-transporter package Installation You can install the package via co

Samuel Mwangi 2 Dec 14, 2022
A Laravel Wrapper for the Binance API. Now easily connect and consume the Binance Public & Private API in your Laravel apps without any hassle.

This package provides a Laravel Wrapper for the Binance API and allows you to easily communicate with it. Important Note This package is in early deve

Moinuddin S. Khaja 7 Dec 7, 2022
Laravel Podcast Manager is a complete podcast manager package for Laravel 5.3+ that enables you to manage RSS feeds for your favorite podcasts and listen to the episodes in a seamless UI.

laravelpodcast | A Laravel podcast manager package - v0.0.8 Introduction Laravel Podcast Manager is a complete podcast manager package for Laravel 5.3

Jeremy Kenedy 22 Nov 4, 2022
Laravel-htaccess - a package for dynamically edit .htaccess in laravel

laravel-htaccess a package for dynamically edit .htaccess in laravel use RedirectHtaccess Facade function for add RedirectHtaccess()->add(); return in

Mohammad khazaee 3 Dec 19, 2021
Laravel & Google Drive Storage - Demo project with Laravel 6.x and earlier

Laravel & Google Drive Storage Demo project with Laravel 8.X Look at the commit history to see each of the steps I have taken to set this up. Set up t

null 23 Oct 3, 2022
Empower your business to accept payments globally, earn rewards and invest in crypto with lazerpay laravel sdk in your laravel project.

Lazerpay Laravel Package pipedev/lazerpay is a laravel sdk package that access to laravel api Installation PHP 5.4+ and Composer are required. To get

Muritala David 24 Dec 10, 2022
Laravel package for Mailjet API V3 and Laravel Mailjet Mail Transport

Laravel Mailjet Laravel package for handling Mailjet API v3 using this wrapper: https://github.com/mailjet/mailjet-apiv3-php It also provides a mailje

Mailjet 76 Dec 13, 2022
Laravel 9 Template - Just a empty Laravel 9 project, ready to start new crap.

Laravel 9 Template Just a empty Laravel 9 project, ready to start new crap. Clone and start using. Usage - Local Env The same as usual with laravel. C

Gonzalo Martinez 1 Oct 31, 2022
Laravel Larex lets you translate your whole Laravel application with a single CSV file.

Laravel Larex Laravel Larex lets you translate your whole Laravel application with a single CSV file. You can import translation entries from lang fol

Luca Patera 68 Dec 12, 2022
Laravel Nova integration for justbetter/laravel-magento-customer-prices

Laravel Magento Customer Prices Nova Laravel Nova integration for justbetter/laravel-magento-customer-prices. Installation Install the package. compos

JustBetter 13 Nov 4, 2022
Laravel Nova integration for justbetter/laravel-magento-prices

Laravel Magento Prices Nova This package is the Laravel Nova integration for justbetter/laravel-magento-prices. Installation Install the package. comp

JustBetter 15 Nov 29, 2022
This package is the Laravel Nova integration for justbetter/laravel-magento-prices

Laravel Magento Products Nova This package is the Laravel Nova integration for justbetter/laravel-magento-products. Installation Install the package.

JustBetter 14 Nov 4, 2022
A helpful Laravel package to help me get started in Laravel projects quicker.

Launchpad A helpful Laravel package to help me get started in Laravel projects quicker. This is still a work in progress, so use at your own risk! CLI

Steve McDougall 13 Jun 15, 2023
A redacted PHP port of Underscore.js with additional functions and goodies – Available for Composer and Laravel

Underscore.php The PHP manipulation toolbelt First off : Underscore.php is not a PHP port of Underscore.js (well ok I mean it was at first). It's does

Emma Fabre 1.1k Dec 11, 2022