imliam / laravel-throttle-simultaneous-requests
Throttle the current user's requests based on how many requests are currently being executed.
Fund package maintenance!
imliam
Requires
- php: ^7.3
- illuminate/http: ^7.0|^8.0
- illuminate/support: ^7.0|^8.0
Requires (Dev)
- larapack/dd: ^1.0
- orchestra/testbench: ^5.0|^6.0
- phpunit/phpunit: ^7.0|^8.0|^9.0
This package is auto-updated.
Last update: 2024-11-13 22:03:44 UTC
README
Throttle the current user's requests based on how many requests are currently being executed, in case any are time consuming before giving a response.
This helps when some endpoints are more resource-intensive than others, and stops users from retrying requests that may not have even completed yet.
This forces users of your API to interact in a different way by queuing their requests appropriately instead of spamming until they reach the request limit.
When performing an action only the current user can perform, this also helps to ensure that the endpoint has a form of idempotency and any side effects can only occur once until a subsequent request is made.
Installation
You can install the package with Composer using the following command:
composer require imliam/laravel-throttle-simultaneous-requests:^2.0.0
Once installed to your project, add the middleware to your App\Http\Kernel::$routeMiddleware
array.
protected $routeMiddleware = [ // ... 'simultaneous' => \ImLiam\ThrottleSimultaneousRequests\ThrottleSimultaneousRequests::class, ];
Usage
You can use the middleware like any other. For example, to limit a particular endpoint to only 3 concurrent requests by the same user:
Route::get('/', 'HomeController@index')->middleware('simultaneous:3');
Why not use queues?
Queues have their place to defer time consuming tasks to a later date, however they are not always the most appropriate solution for a task. A given task could require use of limited hardware resources, or require some other kind of processing that does not make sense to run concurrently.
See how Stripe use concurrent request limiters...
Why is no Retry-After
header sent?
Most typical rate limiting solutions limit a user to a number of requests within a set time period, such as 100 requests per minute, so include a Retry-After
header to let the requestor know when they are available to try again.
This middleware does not add such a header to the response, due to the nature of the request taking a longer amount of time to complete there is no guaranteed time where the requestor can retry the request. Instead, it is up to the requestor to determine when to retry.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email liam@liamhammett.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.