Laravel API Rate-Limiting: Custom Limiters &amp; Headers | 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. Laravel API Rate-Limiting: Custom Limiters, Per-Route Strategies, and Header Contracts

 Laravel API Rate-Limiting: Custom Limiters, Per-Route Strategies, and Header Contracts
=======================================================================================

 Go beyond the default throttle middleware. Learn how to build named rate limiters, per-user dynamic limits, and consistent header contracts that clients can rely on in production Laravel APIs.

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

ShareCopy linkCopied

 ![Laravel API Rate-Limiting: Custom Limiters, Per-Route Strategies, and Header Contracts](https://cdn.msaied.com/207/587cfdafc8d105984a71d5f7b170c400.png) 

  On this page +1. [Beyond throttle:60,1: Real API Rate-Limiting in Laravel](#beyond-codethrottle601code-real-api-rate-limiting-in-laravel)
2. [Registering Named Limiters](#registering-named-limiters)
3. [Attaching Limiters to Routes](#attaching-limiters-to-routes)
4. [Understanding the Response Headers](#understanding-the-response-headers)
5. [Programmatic Checking Inside Business Logic](#programmatic-checking-inside-business-logic)
6. [Clearing Limits on Successful Upgrade](#clearing-limits-on-successful-upgrade)
7. [Testing Rate Limiters with Pest](#testing-rate-limiters-with-pest)
8. [Key Takeaways](#key-takeaways)

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

The built-in `throttle` middleware is fine for a quick guard, but production APIs need more: per-plan quotas, per-endpoint budgets, graceful degradation, and headers clients can actually parse. Laravel's `RateLimiter` facade gives you all of that — most teams just never reach for it.

---

### Registering Named Limiters

Define limiters in `AppServiceProvider::boot()` (or a dedicated `RateLimitServiceProvider`).

```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();

        if ($user?->plan === 'enterprise') {
            return Limit::none(); // unlimited
        }

        return Limit::perMinute($user?->rate_limit ?? 60)
            ->by($user?->id ?? $request->ip());
    });

    RateLimiter::for('search', function (Request $request) {
        return [
            Limit::perMinute(30)->by($request->user()?->id ?? $request->ip()),
            Limit::perDay(5_000)->by($request->user()?->id ?? $request->ip()),
        ];
    });
}

```

Returning an **array** of `Limit` objects enforces multiple windows simultaneously — a per-minute burst cap *and* a daily quota. Laravel checks all of them; the first exceeded limit triggers the 429.

---

### Attaching Limiters to Routes

```php
// routes/api.php
Route::middleware('auth:sanctum', 'throttle:api')
    ->group(function () {
        Route::get('/users', [UserController::class, 'index']);
    });

Route::middleware('auth:sanctum', 'throttle:search')
    ->get('/search', [SearchController::class, 'index']);

```

The string passed to `throttle:` maps directly to the name you registered with `RateLimiter::for()`.

---

### Understanding the Response Headers

When a request is allowed, Laravel automatically appends:

```yaml
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 43

```

When the limit is hit (HTTP 429):

```yaml
Retry-After: 47
X-RateLimit-Reset: 1718023847

```

`Retry-After` is in **seconds**; `X-RateLimit-Reset` is a Unix timestamp. Well-behaved clients should honour `Retry-After` before retrying. Document this contract explicitly — it saves support tickets.

---

### Programmatic Checking Inside Business Logic

Sometimes you need to gate an expensive operation *inside* a controller or action, not at the routing layer.

```php
use Illuminate\Support\Facades\RateLimiter;

class GenerateReportAction
{
    public function execute(User $user): Report
    {
        $key = 'report-generation:' . $user->id;

        if (RateLimiter::tooManyAttempts($key, maxAttempts: 5)) {
            $seconds = RateLimiter::availableIn($key);
            throw new TooManyRequestsException(
                "Try again in {$seconds} seconds."
            );
        }

        RateLimiter::hit($key, decaySeconds: 3600);

        return Report::generate($user);
    }
}

```

`RateLimiter::hit()` increments the counter and sets the TTL on first hit. `availableIn()` returns the seconds until the window resets — pipe that into your API error payload so clients can back off intelligently.

---

### Clearing Limits on Successful Upgrade

When a user upgrades their plan mid-session, stale limits can frustrate them. Clear programmatically:

```php
RateLimiter::clear('report-generation:' . $user->id);

```

This is also useful in tests — reset state between feature test cases rather than waiting for cache TTLs.

---

### Testing Rate Limiters with Pest

```php
use Illuminate\Support\Facades\RateLimiter;

it('returns 429 after exceeding the search limit', function () {
    $user = User::factory()->create();

    // Exhaust the limiter
    foreach (range(1, 30) as $_) {
        actingAs($user)->getJson('/api/search?q=test');
    }

    $response = actingAs($user)->getJson('/api/search?q=test');

    $response->assertStatus(429)
        ->assertHeader('Retry-After');
});

beforeEach(fn () => RateLimiter::clear('search:' . auth()->id()));

```

Always clear the limiter in `beforeEach` — cache bleeds between tests otherwise.

---

### Key Takeaways

- Use `RateLimiter::for()` with named limiters instead of raw `throttle:N,M` for any non-trivial API.
- Return an array of `Limit` objects to enforce burst *and* daily quotas simultaneously.
- `Retry-After` and `X-RateLimit-Reset` are your client contract — document them.
- `RateLimiter::hit()` / `tooManyAttempts()` / `availableIn()` let you gate expensive operations inside business logic, not just at the HTTP layer.
- Clear limiters in Pest's `beforeEach` to prevent cache state leaking between tests.

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

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

  Can I apply multiple rate limit windows (e.g. per-minute and per-day) to the same route?Yes. Return an array of Limit objects from your RateLimiter::for() callback. Laravel evaluates all of them and triggers a 429 as soon as any single limit is exceeded.

   How do I prevent rate limiter state from leaking between Pest feature tests?Call RateLimiter::clear('your-key') in a beforeEach block. Because limiters are backed by the cache driver, they persist across requests in the same test run unless explicitly cleared.

   Does returning Limit::none() for enterprise users skip all header injection?Yes. When Limit::none() is returned, the throttle middleware treats the request as unlimited and does not append X-RateLimit-\* headers, so clients should not rely on those headers being present for all users.

   ![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 articleFilament v5 Preview: What Is Changing and How to Prepare Your Codebase](https://www.msaied.com/public/articles/filament-v5-preview-what-is-changing-and-how-to-prepare-your-codebase) [Next articleLaravel Broadcasting with Reverb: Per-Channel Authorization and Presence Channels at Scale](https://www.msaied.com/public/articles/laravel-broadcasting-with-reverb-per-channel-authorization-and-presence-channels-at-scale)  

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

1. [Beyond throttle:60,1: Real API Rate-Limiting in Laravel](#beyond-codethrottle601code-real-api-rate-limiting-in-laravel)
2. [Registering Named Limiters](#registering-named-limiters)
3. [Attaching Limiters to Routes](#attaching-limiters-to-routes)
4. [Understanding the Response Headers](#understanding-the-response-headers)
5. [Programmatic Checking Inside Business Logic](#programmatic-checking-inside-business-logic)
6. [Clearing Limits on Successful Upgrade](#clearing-limits-on-successful-upgrade)
7. [Testing Rate Limiters with Pest](#testing-rate-limiters-with-pest)
8. [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)
