Rate limiting in Laravel is a built-in traffic control and abuse-prevention system backed by your application’s cache. It lets you restrict how often a user, IP address, token, or custom key can hit an HTTP endpoint or execute a discrete action within a given time window.
Whether you are defending a login form against credential stuffing, enforcing fair usage across API tiers, or throttling expensive background actions like sending emails or generating reports, Laravel gives you both declarative route middleware and a low-level RateLimiter facade.
Why Rate Limiting Matters in Laravel
An unthrottled endpoint turns any client—or bot—into an unscheduled load test:
- Protects infrastructure: Stops sudden request spikes from saturating CPU, memory, database connections, or downstream third-party APIs.
- Blocks brute-force and scraping abuse: Slows down automated login guessing, OTP/password-reset floods, and aggressive content scraping.
- Preserves fairness across tiers: Prevents one noisy tenant or script from degrading response times for everyone else.
- Encourages well-behaved clients: Returns standard
429 Too Many Requestsresponses with retry metadata so API consumers can back off cleanly.
How Laravel Rate Limiting Works Under the Hood
Laravel tracks attempt counts and expiration windows using your configured cache store. Every time a limited key is hit, Laravel increments a counter in the cache with a time-to-live (TTL) matching the decay window. Once the count exceeds the allowed threshold inside that window, requests are rejected with HTTP 429 (ThrottleRequestsException) until the window resets.
Choosing the Right Cache Store
In modern Laravel setups, the default cache store may be database unless configured otherwise. Using a database cache for high-traffic rate limiting adds extra write load on every request. In config/cache.php, you can dedicate a fast store (such as redis) specifically to the rate limiter without changing your default cache store:
// config/cache.php
'default' => env('CACHE_STORE', 'database'),
'limiter' => env('CACHE_LIMITER_STORE', 'redis'),
Defining Named Rate Limiters (RateLimiter::for)
Instead of hardcoding magic numbers across dozens of routes, define named limiters inside AppServiceProvider::boot() using RateLimiter::for() and IlluminateCacheRateLimitingLimit:
<?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 $request->user()
? Limit::perMinute(120)->by($request->user()->id)
: Limit::perMinute(30)->by($request->ip());
});
RateLimiter::for('login', function (Request $request) {
$email = (string) $request->input('email');
return Limit::perMinute(5)->by($request->ip().'|'.strtolower($email));
});
}
}
Keying by Identity, Not Just IP
IP-based limits alone have trade-offs: an entire corporate office or mobile carrier NAT can share one IP, while an attacker can rotate IPs or hit an account from multiple addresses.
- Authenticated users: Key by
$request->user()->idso limits follow the account rather than a shifting IP. - Login & auth flows: Combine the client IP and normalized email/username so a single bad password attempt doesn’t lock out everyone on that network, while targeted attacks against one account still get throttled.
- API tokens / tenants: Key by token ID or tenant identifier when serving multi-tenant SaaS traffic.
Layering Limits and Customizing Responses
A single per-minute cap stops sharp bursts, but an automated client sending steady traffic just under the per-minute ceiling can still drain resources over hours. You can return an array of Limit instances from RateLimiter::for() to enforce short-burst and sustained windows together:
use IlluminateCacheRateLimitingLimit;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRateLimiter;
RateLimiter::for('exports', function (Request $request) {
$key = (string) ($request->user()?->id ?? $request->ip());
return [
Limit::perMinute(10)->by('exports:minute:'.$key),
Limit::perHour(60)->by('exports:hour:'.$key),
];
});
Give each limit a distinct ->by(...) prefix so separate windows do not collide on the same underlying cache key.
Customizing the 429 Response
When a limit is exceeded, you can customize the response payload with ->response() while keeping Laravel’s standard rate-limit and Retry-After headers intact:
use IlluminateCacheRateLimitingLimit;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRateLimiter;
RateLimiter::for('webhooks', function (Request $request) {
return Limit::perMinute(30)
->by($request->ip())
->response(function (Request $request, array $headers) {
return response()->json([
'error' => 'rate_limit_exceeded',
'message' => 'Too many webhook requests. Retry after the indicated window.',
], 429, $headers);
});
});
Applying Limiters to Routes
Attach a named limiter to routes or route groups using the throttle:<name> middleware:
use AppHttpControllersAuthController;
use AppHttpControllersExportController;
use IlluminateSupportFacadesRoute;
Route::middleware('throttle:login')
->post('/login', [AuthController::class, 'login']);
Route::middleware(['auth:sanctum', 'throttle:exports'])
->post('/reports/export', [ExportController::class, 'store']);
If you need a quick inline cap without registering a named limiter, Laravel also supports direct numeric syntax such as throttle:60,1 (60 attempts per 1 minute). Named limiters in RateLimiter::for() are generally cleaner once rules grow beyond a basic fixed cap.
Rate Limiting Non-HTTP Actions with RateLimiter
Rate limiting is not limited to incoming HTTP requests. You can use RateLimiter::attempt() inside queued jobs, console commands, domain services, or Livewire/controller actions to protect any side effect—such as SMS codes, outbound emails, or external API calls:
use IlluminateSupportFacadesRateLimiter;
$executed = RateLimiter::attempt(
key: 'send-otp:'.$user->id,
maxAttempts: 3,
callback: function () use ($user) {
$user->sendVerificationCode();
},
decaySeconds: 300
);
if (! $executed) {
$seconds = RateLimiter::availableIn('send-otp:'.$user->id);
return back()->withErrors([
'otp' => "Too many code requests. Try again in {$seconds} seconds.",
]);
}
For finer manual control, the RateLimiter facade also provides:
tooManyAttempts($key, $maxAttempts)to check if a quota is exhausted.remaining($key, $maxAttempts)to inspect remaining hits.hit($key, $decaySeconds)orincrement($key, $amount, $decaySeconds)to record usage manually.availableIn($key)to retrieve the seconds remaining before reset.clear($key)to reset a counter early (for example, after a user completes verification or reads a message).
Practical Production Checklist
| Area | Recommendation |
|---|---|
| Cache backend | Use Redis or Memcached (cache.limiter) in production rather than high-churn database writes. |
| Reverse proxies | Configure trusted proxies properly so $request->ip() reflects the real client IP rather than the proxy IP. |
| Tiered quotas | Give authenticated or paid users higher limits than anonymous guests. |
| Layered windows | Pair short burst limits (per second/minute) with longer caps (per hour/day) on expensive endpoints. |
| Automated tests | Write feature tests asserting 200/201 up to the limit and 429 on the next request so middleware is never accidentally removed. |
Leave a Reply