Laravel Rate Limiting: Complete Guide & Best Practices

Written by

in

Controlling the Flood: A Complete Guide to Rate Limiting in Laravel

Every public-facing web application eventually faces an unwanted surge of traffic. Sometimes it is malicious—credential stuffing bots hammering a login endpoint or scrapers draining server resources. Other times, it is accidental—a partner’s webhook retry loop misfiring or a frontend useEffect hook accidentally firing hundreds of API requests per second.

Without a bouncer at the door, these bursts degrade performance for legitimate users and can bring an entire database to its knees.

Laravel provides a clean, expressive, and Redis-backed rate-limiting layer out of the box. Rather than burying traffic rules inside web server configurations, Laravel lets you define dynamic, user-aware throttling directly in your application code.


How Laravel’s Rate Limiter Works Under the Hood

At its core, Laravel’s RateLimiter facade uses a sliding window counter backed by your configured cache driver.

When a request hits a throttled route, Laravel generates a unique cache key—typically derived from the limiter’s name combined with the user’s ID or IP address. It increments a counter stored under that key and sets an expiration time (TTL). If the counter exceeds your defined threshold before the TTL expires, Laravel immediately intercepts the request and throws an IlluminateHttpExceptionsThrottleRequestsException, returning an HTTP 429 Too Many Requests response.

Production Tip: Always configure Redis as your cache driver (or specifically as your rate-limiter cache store) in production. File or database cache drivers introduce disk I/O bottlenecks and race conditions under high concurrency, whereas Redis handles atomic increments in memory in microseconds.


Defining Rate Limiters

Rate limiters are registered using the RateLimiter::for() method, typically inside the boot() method of your AppProvidersAppServiceProvider.

1. Basic Per-Minute Throttling

The simplest rate limiter restricts all incoming requests to a fixed number per minute, segmented by IP address:

use IlluminateCacheRateLimitingLimit;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRateLimiter;

public function boot(): void
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->ip());
    });
}

2. Dynamic Tiered Limits

Because the closure receives the incoming IlluminateHttpRequest, you can inspect the authenticated user and apply different rules based on subscription tiers, roles, or IP addresses:

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

    if (! $user) {
        // Strict limit for unauthenticated guests
        return Limit::perMinute(20)->by($request->ip());
    }

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

Notice how authenticated users are keyed by $user->id rather than $request->ip(). This prevents users sharing a corporate VPN or university Wi-Fi network from exhausting each other’s quotas.

3. Multi-Dimensional (Stacked) Limits

Sometimes a single per-minute rule isn’t enough. A user might stay under 60 requests per minute while still violating a daily quota, or an attacker might rotate accounts from a single IP. You can return an array of Limit instances—if any limit in the array is breached, the request is rejected:

RateLimiter::for('uploads', function (Request $request) {
    return [
        // Burst protection: max 5 uploads per minute per user
        Limit::perMinute(5)->by($request->user()->id),
        
        // Daily cap: max 50 uploads per day per user
        Limit::perDay(50)->by($request->user()->id),
        
        // Infrastructure protection: max 200 uploads per minute from a single IP
        Limit::perMinute(200)->by($request->ip()),
    ];
});

Applying Rate Limiters to Routes

Once defined, attach your named limiter to routes or route groups using Laravel’s built-in throttle middleware:

use IlluminateSupportFacadesRoute;

// Apply to a single route
Route::post('/login', [AuthController::class, 'login'])
    ->middleware('throttle:login');

// Apply to an entire API route group
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
    Route::get('/projects', [ProjectController::class, 'index']);
    Route::post('/projects', [ProjectController::class, 'store']);
});

Inline Ad-Hoc Throttling

For quick prototypes or isolated endpoints, you can pass numeric parameters directly to the middleware without defining a named limiter in AppServiceProvider:

// Allow 10 requests per 1 minute
Route::post('/contact', ContactController::class)
    ->middleware('throttle:10,1');

Customizing the 429 Response

By default, Laravel returns a generic HTML error page or a basic JSON payload ({"message": "Too Many Requests."}) along with standard HTTP headers:

  • X-RateLimit-Limit: The maximum number of requests allowed in the window.
  • X-RateLimit-Remaining: How many requests the client has left.
  • Retry-After: Seconds remaining until the rate limit resets (sent only when throttled).

