Laravel Throttle Guide: Rate Limiting Made Easy

Written by

in

Mastering Laravel Throttle: Protecting Your Application from Overload and Abuse

Every public-facing web application eventually meets an uninvited guest: a misconfigured client stuck in a retry loop, a credential-stuffing bot hammering /login, or a scraper pulling your entire catalog in seconds. Left unchecked, a single noisy neighbor can exhaust your PHP workers, saturate database connections, and take down your application for everyone else.

Laravel solves this out of the box with its throttle middleware and RateLimiter facade—an expressive, cache-backed system for controlling how frequently users, IP addresses, or API keys can trigger routes and actions.


How Laravel Throttling Works Under the Hood

At its core, Laravel’s throttle alias maps to IlluminateRoutingMiddlewareThrottleRequests (or ThrottleRequestsWithRedis when Redis-backed throttling is enabled).

When an HTTP request hits a throttled route, Laravel performs a rapid sequence of steps before your controller ever executes:

  1. Key Resolution: It generates a unique cache signature for the incoming request—typically combining the limiter name, route signature, and the client’s IP address or authenticated user ID.
  2. Counter Check: It checks your configured cache store to see how many hits that key has accumulated within the current time window.
  3. Allow or Reject:
    • Under the limit: Laravel increments the counter, passes the request to your controller, and attaches helpful rate-limit headers (X-RateLimit-Limit and X-RateLimit-Remaining) to the response.
    • Over the limit: Laravel immediately aborts with an HTTP 429 Too Many Requests response and adds a Retry-After header telling the client how many seconds to wait before trying again.

Because this check happens in middleware, blocked requests never touch your controllers, Eloquent models, or heavy business logic.


Quick Inline Throttling on Routes

For straightforward endpoints where a fixed ceiling is all you need, pass parameters directly to the throttle middleware using the format throttle:maxAttempts,decayMinutes:

use IlluminateSupportFacadesRoute;

// Allow 60 requests per 1 minute
Route::middleware('throttle:60,1')->group(function () {
    Route::get('/articles', [ArticleController::class, 'index']);
});

// Strict limit for sensitive endpoints: 5 attempts every 10 minutes
Route::post('/password/reset', [PasswordResetController::class, 'store'])
    ->middleware('throttle:5,10');

When using inline parameters like throttle:60,1, Laravel tracks authenticated requests by user ID and guest requests by IP address automatically.


Named Rate Limiters: Dynamic, Tiered Control

Inline numbers work well for simple rules, but real-world applications rarely treat every user the same. Free-tier users might get 60 requests per minute, enterprise customers 1,000, and internal webhooks no limit at all.

Laravel’s named rate limiters centralize this logic in the boot() method of your AppProvidersAppServiceProvider using RateLimiter::for():

use IlluminateCacheRateLimitingLimit;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRateLimiter;

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

        if (! $user) {
            return Limit::perMinute(30)->by($request->ip());
        }

        return $user->isPro()
            ? Limit::perMinute(300)->by($user->id)
            : Limit::perMinute(60)->by($user->id);
    });
}

Once registered, attach the limiter by name in your route definitions:

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

Stacking Multiple Limits

You can return an array of Limit instances from a single named limiter. Every rule in the array is evaluated in order, letting you enforce both short-term burst protection and broader daily caps simultaneously:

RateLimiter::for('exports', function (Request $request) {
    return [
        // Prevent rapid-fire bursts (max 2 per minute)
        Limit::perMinute(2)->by($request->user()->id),
        // Enforce a daily quota (max 20 per day)
        Limit::perDay(20)->by($request->user()->id),
    ];
});

Customizing the 429 Response

By default, exceeding a rate limit returns Laravel’s standard 429 error view or JSON payload. You can override that response per limiter by chaining the response() method:

RateLimiter::for('uploads', function (Request $request) {
    return Limit::perMinute(10)
        ->by($request->user()->id)
        ->response(function (Request $request, array $headers) {
            return response()->json([
                'message' => 'Upload quota reached. Please wait before sending more files.',
                'retry_after_seconds' => $headers['Retry-After'] ?? 60,
            ], 429, $headers);
        });
});

Enabling Global API Throttling in Modern Laravel

In modern Laravel releases (Laravel 11 and newer), the default api middleware group does not include throttling out of the box. If you want all routes in routes/api.php throttled automatically, opt in inside bootstrap/app.php:

use IlluminateFoundationApplication;
use IlluminateFoundationConfigurationMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->throttleApi();
    })
    ->create();

Important catch: Calling $middleware->throttleApi() attaches throttle:api to your API routes. Because Laravel no longer defines an 'api' rate limiter by default, you must also define RateLimiter::for('api', ...) in AppServiceProvider::boot(), or API requests will throw a MissingRateLimiterException.


Programmatic Throttling Beyond HTTP Routes

Not every action you want to protect is an HTTP route. You might want to prevent a user from triggering more than three SMS verifications per hour inside a service class, or limit how fast a console command dispatches notifications.

For non-route logic, use the RateLimiter facade directly:

use IlluminateSupportFacadesRateLimiter;

$key = 'send-sms:' . $user->id;

$executed = RateLimiter::attempt(
    key: $key,
    maxAttempts: 3,
    callback: function () use ($user) {
        $user->sendVerificationSms();
    },
    decaySeconds: 3600
);

if (! $executed) {
    $seconds = RateLimiter::availableIn($key);
    throw new RuntimeException("Too many SMS requests. Try again in {$seconds} seconds.");
}

You also have fine-grained manual methods when you need them:

  • RateLimiter::tooManyAttempts($key, $maxAttempts) — Check if the threshold has been reached.
  • RateLimiter::increment($key) — Record a hit manually (useful for incrementing only on failed login attempts rather than successful ones).
  • RateLimiter::remaining($key, $maxAttempts) — Check how many tries are left.
  • RateLimiter::clear($key) — Reset the counter immediately (for example, right after a user successfully logs in).

Production Best Practices

  1. Use Redis for your limiter cache store: By default, Laravel uses your default cache driver—which in newer installations is often the database store. Writing to SQL on every throttled HTTP request adds unnecessary database load. Dedicate Redis to rate limiting in config/cache.php:
    'limiter' => 'redis',
    

    If you use Redis, you can also call $middleware->throttleWithRedis() in bootstrap/app.php to use Redis’s atomic sliding-window implementation instead of basic cache keys.

  2. Avoid IP-only limits for authenticated endpoints: Thousands of mobile users or corporate employees often share a single public IP via NAT. Always key authenticated traffic by $request->user()->id (or API token ID) so one active user doesn’t lock out their entire office.
  3. Configure trusted proxies: If your app sits behind Cloudflare, AWS ALB, or Nginx, configure $middleware->trustProxies(...) in bootstrap/app.php. Otherwise, $request->ip() will return your load balancer’s internal IP, causing every visitor on the internet to share a single rate-limit bucket.
  4. Layer network-level protection for DDoS floods: Laravel’s throttle middleware still boots the PHP framework on every request. For massive volumetric attacks, pair Laravel’s application-aware limits with edge or web-server rate limiting (such as Nginx limit_req, HAProxy stick tables, or Cloudflare WAF rules) to drop abusive traffic before it reaches PHP.

Comments

Leave a Reply

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