API Rate-Limiting in Laravel: Sliding Windows, Per-Route Limiters, and Redis Precision
#laravel #api #redis #rate-limiting

API Rate-Limiting in Laravel: Sliding Windows, Per-Route Limiters, and Redis Precision

3 min read Mohamed Said Mohamed Said

Beyond throttle:60,1 — Real Rate-Limiting in Laravel

The built-in throttle middleware is fine for simple cases, but the moment you need per-plan quotas, burst allowances, or sub-second precision you hit its limits fast. Laravel's RateLimiter facade, combined with Redis primitives, gives you everything you need without reaching for a third-party package.


Named Limiters in AppServiceProvider

Define limiters once, reference them everywhere.

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

public function boot(): void
{
    RateLimiter::for('api', function (Request $request) {
        $user = $request->user();

        return $user
            ? Limit::perMinute($user->plan->api_rpm)->by($user->id)
            : Limit::perMinute(20)->by($request->ip());
    });
}

Attach it in your route file:

Route::middleware(['auth:sanctum', 'throttle:api'])
    ->group(base_path('routes/api.php'));

The by() key is the Redis key suffix. Using $user->id means every user gets an independent counter — no shared-bucket surprises.


Multiple Limits: Burst + Sustained

Return an array to enforce both a burst cap and a sustained cap simultaneously:

RateLimiter::for('ai-inference', function (Request $request) {
    return [
        Limit::perMinute(10)->by($request->user()->id),   // burst
        Limit::perDay(500)->by($request->user()->id),     // sustained
    ];
});

Laravel evaluates every limit in the array and returns 429 as soon as any one is exceeded. The Retry-After header reflects the shortest remaining window.


Sliding Window with Redis ZADD

Laravel's default limiter uses a fixed window (a counter that resets at a hard boundary). For APIs where clients batch requests at window edges, a sliding window is fairer.

Implement it with a sorted set:

use Illuminate\Support\Facades\Redis;

final class SlidingWindowLimiter
{
    public function attempt(string $key, int $maxAttempts, int $windowSeconds): bool
    {
        $now = microtime(true);
        $windowStart = $now - $windowSeconds;

        Redis::pipeline(function ($pipe) use ($key, $now, $windowStart) {
            // Remove entries outside the window
            $pipe->zremrangebyscore($key, '-inf', $windowStart);
            // Add current request timestamp as both score and member
            $pipe->zadd($key, $now, uniqid('', true));
            // Expire the key slightly beyond the window
            $pipe->expire($key, (int) ceil($windowStart) + 10);
        });

        $count = Redis::zcard($key);

        return $count <= $maxAttempts;
    }
}

Use it inside a custom middleware:

public function handle(Request $request, Closure $next): mixed
{
    $key = 'sliding:' . $request->user()?->id ?? $request->ip();

    if (! $this->limiter->attempt($key, 30, 60)) {
        return response()->json(['message' => 'Too Many Requests'], 429);
    }

    return $next($request);
}

The pipeline keeps the three Redis commands atomic enough for most workloads. For strict atomicity under high concurrency, replace the pipeline with a Lua script.


Exposing Quota Headers

Clients need visibility. Add headers in a response macro or middleware:

$key = RateLimiter::key('api', $request);
$response->headers->set('X-RateLimit-Limit', 60);
$response->headers->set('X-RateLimit-Remaining', RateLimiter::remaining('api', $request));
$response->headers->set('X-RateLimit-Reset', RateLimiter::availableIn('api', $request));

RateLimiter::remaining() accepts the limiter name and the request, so it resolves the correct per-user key automatically.


Handling 429 Gracefully

Return a JSON body with a retry_after field so API clients can back off intelligently:

// In app/Exceptions/Handler.php (Laravel 11+ bootstrap/app.php)
$exceptions->render(function (ThrottleRequestsException $e, Request $request) {
    return response()->json([
        'message' => 'Rate limit exceeded.',
        'retry_after' => $e->getHeaders()['Retry-After'] ?? null,
    ], 429, $e->getHeaders());
});

Key Takeaways

  • Named limiters in boot() centralise quota logic and support dynamic per-user values.
  • Array limits let you combine burst and sustained caps with zero extra code.
  • Sliding windows via Redis sorted sets eliminate the fixed-window edge-burst problem.
  • Expose quota headers (X-RateLimit-*) so clients can self-throttle before hitting 429.
  • Custom 429 responses with retry_after make your API a good citizen for automated consumers.

Found this useful?

Frequently Asked Questions

3 questions
Q01 What is the difference between a fixed window and a sliding window rate limiter?
A fixed window resets its counter at a hard time boundary (e.g., every full minute). A sliding window tracks requests within the last N seconds relative to *now*, so a burst at the boundary of two fixed windows is still caught. Sliding windows are fairer but require a sorted set in Redis rather than a simple counter.
Q02 Can I use named limiters with Sanctum or Passport token scopes?
Yes. Inside the named limiter closure you have full access to the request, including `$request->user()` and any token abilities. You can branch on `$request->user()->tokenCan('admin')` or check a plan attribute to return different `Limit` instances per token scope.
Q03 Is the Redis pipeline approach atomic enough for production?
For most APIs, yes — the three commands (ZREMRANGEBYSCORE, ZADD, EXPIRE) execute back-to-back with no interleaving from other clients in a pipeline. If you need strict atomicity under very high concurrency on a single key, replace the pipeline with a Lua script executed via `Redis::eval()`, which runs atomically on the Redis server.

Continue reading

More Articles

View all