CodexBloom - Programming Q&A Platform

Laravel 10 - Difficulty with custom middleware to limit API request rates causing advanced patterns

πŸ‘€ Views: 23 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
laravel middleware api caching PHP

I'm trying to implement a custom middleware in Laravel 10 that limits the rate of API requests from users based on their roles. The idea is simple: users with the role 'admin' should have unlimited requests, while 'user' roles should be limited to 100 requests per hour. However, I'm running into some unexpected behavior where the limit isn't being enforced correctly for 'user' roles, and sometimes, even 'admin' users are being blocked. Here's the middleware I've created: ```php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Cache; class RateLimitMiddleware { public function handle($request, Closure $next) { $user = $request->user(); $key = 'rate_limit:' . $user->id; if ($user->role === 'admin') { return $next($request); } $requests = Cache::get($key, 0); if ($requests >= 100) { return response()->json(['behavior' => 'Rate limit exceeded'], 429); } Cache::increment($key); Cache::put($key, $requests + 1, 3600); // Expires in an hour return $next($request); } } ``` I've registered the middleware in `Kernel.php` as follows: ```php protected $routeMiddleware = [ // other middleware 'rate.limit' => \App\Http\Middleware\RateLimitMiddleware::class, ]; ``` And I’m applying it to my API routes like this: ```php Route::middleware(['auth:sanctum', 'rate.limit'])->group(function () { Route::get('/user/data', [UserController::class, 'data']); }); ``` What’s perplexing is that while testing, I logged the number of requests for a user with the role 'user', and it correctly shows increments. But after the 100th request, the `RateLimitMiddleware` still lets the user through without any blocking. On the other hand, sometimes 'admin' users are also being blocked, which should not happen at all. I've cleared the cache multiple times using `php artisan cache:clear`, and I also verified that the user role is being checked correctly. I suspect there might be an scenario with how I'm caching the request counts, but I need to pinpoint the question. Could anyone provide insights into what might be going wrong? Am I missing something in the logic, or is there a better way to implement this rate limiting? Any help would be greatly appreciated.