Laravel API Rate-Limiting: Sliding Windows &amp; Redis | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. API Rate-Limiting in Laravel: Sliding Windows, Per-Route Limiters, and Redis Precision

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

 Go beyond the default throttle middleware. Learn how to build sliding-window rate limiters, per-user dynamic limits, and Redis-backed precision counters that hold up under real production traffic.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 9 Jul 2026 · Updated 9 Jul 2026 · 3 min read

ShareCopy linkCopied

 ![API Rate-Limiting in Laravel: Sliding Windows, Per-Route Limiters, and Redis Precision](https://cdn.msaied.com/398/bb46e069aecd78f39c7ac31e2e1b13e2.png) 

  On this page +1. [Beyond throttle:60,1 — Real Rate-Limiting in Laravel](#beyond-codethrottle601code-real-rate-limiting-in-laravel)
2. [Named Limiters in AppServiceProvider](#named-limiters-in-codeappserviceprovidercode)
3. [Multiple Limits: Burst + Sustained](#multiple-limits-burst-sustained)
4. [Sliding Window with Redis ZADD](#sliding-window-with-redis-zadd)
5. [Exposing Quota Headers](#exposing-quota-headers)
6. [Handling 429 Gracefully](#handling-429-gracefully)
7. [Key Takeaways](#key-takeaways)

 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.

```php
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:

```php
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:

```php
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:

```php
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 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:

```php
$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:

```php
// 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.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [api](https://www.msaied.com/public/articles?search=api)
- [redis](https://www.msaied.com/public/articles?search=redis)
- [rate-limiting](https://www.msaied.com/public/articles?search=rate-limiting)

 Frequently asked questions 
---------------------------

  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.

   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-&gt;user()` and any token abilities. You can branch on `$request-&gt;user()-&gt;tokenCan('admin')` or check a plan attribute to return different `Limit` instances per token scope.

   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.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleLaravel Telescope Alternatives: Building a Lightweight Debug Bar with Custom Watchers](https://www.msaied.com/public/articles/laravel-telescope-alternatives-building-a-lightweight-debug-bar-with-custom-watchers) [Next articleLaravel Eloquent Global Scopes: Bootable Traits, Scope Removal, and Testing Pitfalls](https://www.msaied.com/public/articles/laravel-eloquent-global-scopes-bootable-traits-scope-removal-and-testing-pitfalls)  

   On this page
-------------

1. [Beyond throttle:60,1 — Real Rate-Limiting in Laravel](#beyond-codethrottle601code-real-rate-limiting-in-laravel)
2. [Named Limiters in AppServiceProvider](#named-limiters-in-codeappserviceprovidercode)
3. [Multiple Limits: Burst + Sustained](#multiple-limits-burst-sustained)
4. [Sliding Window with Redis ZADD](#sliding-window-with-redis-zadd)
5. [Exposing Quota Headers](#exposing-quota-headers)
6. [Handling 429 Gracefully](#handling-429-gracefully)
7. [Key Takeaways](#key-takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
