Issue
I have my routes declared like this:
Route::group(['prefix' => 'media', 'middleware' => 'auth'], function() {
Route::group(['middleware' => 'throttle:120,1'], function() {
Route::get('/', 'MediaController@index'); // <-- Route in question
Route::delete('/{id}', 'MediaController@delete');
Route::patch('/{id}', 'MediaController@edit');
});
Route::post('/', 'MediaController@upload')->middleware('throttle:100,1440');
});
If I understand the throttling middleware correctly, when user hits the rate limiting (120 requests in 1 minute) he should be throttled for the remaining time of the 1 minute period and then unblocked.
However, the blocking time is higher than 1 minute. See retry-after
header:
(When I first noticed it, it was more than 600 seconds so it's not always 180 seconds)
Any ideas why would it be higher than 1 minute?
Solution
I figured it out!
Turns out the default behavior for the throttle
middleware doesn't work per route. It just throttles requests per logged in user. And as you can see I had one route (the upload one) that has throttle:100,1440
, and this caused problems resulting in much longer "punishments" even for routes with throttle:120,1
.
My solution:
I wrote my own version of the ThrottleRequests.php
middleware that works per route:
- Place this file in your
app/Http/Middleware
folder. - In
app/Http/Kernel.php
change your throttle route middleware to the new one:
'throttle' => \App\Http\Middleware\ThrottleRequestsPerRoute::class,
- Now whenever you assign a
throttle
middleware it will work per route.
Another solution:
You can also use the default middleware and make use of the 3rd parameter. You can pass a prefix parameter like that: throttle:100,1440,upload
. It will assign the upload prefix to the throttling key and rate limit the requests based on that. However, to achieve per route rate limiting you would have to assign a different prefix for each route.
Answered By - lukaszmtw Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.