create a rate limiter for a controller in php

One way to implement a rate limiter for a controller in PHP is by using middleware and Redis. Redis is used as a data store to keep track of the number of requests made by a client to a particular endpoint.

Here is an example implementation of a rate limiter middleware that limits the number of requests to 10 per minute per client.

main.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Closure;

class RateLimiterMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $limit = 10; // number of requests allowed
        $period = 60; // time period in seconds
        $clientIp = $request->ip(); // unique identifier for the client

        $key = $this->getKey($clientIp);

        $currentRequests = Redis::get($key) ?: 0; // get client's current requests

        if ($currentRequests >= $limit) {
            return response()->json(['message' => 'Too Many Requests'], 429); // return 429 error response
        }

        Redis::incr($key); // increment client's requests
        Redis::expire($key, $period); // set expiry time

        return $next($request);
    }

    private function getKey($clientIp)
    {
        return "rate_limiter:$clientIp";
    }
}
890 chars
33 lines

To use the middleware in a controller, add it to the middleware() method of the controller:

main.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MyController extends Controller
{
    public function __construct()
    {
        $this->middleware(RateLimiterMiddleware::class);
    }

    public function myMethod(Request $request)
    {
        // controller logic
    }
}
302 chars
18 lines

This middleware limits the number of requests made by a client to an endpoint, allowing for better control over server resources and preventing abuse by clients.

gistlibby LogSnag