How to set the rate limiter for per second in Laravel version 8

560 views
Skip to first unread message

Mahendran K

unread,
Aug 20, 2021, 9:18:53 AM8/20/21
to Laravel
How to set the rate limiter per second in **Laravel 8**. I need to set the rate limiter per second instead of per minute.


Right now I'm able to use Laravel's rate limiter for minutes, hours, etc. But I'm trying to achieve a rate limiter for a second. I want to limit 25 requests per sec.
(Exported Limit class from "Illuminate\Cache\RateLimiting\Limit")

 

Please check the following code which I have used 

    RateLimiter::for('api', function (Request $request) {
            return [
                // Rate limiter based on Client IP Address
                Limit::perMinute(env('IP_ADDR_RATE_LIMITER_PER_MINUTE', 60))->by($request->ip())->response(function () {
                    ....
                }),
                // Rate limiter based on API key/User
                Limit::perMinute(env('API_KEY_RATE_LIMITER_PER_MINUTE', 60))->by($request->input('key'))->response(function () {
                    ...
                })
            ];
        });

Is there any way to rate-limit 25 requests per second?

Note: also tried adding/changing functions in Illuminate\Cache\RateLimiting\Limit, where I tried altering the per minute function.
Thanks in Advance.

Shikhar Soni

unread,
Sep 15, 2021, 9:57:44 AM9/15/21
to Laravel
Hello ,
Prob. Answer :
1- Configure Rate Limiter in RouteServiceProvider
2- Open App\Providers\RouteServiceProvider class and add following changes:
/** * 
Configure the rate limiters for the application. 
*
@return void 
*/ 
protected function configureRateLimiting() 
     // ALLOW 1500/60 = 25 Request/Sec 
     RateLimiter::for('api', function (Request $request) {
      return Limit::perMinute(1500); }); 
      // ALLOW 1000/60 = 16.66 Request/Sec 
      RateLimiter::for('api', function (Request $request) { 
       return Limit::perMinute(1000)->response(function () { 
        return response('Too many request...', 429); 
     });  
   });  
  }

Hope this solution work.
Reply all
Reply to author
Forward
0 new messages