Laravel Magazine
Building an API Rate-Limiting System with Named Throttle Limiters and Sanctum

Building an API Rate-Limiting System with Named Throttle Limiters and Sanctum

Eric Van Johnson ·

The PHP Architect API team shipped a public API last quarter with throttle:60,1 slapped on the route group and called it done. Then the sales team sold an "enterprise" tier that was supposed to get a higher limit, and a free-tier customer started hammering the endpoint from a script. Both problems have the same root cause: one global rate limit doesn't know who's asking. Here's how to build a tiered, per-token rate-limiting system with Laravel's named rate limiters and Sanctum.

Step 1: Define named limiters per plan

Rate limiters are registered in App\Providers\AppServiceProvider (or a dedicated RateLimitServiceProvider) using the RateLimiter facade. Instead of one limiter, define one per plan:

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

public function boot(): void
{
    RateLimiter::for('api-free', function ($request) {
        return Limit::perMinute(30)->by($request->user()?->id ?: $request->ip());
    });

    RateLimiter::for('api-pro', function ($request) {
        return Limit::perMinute(300)->by($request->user()?->id ?: $request->ip());
    });

    RateLimiter::for('api-enterprise', function ($request) {
        return Limit::perMinute(2000)->by($request->user()?->id ?: $request->ip());
    });
}

Each closure returns a Limit scoped by() a key — the authenticated user ID when available, falling back to IP for unauthenticated requests.

Step 2: Resolve the correct limiter per request

You don't want three near-identical route groups. Instead, register a single dynamic limiter that looks up the caller's plan and forwards to the matching limit:

RateLimiter::for('api', function ($request) {
    $plan = $request->user()?->currentPlan() ?? 'free';

    return match ($plan) {
        'enterprise' => Limit::perMinute(2000)->by($request->user()->id),
        'pro' => Limit::perMinute(300)->by($request->user()->id),
        default => Limit::perMinute(30)->by($request->user()?->id ?: $request->ip()),
    };
});

This is the version worth shipping — one middleware name (throttle:api), one place that decides the limit.

Step 3: Apply it to your Sanctum-protected routes

Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
    Route::get('/v1/reports', [ReportController::class, 'index']);
    Route::post('/v1/reports', [ReportController::class, 'store']);
});

Any request that busts the limit gets Laravel's standard 429 Too Many Requests response automatically, with X-RateLimit-Limit and X-RateLimit-Remaining headers included.

Step 4: Give customers visibility into their own usage

A 429 with no context is a support ticket waiting to happen. Expose the current state back to the caller by reading the limiter directly in a controller or a response macro:

use Illuminate\Support\Facades\RateLimiter;

public function usage(Request $request)
{
    $key = 'api-' . ($request->user()?->id ?: $request->ip());

    return response()->json([
        'limit' => RateLimiter::attempts($key),
        'remaining' => RateLimiter::remaining($key, $request->user()?->currentPlan()?->limit ?? 30),
        'retry_after_seconds' => RateLimiter::availableIn($key),
    ]);
}

Step 5: Test it with Pest

it('throttles free tier users after 30 requests per minute', function () {
    $user = User::factory()->create(['plan' => 'free']);

    Sanctum::actingAs($user);

    for ($i = 0; $i < 30; $i++) {
        $this->getJson('/v1/reports')->assertOk();
    }

    $this->getJson('/v1/reports')->assertStatus(429);
});

A few gotchas worth knowing

The by() key determines the bucket — if you key by IP for authenticated users behind a shared corporate NAT, you'll throttle the whole office together. Prefer the user ID whenever you have one. Also remember that Laravel's default rate limiter cache store is whatever's configured in config/cache.php; for anything beyond a single server, make sure that's Redis or Memcached, not file or array, or your limits will be per-server instead of global.

Named, plan-aware rate limiters take about twenty minutes to wire up and save you from the two worst outcomes: angry enterprise customers hitting a limit meant for free users, and a single bad actor taking down an endpoint everyone else depends on.

Stay Updated

Subscribe to our newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.

Weekly articles
We send a new issue of the newsletter every week on Friday.
No spam
We'll never share your email address and you can opt out at any time.