Laravel API Rate Limiting: Setup & Best Practices

Written by

in

Mastering Laravel API Rate Limiting: Protecting Your Endpoints Without Punishing Users

Every public API eventually meets two types of traffic: legitimate users building cool integrations, and runaway loops, scrapers, or brute-force bots hammering your endpoints until your database melts.

Rate limiting is your first line of defense. Rather than manually tracking request timestamps in middleware or writing custom Redis scripts from scratch, Laravel ships with an expressive, battle-tested rate limiting system right out of the box. Whether you need a simple 60-requests-per-minute cap or multi-tiered quotas based on a user’s SaaS subscription plan, Laravel makes it remarkably clean to configure.


How Laravel Rate Limiting Works Under the Hood

At its core, Laravel’s rate limiter pairs the RateLimiter facade with your application’s cache store (such as Redis, Memcached, or Database) to track request counts inside a rolling or fixed time window.

When a request hits a throttled route:

  1. Laravel generates a unique limiter key (typically combining the limiter name with a user ID or IP address).
  2. It checks the cache to see how many attempts that key has made within the decay window.
  3. If the count is under the limit, the counter increments and the request proceeds.
  4. If the limit is exceeded, Laravel immediately halts execution and returns an HTTP 429 Too Many Requests response, complete with standard rate-limit headers.

Standard HTTP Headers Returned

Whenever a route uses Laravel’s throttle middleware, clients receive helpful telemetry headers automatically:

Header Purpose
X-RateLimit-Limit Maximum requests allowed in the current window.
X-RateLimit-Remaining Number of requests left before throttling kicks in.
Retry-After (On 429 responses) Seconds the client must wait before retrying.
X-RateLimit-Reset (On 429 responses) Unix timestamp when the quota resets.

(Citation:)


Step 1: Defining Custom Rate Limiters

In modern Laravel applications (Laravel 11, 12, and 13+), rate limiters are defined inside the boot() method of your AppProvidersAppServiceProvider using RateLimiter::for().

<?php

namespace AppProviders;

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

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

Notice the ->by(...) method. If the user is authenticated, we track their quota by their User ID—meaning they won’t get blocked just because they share office Wi-Fi with twenty coworkers. If they are a guest, we fall back to their IP address.


Step 2: Applying Limiters to Routes

Once named, you attach a limiter to individual routes or route groups using the throttle middleware.

use IlluminateSupportFacadesRoute;
use AppHttpControllersProjectController;

// Apply the 'api' limiter defined in AppServiceProvider
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
    Route::apiResource('projects', ProjectController::class);
});

// Quick inline syntax without defining a named limiter (5 attempts per 1 minute)
Route::post('/login', [AuthController::class, 'login'])
    ->middleware('throttle:5,1');

Pro Tip: While throttle:60,1 works fine for quick prototypes, named limiters (throttle:api) keep your route files clean and allow dynamic logic without touching routing definitions.


Real-World Patterns for Production APIs

A single global limit rarely fits every endpoint. Heavy export endpoints, authentication routes, and paid subscription tiers all deserve tailored rules.

1. Tiered Limits by Subscription Plan

Reward paying customers with higher throughput while keeping free-tier traffic predictable:

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

    return match (true) {
        $user?->isEnterprise() => Limit::perMinute(1000)->by($user->id),
        $user?->isPro()        => Limit::perMinute(300)->by($user->id),
        $user !== null         => Limit::perMinute(60)->by($user->id),
        default                => Limit::perMinute(20)->by($request->ip()),
    };
});

2. Stacking Multiple Limits (Burst + Daily Quotas)

Returning an array of Limit instances enforces all of them simultaneously. This is ideal for preventing short-term bursts while also capping total daily consumption:

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

    return [
        // Prevent rapid-fire spam (max 5 per minute)
        Limit::perMinute(5)->by($key),
        // Cap daily compute costs (max 100 per day)
        Limit::perDay(100)->by($key),
    ];
});

3. Customizing the 429 JSON Response

By default, Laravel returns a generic "Too Many Attempts." message. For a polished developer experience, chain the ->response() callback onto your limit to return structured JSON matching your API’s error schema:

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

Passing $headers as the third argument to response()->json() ensures Retry-After and X-RateLimit-* headers remain intact.


Programmatic Rate Limiting Outside HTTP Routes

Sometimes you need to throttle actions that aren’t tied directly to an HTTP route—such as sending SMS verification codes, triggering webhooks, or dispatching expensive queued jobs. You can invoke RateLimiter::attempt() anywhere in your codebase:

use IlluminateSupportFacadesRateLimiter;

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

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

(Citation:)


Production Best Practices

  • Use Redis in Multi-Server Setups: File or database cache drivers buckle under high concurrency and won’t share state across load-balanced web servers. Set 'limiter' => 'redis' in config/cache.php so all app nodes evaluate atomic counters against a single Redis instance.
  • Trust Your Proxies: If your API sits behind Cloudflare, AWS ALB, or Nginx, configure trustProxies in bootstrap/app.php. Otherwise, $request->ip() will return your load balancer’s internal IP, causing one abusive user to get your entire user base throttled.
  • Test Your Limits: Use Laravel’s HTTP test helpers ($this->getJson('/api/...')) in a loop alongside Carbon::travel() to verify that 429 responses trigger at the exact boundary and reset cleanly after the decay window expires.

Comments

Leave a Reply

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