HomeLARAVELHow do you implement rate limiting in Laravel?

How do you implement rate limiting in Laravel?

In Laravel, rate limiting is used to restrict the number of requests a user can make to your application in a given time frame. This is commonly used for APIs to prevent abuse. Laravel provides a very elegant way to handle this using middleware and the RateLimiter facade. Here’s a detailed explanation:


1. Using the throttle Middleware (Simplest Way)

Laravel comes with a built-in throttle middleware that you can attach to your routes.

Example:

Route::middleware('throttle:10,1')->group(function () {
    Route::get('/api/data', [ApiController::class, 'index']);
});

Explanation:

  • 10 → Maximum 10 requests
  • 1 → Time window in minutes
  • So, the user can make 10 requests per 1 minute.

2. Custom Rate Limiting Using RateLimiter Facade

Laravel 8+ allows defining custom rate limiters in App\Providers\RouteServiceProvider.

Step 1: Open RouteServiceProvider.php

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

Step 2: Define a custom limiter in the boot() method:

public function boot()
{
    $this->configureRateLimiting();

    $this->routes(function () {
        Route::middleware('api')
            ->prefix('api')
            ->group(base_path('routes/api.php'));
    });
}

protected function configureRateLimiting()
{
    RateLimiter::for('global', function ($request) {
        return Limit::perMinute(60)->by($request->ip());
    });

    RateLimiter::for('login', function ($request) {
        return Limit::perMinute(5)->by($request->input('email'));
    });
}

Explanation:

  • Limit::perMinute(60) → 60 requests per minute.
  • by($request->ip()) → Rate limiting per IP address.
  • You can also use a user identifier for authenticated users ($request->user()->id).

Step 3: Apply custom limiter to a route:

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

3. Handling Too Many Requests

If a user exceeds the limit, Laravel automatically returns a 429 HTTP status code with a message:

{
    "message": "Too Many Attempts."
}

You can customize this by catching the ThrottleRequestsException in your App\Exceptions\Handler.


4. Advanced Options

You can define more complex limits:

  • Dynamic limits: Based on user type or role
  • Different time windows: perSecond(), perHour(), perDay()
  • Multiple keys: Track multiple identifiers simultaneously

Example:

RateLimiter::for('uploads', function ($request) {
    return Limit::perHour(100)
        ->by($request->user()->id ?: $request->ip())
        ->response(function () {
            return response()->json(['error' => 'Upload limit reached'], 429);
        });
});

Which Laravel feature handles rate limiting?

laravel provides rate limiting using the RateLimiter facade and middleware like throttle.

What is the default rate limiting middleware in Laravel?

The throttle middleware is used. Example:

Route::middleware('throttle:60,1')->group(function () { // Routes here });

Where is rate limiting defined in Laravel?

In App\Providers\RouteServiceProvider, inside the configureRateLimiting() method.

What are different ways to identify users in rate limiting?

By User ID (for logged-in users)
By IP address (for guests)
By custom keys (like API token)

How do you apply different rate limits for different routes?

You can define named limiters and apply them:

Route::middleware('throttle:api')->get('/user', function () { return auth()->user(); });

What happens when the rate limit is exceeded in Laravel?

Laravel returns a 429 Too Many Requests response with headers like:
Retry-After
X-RateLimit-Limit
X-RateLimit-Remaining

How to reset or clear rate limiting in Laravel?

You can clear cache (since rate limits are stored in cache/Redis):

php artisan cache:clear

Which storage does Laravel use for rate limiting?

Laravel uses cache drivers like Redis, Memcached, or Database to store rate limit counters.

Can you implement sliding window rate limiting in Laravel?

Laravel by default uses fixed window. For sliding window or more advanced techniques, you can extend RateLimiter with custom logic or use Redis-based solutions.

What is the difference between Limit::perMinute() and Limit::perHour()?

perMinute() allows X requests per minute.
perHour() allows X requests per hour.
Example:

Limit::perMinute(60); Limit::perHour(1000);

Summary

  1. Use throttle middleware for simple limits.
  2. Use RateLimiter facade for custom or dynamic limits.
  3. Automatically returns 429 Too Many Requests.
  4. Can be applied to IP, user, email, or any identifier.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

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