Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

poma's avatar
Level 1

How to apply different rate limits for different paths?

I want to apply a global throttle to all my API requests but for some paths apply a special rule. I could remove throttle middleware from Kernel.php and split all routes in groups but this would create a mess in routes file. Is there a way to keep a throttle middleware in Kernel.php applied to all routes and override its behavior for certain routes like this

Route::get(...)->middleware('throttle:10,1');

OR

Route::get(...)->middleware('throttle-override:10,1');
0 likes
5 replies
robrogers3's avatar

yep. use default throttle middleware for most. and then write custom middleware for the custom routes.

For your custom routes, copy or make this parent class. (You're really only interested in ::handle method, so parent is fine. https://github.com/illuminate/routing/blob/master/Middleware/ThrottleRequests.php

So, you might create one called ThrottleOverRideRequests change the ::handle method for the defaults (if needed).

Assign the middleware: https://github.com/illuminate/routing/blob/master/Middleware/ThrottleRequests.php

  • 'super-strict-throttle' => \App\Http\Middleware\ThrottleOverRideRequests::class

Use it: Route::get(...)->middleware('super-strict-throttle');

rinse and repeat.

poma's avatar
Level 1

The problem is that because global throttle is still attached and is above my middleware it will override x-ratelimit-remaining header with its value.

robrogers3's avatar

Do you mean this: 'api' => [ 'throttle:60,1', 'auth:api', ],

I think my solution in the past was to yank it out -- it's just a default Taylor wrote in so you don't have to. Then apply it in the api as needed. Or maybe not, but I've coded different throttles and they worked fine.

https://laracasts.com/discuss/channels/laravel/laravel-api-rate-limiting-throttle-increase-limit-greater-than-60

If that does'nt work let me know and I'll code up something

poma's avatar
Level 1

I think my solution in the past was to yank it out -- it's just a default Taylor wrote in so you don't have to. Then apply it in the api as needed.

That's what I wanted to avoid as mentioned in op. If I remove it then I will need to explicitly specify throttle for each route which makes code ugly.

robrogers3's avatar

I get what you are saying. The default throttle kicks in last and overwrites x-ratelimit-remaining. It calls $response->headers->add which replaces any other headers previously set.

An option is to override ThrottleRequests::addHeaders to use $response->headers->set($key, $values, FALSE); <-- default is true This would keep the original x-ratelimit-remaining set.

For me ugly is the way to go. I like to explicitly set my middleware. Less secret sauce the better.

Please or to participate in this conversation.