PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 16, 2022

[FIXED] Why are requests throttled for more time than specified in the middleware?

 November 16, 2022     laravel, laravel-6.2, php     No comments   

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: Returned retry-after header value is 180

(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:

  1. Place this file in your app/Http/Middleware folder.
  2. In app/Http/Kernel.php change your throttle route middleware to the new one:
'throttle' => \App\Http\Middleware\ThrottleRequestsPerRoute::class,
  1. 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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing