Laravel API Rate Limiting: Complete Developer Guide

Written by

in

An unprotected API is a ticking clock. Whether it is a misconfigured client loop, a credential-stuffing script, or a sudden viral traffic spike, an unthrottled endpoint will quickly exhaust your database connections and bring your application down.

Laravel provides a clean, expressive rate-limiting layer out of the box. Built on top of your application’s cache driver, it lets you define granular traffic rules without reaching for external infrastructure like an API gateway on day one.

Defining Your First Rate Limiter

In modern Laravel applications (Laravel 11 and 12), rate limiters are configured inside the boot method of app/Providers/AppServiceProvider.php using the RateLimiter facade.

A standard rate limiter pairs a name with a closure that returns a Limit instance:

<?php

namespace AppProviders;

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

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

This rule allows 60 requests per minute. Notice the by() method—it defines the throttle key. If the request is authenticated, Laravel tracks usage against the user’s ID; if the user is a guest, it falls back to their IP address. Without by(), every user would share a single global bucket of 60 requests.

Attaching Limiters to Routes

Once defined, apply the limiter using the built-in throttle middleware in routes/api.php. Pass the name of your limiter after a colon:

use IlluminateSupportFacadesRoute;

Route::middleware(['throttle:api'])->group(function () {
    Route::get('/posts', [PostController::class, 'index']);
    Route::post('/posts', [PostController::class, 'store']);
});

When a client exceeds the limit, Laravel automatically halts execution and returns an HTTP 429 Too Many Requests response.

Dynamic and Tiered Limits

Real-world APIs rarely treat every user equally. Because RateLimiter::for() accepts the incoming $request, you can inspect the authenticated user, subscription plan, or request payload to calculate limits dynamically:

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

    if ($user?->isEnterprise()) {
        return Limit::none();
    }

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

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

Stacking Multiple Windows

Sometimes a single per-minute window isn’t enough. A user might stay under 60 requests per minute while still hammering your servers all day, or burst all 60 requests in a single second. You can enforce multiple thresholds simultaneously by returning an array of Limit instances:

RateLimiter::for('uploads', function (Request $request) {
    return [
        Limit::perSecond(2)->by($request->user()->id),
        Limit::perHour(50)->by($request->user()->id),
    ];
});

If either limit is breached, the request is rejected.

Customizing the 429 Response

By default, Laravel returns a generic JSON error message ({"message": "Too Many Requests."}) for API requests. If your API follows a specific error envelope—such as RFC 7807 Problem Details—chain the response() method onto your limit definition:

RateLimiter::for('strict-auth', function (Request $request) {
    return Limit::perMinute(5)
        ->by($request->input('email') . '|' . $request->ip())
        ->response(function (Request $request, array $headers) {
            return response()->json([
                'error' => 'rate_limit_exceeded',
                'message' => 'Too many login attempts. Please wait before trying again.',
                'retry_after_seconds' => $headers['Retry-After'] ?? 60,
            ], 429, $headers);
        });
});

Passing $headers into the JSON response preserves standard rate-limiting headers (X-RateLimit-Limit, X-RateLimit-Remaining, and Retry-After) so well-behaved API clients know exactly when to back off.

Production Considerations

  • Choose a fast cache store: Rate limiting hits your cache on every single API request. In production, set CACHE_STORE=redis (or Memcached) in your .env file. Using the database cache driver for high-traffic rate limiting will introduce lock contention and slow down every endpoint.
  • Configure trusted proxies: If your Laravel app sits behind a load balancer, Cloudflare, or AWS ALB, $request->ip() will return the proxy’s internal IP unless you configure trustProxies() in bootstrap/app.php. If left unconfigured, every guest user will share the load balancer’s IP and trigger false-positive lockouts.
  • Isolate sensitive endpoints: Keep expensive operations—like login routes, password resets, report exports, and AI generation endpoints—on their own dedicated limiters so a user cannot burn their general browsing quota to brute-force authentication.

Comments

Leave a Reply

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