Laravel: different api rate limits for different paths
Asked Answered
S

1

6

I need to setup different rate limits for different paths. Foe example:

On path /users I want to have rate limit of 60 requests per minute, while for path /stats I want to have rate limit of only 5 requests per minute.

I tried with next approach

Route::group(['middleware' => ['auth', 'throttle:60']], function(){
   Route::get('users', 'User@list');
});
Route::group(['middleware' => ['auth', 'throttle:5']], function(){
   Route::get('stats', 'User@stats');
});

Somehow, last rate limit is applied. However, when making requests on users path, X-Rate-Limit-Limit header is set to 60, but it throws "Too many requests" error when it reaches 6th request.

Spurtle answered 29/4, 2017 at 16:41 Comment(1)
this is weird, this is works fine in my side.Scutellation
N
5

You may want to try commenting out the default rate on line 40 of the Kernel.php since you are specifying it in each middleware group to avoid conflict.

You may also want to change the middleware to include the second parameter of how long the waiting period is until the next request can come in. (e.g. throttle:60,1)

Nonetheless answered 5/5, 2017 at 8:16 Comment(2)
There were two issues. One was my rookie mistake. I had same paths in different groups :( Second was that I required high number of requests on one path (200 req/min) so I change it initially in Kernel.php. But this solution with commenting it out in Kernel and specifying it separately for every group works fine.Spurtle
Is there a way to have a "default" throttle defined in kernel but override it for certain paths?Deviationism

© 2022 - 2024 — McMap. All rights reserved.