To return a custom JSON structure—such as including upgrade links or structured error codes—chain the response() method onto your Limit definition:

RateLimiter::for('search', function (Request $request) {
    return Limit::perMinute(30)
        ->by($request->user()?->id ?: $request->ip())
        ->response(function (Request $request, array $headers) {
            return response()->json([
                'error'       => 'rate_limit_exceeded',
                'message'     => 'You have exceeded your search quota. Please slow down.',
                'retry_after' => (int) ($headers['Retry-After'] ?? 60),
            ], 429, $headers);
        });
});

Passing $headers as the third argument to response()->json() ensures clients still receive Retry-After and X-RateLimit-* metadata so well-behaved SDKs can back off automatically.


Programmatic Rate Limiting Outside HTTP Routes

Rate limiting is not restricted to HTTP middleware. You can invoke RateLimiter::attempt() anywhere in your codebase—such as inside console commands, queue listeners, or Livewire actions—to throttle expensive operations like sending SMS verification codes or calling billable third-party APIs:

use IlluminateSupportFacadesRateLimiter;

$executed = RateLimiter::attempt(
    key: 'send-sms:' . $user->id,
    maxAttempts: 3,
    callback: function () use ($user) {
        $user->sendVerificationSms();
    },
    decaySeconds: 300 // 5-minute window
);

if (! $executed) {
    $seconds = RateLimiter::availableIn('send-sms:' . $user->id);
    throw new RuntimeException("Too many SMS requests. Try again in {$seconds} seconds.");
}

Manual Counter Control

When building custom authentication flows, you often want to increment the failure counter only when an action fails rather than counting valid requests:

$key = 'login-attempts:' . $request->ip();

if (RateLimiter::tooManyAttempts($key, maxAttempts: 5)) {
    $seconds = RateLimiter::availableIn($key);
    abort(429, "Account locked. Try again in {$seconds} seconds.");
}

if (! Auth::attempt($credentials)) {
    // Record a failed attempt that expires in 60 seconds
    RateLimiter::hit($key, decaySeconds: 60);
    return back()->withErrors(['email' => 'Invalid credentials.']);
}

// Clear failed attempts upon successful login
RateLimiter::clear($key);

Throttling Outbound Queued Jobs

While HTTP rate limiters protect your app from incoming traffic, Laravel also includes a ThrottlesExceptions and RateLimited job middleware to protect external APIs from your own queue workers.

If a third-party payment gateway allows only 10 API calls per second, configure a limiter in AppServiceProvider:

RateLimiter::for('stripe-api', function (object $job) {
    return Limit::perSecond(10);
});

Then attach IlluminateQueueMiddlewareRateLimited to your job class:

use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationQueueQueueable;
use IlluminateQueueMiddlewareRateLimited;

class SyncStripeInvoice implements ShouldQueue
{
    use Queueable;

    public function middleware(): array
    {
        return [new RateLimited('stripe-api')];
    }

    public function handle(): void
    {
        // Safely executes at most 10 times per second across all workers
    }
}

When the limit is reached, the job is automatically released back onto the queue with an appropriate delay rather than failing or throwing an exception.


Common Pitfalls to Avoid

Pitfall Why It Happens How to Fix It
Wrong client IPs behind load balancers $request->ip() returns the proxy’s internal IP instead of the user’s real IP, throttling everyone together. Configure TrustProxies in bootstrap/app.php so Laravel reads X-Forwarded-For accurately.
Collision between limiter keys Two different limiters use $request->ip() without distinct limiter names. Always use named limiters (RateLimiter::for('name', ...)), which automatically prefix cache keys.
Throttling health checks or webhooks Global api middleware throttles AWS/Kubernetes health checks or Stripe webhook bursts. Exclude /up health routes and give verified webhooks their own dedicated, high-throughput limiter.
Over-strict limits during automated tests Feature tests hit the same endpoint dozens of times in milliseconds and fail with 429. Disable throttling selectively in tests via $this->withoutMiddleware(ThrottleRequests::class) or mock RateLimiter.

Thoughtful rate limiting is one of the highest-leverage defenses you can add to a Laravel application. By combining Redis-backed storage, user-aware keys, and job-level throttling, you ensure your application stays responsive under pressure—whether that pressure comes from a sudden viral spike or a misbehaving script.

Comments

Leave a Reply

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