Laravel API Rate Limiting: Setup & Best Practices

Written by

in

An API without rate limiting is a revolving door with no bouncer. A single misbehaving client script, a scraper, or a credential-stuffing bot can saturate database connections, spike CPU usage, and inflate third-party billing before your monitoring even alerts you.

Laravel solves this with a clean two-part architecture: named rate limiters (RateLimiter::for(...)) that define who is limited and how much, paired with the throttle middleware that enforces those rules and returns standard HTTP 429 Too Many Requests responses when exceeded.


Why API Rate Limiting Matters in Production

Rate limiting protects both system stability and product economics:

  • Preventing resource exhaustion: Caps sudden traffic spikes so database pools, queues, and workers stay healthy under load.
  • Blocking brute-force and scraping abuse: Slows down automated login guessing, OTP spam, and bulk catalog scraping.
  • Enforcing plan tiers fairly: Gives authenticated or paid API consumers higher quotas than anonymous guests.
  • Protecting downstream services: Keeps your outbound calls within third-party API and mail-provider quotas.

Setting Up API Throttling in Laravel

In modern Laravel applications, API middleware is configured in bootstrap/app.php and named limiters are typically registered inside AppProvidersAppServiceProvider::boot().

1. Enable the api Rate Limiter

Enable API throttling in bootstrap/app.php:

<?php

use IlluminateFoundationApplication;
use IlluminateFoundationConfigurationMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->throttleApi();
    })
    ->create();

2. Define the api Limiter in AppServiceProvider

Define how api is evaluated for each incoming Request:

<?php

namespace AppProviders;

use IlluminateCacheRateLimitingLimit;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRateLimiter;
use IlluminateSupportServiceProvider;

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

Keying by $request->user()->id for authenticated requests prevents users behind a shared corporate or mobile carrier IP from throttling one another, while falling back to $request->ip() for guests.


Customizing Limits for Real-World Endpoints

A single global bucket rarely fits every route. A public read endpoint and a password reset endpoint have very different risk profiles.

Tiered Quotas by Plan or Role

Return a different Limit instance based on the authenticated user’s tier or role:

RateLimiter::for('exports', function (Request $request) {
    $user = $request->user();

    if (! $user) {
        return Limit::none();
    }

    return match ($user->plan) {
        'enterprise' => Limit::perMinute(60)->by($user->id),
        'pro' => Limit::perMinute(15)->by($user->id),
        default => Limit::perMinute(3)->by($user->id),
    };
});

Protecting Authentication Endpoints

For login routes, keying by both the submitted email/identifier and IP address helps contain targeted credential attacks without blocking unrelated users on the same network:

RateLimiter::for('login', function (Request $request) {
    $email = strtolower((string) $request->input('email'));

    return Limit::perMinute(5)->by($email.'|'.$request->ip());
});

Apply custom limiters directly on routes in routes/api.php:

use AppHttpControllersApiAuthController;
use AppHttpControllersApiExportController;
use IlluminateSupportFacadesRoute;

Route::post('/login', [AuthController::class, 'login'])
    ->middleware('throttle:login');

Route::middleware(['auth:sanctum', 'throttle:exports'])
    ->post('/exports', [ExportController::class, 'store']);

Layering Multiple Limits

You can return an array of Limit objects from a single RateLimiter::for(...) callback to combine short burst protection with a sustained daily cap:

RateLimiter::for('webhooks', function (Request $request) {
    $key = $request->user()?->id ?? $request->ip();

    return [
        Limit::perMinute(60)->by($key),
        Limit::perDay(1000)->by($key),
    ];
});

Understanding Responses, Headers, and Cache Stores

HTTP 429 and Rate Limit Headers

When a client stays within its quota, Laravel includes rate limit headers such as X-RateLimit-Limit and X-RateLimit-Remaining on responses. When a limit is exceeded, Laravel throws a ThrottleRequestsException, returning a 429 Too Many Requests response along with retry metadata (such as Retry-After and X-RateLimit-Reset).

Clients consuming your API should inspect Retry-After (with a sensible upper cap and jitter) rather than hammering retries in a tight loop.

Use a Fast Cache Store in Production

RateLimiter relies on Laravel’s cache store to track counters. Using a database cache store under heavy traffic adds extra write load on every API request. Pointing cache.limiter to redis isolates rate-limit counters on a fast in-memory store:

// config/cache.php
'limiter' => env('CACHE_LIMITER', 'redis'),

Production Checklist for Laravel API Rate Limits

Area Recommendation Why It Matters
Cache driver Use redis for cache.limiter Avoids database contention during traffic bursts
Bucket keys Key by authenticated user ID when logged in; fall back to IP Prevents shared-IP false positives for authenticated clients
Endpoint granularity Separate login, search, write, and export limiters Matches quota strictness to computational cost and abuse risk
Burst + sustained caps Pair perMinute with perHour or perDay limits Stops both sudden spikes and slow, all-day scraping
Reverse proxy IPs Configure trusted proxies properly Ensures $request->ip() reflects the real client IP behind load balancers

Common Pitfalls to Avoid

  • Leaving limits off public or unauthenticated routes: Bots hit unauthenticated endpoints first; always give anonymous traffic a strict baseline limit.
  • Setting uniform limits across cheap and expensive endpoints: A lightweight health or profile read should not share the same budget as a heavy report or search query.
  • Ignoring proxy headers: If your Laravel app sits behind a load balancer or CDN and trusted proxies are misconfigured, all traffic can appear to come from the proxy IP—locking out your entire user base at once.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *