Rate Limiting for API Requests
Rate limiting protects an API from abuse, accidental infinite loops in client code, and traffic spikes, by capping how many requests a client can make within a given time window.
The throttle Middleware
Laravel ships with a throttle middleware that can be applied to any route or route group.
Route::middleware('throttle:60,1')->group(function () {
Route::get('/posts', [PostController::class, 'index']);
});
This example allows 60 requests per 1 minute per client.
Named Rate Limiters
For more control, rate limiters can be defined in a service provider using the RateLimiter facade, keyed by user ID or IP address.
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(100)->by($request->user()?->id ?: $request->ip());
});
What Clients See When Limited
- A 429 Too Many Requests response once the limit is hit
- X-RateLimit-Limit and X-RateLimit-Remaining headers on every response
- A Retry-After header telling the client when to try again
With the API itself secured and throttled, the course now shifts from request/response handling to background processing, starting with events and listeners.
Where Limiters Live and How Routes Use Them
In current Laravel versions, named limiters are usually defined in the boot() method of AppServiceProvider; older projects keep them in RouteServiceProvider. A route then refers to the limiter by name with throttle:name.
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
public function boot(): void
{
RateLimiter::for('uploads', function (Request $request) {
$key = $request->user()?->id ?: $request->ip();
if ($request->user()?->is_premium) {
return Limit::perMinute(60)->by('min:'.$key);
}
return [
Limit::perMinute(10)->by('min:'.$key),
Limit::perDay(200)->by('day:'.$key),
];
});
}
// routes/api.php
Route::post('/uploads', [UploadController::class, 'store'])
->middleware(['auth:sanctum', 'throttle:uploads']);
Here is what happens on each request: the middleware calls your closure, builds a cache key from the value passed to by(), increases the counter for that key and compares it with the allowed number. If the counter is still under the limit, the request continues and the remaining count is sent back in the headers. Once it goes over, the request stops with a 429 before your controller ever runs.
Returning an array applies several limits at once. Each limit needs its own key prefix, otherwise they would share one counter and the daily cap would never work as intended. The is_premium attribute here stands for whatever plan field your users table has.
Customising the 429 Response
By default, Laravel answers with a generic "Too Many Attempts" message. For a public API, a clear JSON body helps client developers fix their integration:
return Limit::perMinute(10)
->by($key)
->response(function (Request $request, array $headers) {
return response()->json([
'message' => 'Rate limit reached. Please retry later.',
], 429, $headers);
});
Passing $headers through keeps the Retry-After and rate-limit headers, so well-behaved clients can wait the right amount of time automatically.
Protecting a Login Form With Manual Limits
For actions that are not simple routes, use the RateLimiter facade directly. A common defensive pattern slows down repeated failed logins for one account from one IP address:
$key = 'login:'.Str::lower($request->input('email')).'|'.$request->ip();
if (RateLimiter::tooManyAttempts($key, 5)) {
$seconds = RateLimiter::availableIn($key);
return back()->withErrors([
'email' => "Too many attempts. Try again in {$seconds} seconds.",
]);
}
if (! Auth::attempt($request->only('email', 'password'))) {
RateLimiter::hit($key, 60); // count the failure for 60 seconds
return back()->withErrors(['email' => 'Invalid credentials.']);
}
RateLimiter::clear($key); // reset after a successful login
Laravel's starter kits use a very similar approach, so reviewing their login request class is a good way to see this in a complete flow.
Production Notes and Testing
- Use a shared cache store. Counters live in the cache. With several app servers, a store such as Redis keeps one counter per client; a local file cache would give each server its own count.
- Know your real client IP. Behind a load balancer or CDN, configure trusted proxies so
$request->ip()is not the proxy address for every user. - Limit by user when you can. Many people can share one office or mobile network IP.
- Test it. A feature test can send requests in a loop and assert that the next one returns
429.
for ($i = 0; $i < 60; $i++) {
$this->getJson('/api/posts')->assertOk();
}
$this->getJson('/api/posts')->assertStatus(429);
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.