Laravel how to limit route to 400 executions per second for all users, not each of them,…
- User
Laravel how to limit route to 400 executions per second for all users, not each of them, but all of them?
- Assistant
One possible solution is to use a middleware that limits the number of requests to a certain threshold. Here's an example of how to implement such a middleware in Laravel:
-
Create a new middleware class using the
make:middlewarecommand:php artisan make:middleware RateLimitMiddleware -
In the
handlemethod of the middleware, you can track the number of requests made within the last second using a cache driver of your choice (e.g. Redis or Memcached):use Closure; use Illuminate\Support\Facades\Cache; class RateLimitMiddleware { public function handle($request, Closure $next) { $key = 'rate-limit:' . date('YmdHi'); $requests = Cache::increment($key); if ($requests > 400) { abort(429, 'Too many requests'); } Cache::put($key, $requests, now()->addSeconds(1)); return $next($request); } }
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.