Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel 10 – Make a Limit in ThrottleRequest with cache

So I want to give a limit to requests that require a key, and a limit of 100x requests in 60 minutes (for a trial of 10x requests in 5 seconds) and will return (reset) to 0.
but i tried this code, and after 5 seconds the limit is not reset and requests are still limited.

I try this code :

        $key = $request->apikey;
        $apiKey = ApiKey::where('key', $key)->first();
        if (!$apiKey) {
            return response()->json(['message' => 'Invalid API key'], 401);
        }

        $rateLimit = 10;
        $timer = 5;

        $requests = $apiKey->ignore_limits ?? 0;
        $lastRequestTime = Cache::get($key . ':timer');
        dd(Cache::has($key));
        if ($lastRequestTime && (time() - $lastRequestTime) > ($timer)) {
            $requests = 0;
        } else {
            if ($requests >= $rateLimit) {
                return response()->json(['message' => 'Rate limit exceeded'], 429);
            }
            $requests = $apiKey->ignore_limits ?? $requests;
        }

        $apiKey->ignore_limits = $requests + 1;
        $apiKey->save();
        Cache::put($key, $requests, now()->addSeconds($timer));
        Cache::put($key . ':timer', time(), now()->addSeconds($timer));

        return $next($request);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’ve made some adjustments to your code to make it correctly implement rate limiting:

  $key = $request->apikey;
$apiKey = ApiKey::where('key', $key)->first();

if (!$apiKey) {
    return response()->json(['message' => 'Invalid API key'], 401);
}

$rateLimit = 10;
$timer = 5;

$requests = Cache::get($key, 0);
$lastRequestTime = Cache::get($key . ':timer');

if ($lastRequestTime && (time() - $lastRequestTime) > $timer) {
    Cache::put($key, 0, now()->addMinutes(1)); // Reset the request count
} else {
    if ($requests >= $rateLimit) {
        return response()->json(['message' => 'Rate limit exceeded'], 429);
    }
    Cache::increment($key); // Increase the request count
}

Cache::put($key . ':timer', time(), now()->addMinutes(1)); // Update the request time

return $next($request);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading