Laravel Rate Limiting Tutorial & Best Practices

Written by

in

Rate limiting is a foundational pillar of modern web application security and architecture. Without it, your APIs and login endpoints are vulnerable to brute-force attacks, scraping, credential stuffing, and Denial of Service (DoS) floods.

Laravel provides a robust, elegant, and highly flexible rate-limiting system out of the box. Whether you need to protect a public-facing API endpoint or secure your authentication routes, Laravel makes throttling traffic straightforward using its middleware and the RateLimiter facade.


1. The Basics: How Laravel Rate Limiting Works

At its core, Laravel’s rate limiting relies on the cache driver (such as Redis, Memcached, or database cache) to track incoming requests from clients. It uses the ThrottleRequests middleware to intercept requests, count them against a specific key (usually an IP address or authenticated user ID), and return an HTTP 429 Too Many Requests response if the limit is exceeded.

Out of the box, Laravel includes a global api rate limiter defined in your application service provider.


2. Defining Rate Limiters

Rate limiters are typically defined inside the boot method of your AppProvidersAppServiceProvider (or via routing service providers in older Laravel versions) using the RateLimiter facade.

Here is how you can define custom limiters for different use cases:

use IlluminateCacheRateLimitingLimit;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRateLimiter;

public function boot(): void
{
    // Standard IP-based limiter (60 requests per minute)
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });

    // Strict limiter for login routes (5 requests per minute)
    RateLimiter::for('login', function (Request $request) {
        return Limit::perMinute(5)->by($request->input('email').$request->ip());
    });

    // Dynamic limits based on user subscription tiers
    RateLimiter::for('uploads', function (Request $request) {
        $user = $request->user();

        if ($user && $user->isPremium()) {
            return Limit::perMinute(120);
        }

        return Limit::perMinute(30);
    });
}

Key Methods on the Limit Class:

  • Limit::perMinute($max) / Limit::perHour($max) / Limit::perDay($max): Sets the time window and maximum allowed requests.
  • by($key): Defines the unique identifier to track. By combining user IDs and IPs, you prevent malicious actors from spoofing single IPs to bypass limits.

3. Applying Rate Limiters to Routes

Once defined, you can attach your rate limiters to routes or route groups using the throttle middleware.

use IlluminateSupportFacadesRoute;

// Apply the default 'api' limiter
Route::middleware('throttle:api')->group(function () {
    Route::get('/user', [UserController::class, 'show']);
});

// Apply a custom limiter named 'login'
Route::post('/login', [AuthController::class, 'login'])
    ->middleware('throttle:login');

// Inline rate limiting without pre-defining in AppServiceProvider
Route::middleware('throttle:10,1')->get('/fast-endpoint', function () {
    return response()->json(['message' => 'Success']);
});

(Note: throttle:10,1 allows 10 requests per 1 minute).


4. Customizing Responses and Headers

When a user exceeds their rate limit, Laravel automatically responds with a 429 Too Many Requests status code. You can customize the response message or headers using response() callbacks:

RateLimiter::for('downloads', function (Request $request) {
    return Limit::perHour(10)->by($request->user()->id)->response(function (Request $request, array $headers) {
        return response()->json([
            'message' => 'You have downloaded too many files. Please try again later.',
            'retry_after' => $headers['Retry-After'] ?? 3600,
        ], 429, $headers);
    });
});

Standard Rate Limit Headers

Laravel automatically attaches helpful headers to responses so clients know their current status:

  • X-RateLimit-Limit: The maximum number of requests allowed during the window.
  • X-RateLimit-Remaining: The number of requests remaining in the current window.
  • Retry-After: (Present on 429 responses) The number of seconds until the client can make requests again.

5. Best Practices for Production

  1. Use Redis: For high-traffic applications, database-driven cache drivers can become a bottleneck when tracking rate limits. Use Redis for lightning-fast atomic increments and expiration handling.
  2. Combine Identifiers: For sensitive endpoints like login or password resets, throttle by both IP address and user input (such as email) to prevent distributed botnets from guessing a single user’s credentials across multiple IPs.
  3. Handle 429s Gracefully in Frontend Apps: Ensure your frontend or API consumers gracefully handle HTTP 429 errors by reading the Retry-After header and backing off accordingly.

Comments

Leave a Reply

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