API Design
Laravel Rate Limiting Guide
Rate limiting a Laravel 13 API from both ends: switching it on, keying and layering limits, a 429 a client can act on, the IETF RateLimit headers, and a client that waits instead of hammering.
Nov 202613 min read
This article exists because my own 404 page suggested it. I’d just added one to this site, and to test it I made up an address that didn’t exist, /articles/laravel-rate-limiting-guide/. The page dutifully pre-filled the search box with “laravel rate limiting guide”, and I sat there thinking that actually sounded like something worth reading.
So here it is. Most rate limiting guides for Laravel stop at throttle:60,1, and that’s maybe a third of the story. A rate limit is a contract between your API and every client that calls it, and a contract has two sides. The server has to enforce it fairly and say what the terms are, and the client has to read those terms and back off instead of hammering you until it gets banned. I want to walk through both ends.
Laravel 13 throughout:
laravel new rate-limitsphp artisan install:apiYour API probably isn’t rate limited
This is the part that surprised me when I went looking. If you started a project on Laravel 11 or later, your API routes have no rate limit at all unless you’ve switched one on yourself.
Up to Laravel 10, the skeleton’s HTTP kernel put a throttle on the api middleware group, and from Laravel 8 that throttle used an api limiter defined in RouteServiceProvider. When the slimmer application skeleton arrived in Laravel 11, both files went, and the throttle went with them. The api group now only gets a throttle if you ask for one, and php artisan install:api doesn’t ask for you. Run php artisan route:list -v on a fresh app and the api/user route shows the api group and Sanctum’s auth middleware, and no throttle anywhere.
Switching it on is one line in bootstrap/app.php:
->withMiddleware(function (Middleware $middleware): void { $middleware->throttleApi();})But that line on its own breaks every API request. throttleApi() adds throttle:api to the group, and there’s no limiter called api any more, so the middleware throws a MissingRateLimiterException and every request becomes a 500. You need to define the limiter as well, in the boot method of your AppServiceProvider:
use Illuminate\Cache\RateLimiting\Limit;use Illuminate\Http\Request;use Illuminate\Support\Facades\RateLimiter;
public function boot(): void{ RateLimiter::for('api', function (Request $request) { return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip()); });}Now every response from an API route carries two headers, and the sixty-first request in a minute gets a 429:
X-RateLimit-Limit: 60X-RateLimit-Remaining: 59If you take one thing from this article, take this section. Go and check your bootstrap/app.php.
Who you count against
The by() call is the decision that matters most, because it decides whose requests share a counter. Get it wrong one way and one noisy client uses up everybody’s allowance. Get it wrong the other way and nobody is limited at all.
The limiter above counts an authenticated user by their ID and everyone else by IP address. That’s a sensible default, and it’s what Laravel 10 used to ship, but the IP half has two problems worth knowing about before you rely on it.
The first is that $request->ip() is only the client’s address if Laravel trusts the proxy in front of it. Behind a load balancer or a CDN, without trustProxies configured, every request appears to come from the load balancer, and your whole user base shares one counter of sixty requests a minute. Configure it for the proxies you actually run behind rather than with a wildcard. Trust every address, and depending on how your proxy handles the header, a client may be able to send its own X-Forwarded-For and pick a fresh IP for every request.
The second is that an IP address isn’t a person. An office, a university or a mobile network can put thousands of people behind one address, and one person with a few cloud machines has as many addresses as they like. If that matters for your API, I wrote about limiting by device instead in Server-Side Rate Limiting in Laravel with Fingerprint.dev.
Because the limiter is a closure, it can also give different callers different limits. A signed-in user is someone you can identify and contact, so they can have more room than an anonymous caller:
RateLimiter::for('api', function (Request $request) { return $request->user() ? Limit::perMinute(120)->by($request->user()->id) : Limit::perMinute(30)->by($request->ip());});The same shape works for plans. Read the limit from the user, their team or their subscription, and return the Limit that matches.
Layering limits
A per-minute limit stops a burst. It doesn’t stop a client that sends fifty-nine requests a minute, all day. For that you want a second, longer window, and a limiter can return an array of limits that all have to pass:
RateLimiter::for('api', function (Request $request) { $key = $request->user()?->id ?: $request->ip();
return [ Limit::perMinute(60)->by('minute:'.$key), Limit::perDay(1000)->by('day:'.$key), ];});The prefixes on those keys used to matter a lot. Laravel builds the cache key for each limit from the limiter’s name and the by() value, so two limits with the same by() value would share one counter, and the docs still tell you to make each one unique. I went to prove what goes wrong if you don’t, and couldn’t. Laravel 13 spots limits with duplicate keys and quietly rewrites them to a fallback that includes the limit and the window, so they get separate counters anyway.
I’d still prefix them, because a key you chose is a key you can find. When a customer has locked themselves out and you want to reset their daily count, you need the cache key, and the throttle middleware stores it as an MD5 of the limiter’s name and your by() value run together:
RateLimiter::clear(md5('api'.'day:'.$user->id));That’s easy enough to write from a prefix you picked. Reconstructing the fallback key Laravel generated for you, with the limit and window baked into it, isn’t something I want to be doing in a hurry.
Only counting what matters
Not every request deserves to count. The classic case is a login endpoint, where you want to slow down someone guessing passwords without punishing a user who gets their password right first time. after() takes the response and decides whether this request counts at all:
use Symfony\Component\HttpFoundation\Response;
RateLimiter::for('login', function (Request $request) { return Limit::perMinute(5) ->by(strtolower((string) $request->input('email')).'|'.$request->ip()) ->after(fn (Response $response) => $response->getStatusCode() === 422);});Route::post('/login', LoginController::class)->middleware('throttle:login');This assumes a failed login comes back as a 422, the way a validation error does, so adjust the check to whatever yours returns. Only failed attempts are counted, so five wrong passwords in a minute locks that email from that address, and a successful login never touches the counter. Keying on the email and the IP together means an attacker can’t lock a real user out from somewhere else, which a key on the email alone would let them do.
A 429 a client can act on
When a limit is hit, Laravel throws a ThrottleRequestsException, and with the api/* JSON rendering a new app has set up in bootstrap/app.php, the client gets this (with debug off, or there’s a stack trace in there too):
HTTP/1.1 429 Too Many RequestsRetry-After: 60X-RateLimit-Limit: 60X-RateLimit-Remaining: 0X-RateLimit-Reset: 1795171750
{"message": "Too Many Attempts."}The headers are the useful part. Retry-After is defined by HTTP itself, so it’s the one header a client can rely on meaning the same thing from every API. The body says nothing a program can use.
I’d make the body a Problem Details document, the same as every other error the API returns. response() on the limit lets you build it, and it’s handed the headers Laravel would have sent, so you keep Retry-After:
return Limit::perMinute(60) ->by($request->user()?->id ?: $request->ip()) ->response(function (Request $request, array $headers) { return response()->json([ 'type' => 'https://apiguide.dev/errors/rate-limit-exceeded', 'title' => 'Rate Limit Exceeded', 'status' => 429, 'detail' => "Too many requests. Try again in {$headers['Retry-After']} seconds.", ], 429, [ ...$headers, 'Content-Type' => 'application/problem+json', 'Cache-Control' => 'no-store', ]); });That Cache-Control isn’t me being fussy. RFC 6585, which defines the 429, says the response must not be stored by a cache. Saying so explicitly means a cache in the middle, configured by someone who isn’t you, never serves a stale 429 to clients that are well within their limit.
The headers nobody standardised
Here’s the awkward bit. Those X-RateLimit-* headers aren’t defined by any standard. They’re a convention, and every API interprets them a little differently. Laravel’s X-RateLimit-Reset is a Unix timestamp, and so is GitHub’s. Plenty of other APIs send the number of seconds until the reset. Nothing in the header tells a client which one it’s looking at.
And on a successful response, Laravel only sends the limit and what’s left. A client can see it has 12 requests remaining, but not whether that’s 12 more this minute or 12 more today, so it can’t pace itself. It finds out the window when it hits a 429.
The IETF HTTPAPI working group has been fixing this with two new fields in draft-ietf-httpapi-ratelimit-headers: RateLimit-Policy describes the terms, and RateLimit describes where the client is right now. At the time of writing it’s at revision 11, which expires on 24 November 2026. It’s still a draft and it can still change, so treat everything in this section as provisional.
I built support for it into my api-toolbox package as an experimental feature. You switch it on in config/api-toolbox.php:
Features::rateLimitHeaders([ 'legacy_headers' => true, // keep Laravel's X-RateLimit-* alongside]),Your limiters don’t change at all. The same api limiter from earlier now produces:
RateLimit-Policy: "api";q=60;w=60RateLimit: "api";r=59;t=60q is the quota and w the window in seconds, so a client knows from the very first response that it’s sixty a minute. r is what’s left and t is the number of seconds until the window resets, which is always seconds, so there’s no guessing whether it’s a timestamp. A limiter that returns several limits gets a policy for each, numbered, so the layered one from earlier tells the client about both windows up front:
RateLimit-Policy: "api-1";q=60;w=60, "api-2";q=1000;w=86400RateLimit: "api-1";r=59;t=60, "api-2";r=999;t=86400On a 429, the package renders the Problem Details body and adds the no-store for you, so you can drop the response() callback from earlier.
One thing it deliberately leaves out is the draft’s partition key, pk. The draft says to avoid partition keys that carry sensitive information, and Laravel’s keys are user IDs and IP addresses. It also doesn’t cover apps that throttle with Redis through throttleWithRedis() yet, because that’s a different middleware with a different way of counting.
The other end: a client that waits
Everything so far has been the server’s half. The client’s half is reading those terms and acting on them, and most clients do one of two things wrong: they ignore a 429 and fail, or they retry immediately, in a loop, which is the exact behaviour the limit exists to stop.
A 429 is safe to retry whatever the method was, because a rate limiter turns a request away before any of the work is done. Laravel’s throttle answers before your controller ever sees the request. That’s different from a 500 on a POST, where the first attempt may have created something. The right retry waits as long as Retry-After says, and no longer.
Laravel’s HTTP client can do that. retry() takes a closure for the delay, which gets the attempt number and the exception, and a second closure that decides whether to retry at all:
use Illuminate\Http\Client\RequestException;use Illuminate\Support\Facades\Http;
$response = Http::retry( 3, function (int $attempt, Throwable $e): int { $wait = $e instanceof RequestException ? $e->response->header('Retry-After') : '';
return is_numeric($wait) ? min((int) $wait, 30) * 1000 : 200 * $attempt; }, fn (Throwable $e) => $e instanceof RequestException && in_array($e->response->status(), [429, 503], true),)->get('https://api.example.com/orders');The min() is doing real work. An API that says Retry-After: 3600 would otherwise park your queue worker, or worse your web request, for an hour. Thirty seconds is a reasonable ceiling for a queued job. In a request with a person watching a spinner, I’d go much lower and let it fail. This version only reads Retry-After as a number of seconds; HTTP also allows a date there, and an API that sends one falls back to the short backoff.
Retrying after a 429 is still reacting. The better client never sends the request it knows will be refused, and that means remembering what the last response said. This is the half I built sdk-toolbox for, my framework for PHP SDKs. A connector given a Throttle reads the rate limit fields on every response, the IETF ones first and the X-RateLimit-* conventions failing that, and when a response says the quota is spent, the next request to that host waits until the reset. With Acme standing in for your SDK’s connector:
use JustSteveKing\SdkToolbox\RateLimits\Throttle;
$acme = new Acme($token, throttle: new Throttle(maxWait: 30.0));If the reset is further away than maxWait, it throws a RateLimitExceededException without sending anything at all, with retryAfter set so you can reschedule the job. It only ever acts on what the server reported, and never assumes it knows how much quota is left. The X-RateLimit-Reset problem from earlier gets the only honest answer available: a value big enough to be a timestamp is read as one. That’s a guess, and it’s exactly the kind of guess the IETF fields make unnecessary.
Testing that the limit is there
Given how easy it is to have no limit at all without noticing, it’s worth a test that would fail if the throttle went missing. This one assumes the sixty-a-minute api limiter from earlier and a /api/ping route:
public function test_the_api_is_rate_limited(): void{ for ($i = 0; $i < 60; $i++) { $this->getJson('/api/ping')->assertOk(); }
$this->getJson('/api/ping') ->assertTooManyRequests() ->assertHeader('Retry-After');}The rate limiter uses your cache, so this works with the array cache store a default test environment uses, and the counter is fresh for every test.
That cache is worth a thought in production too. A new Laravel 13 app uses the database cache store by default, which means every rate-limited request writes to your database. The limiter uses whatever store cache.limiter names, falling back to your default, so you can move it to Redis on its own without changing anything else:
'limiter' => 'redis',What I’d actually do
For a new Laravel API, I’d switch on throttleApi() on day one, key on the user ID with the IP as the fallback, and add a daily limit alongside the per-minute one, with distinct keys. Every 429 gets a Problem Details body and no-store. If the API has outside consumers, I’d add the IETF fields with legacy_headers left on, so existing clients keep working while new ones can read the policy properly.
What I wouldn’t do is treat any of this as protection against an attack. By the time Laravel’s throttle runs, the request has already reached PHP, booted the framework and hit your cache. Application rate limiting is about fairness between well-behaved clients, keeping one of them from using up the capacity everyone shares. A flood is a job for whatever sits in front of your app, your CDN or your load balancer, long before a request ever gets that far.
And on the client side, honour Retry-After, cap how long you’ll wait, and never retry a 429 in a tight loop. The limit is the API telling you exactly what it needs. All you have to do is read it.
Related
More in API Design
Your API Key Is in Your Stack Trace
With one PHP setting off, every frame of an exception's trace keeps its arguments, and an SDK's authenticated request goes with them. Where keys leak, why production hides it, and how to stop it.
Nov 2026 · 10 min read
API DesignRebuilding Resend's PHP SDK
I rebuilt part of Resend's official PHP SDK on sdk-toolbox and ran both against the same failures. The rebuild handles what goes wrong better. The official one is still better to use.
Nov 2026 · 15 min read
API DesignYou Can't Deprecate a Field With a Header
RFC 9745's Deprecation header covers whole resources, so a field changing shape has no HTTP signal. Where that deprecation goes instead, and where the header is exactly right.
Oct 2026 · 7 min read
Same subject
In other formats
Rate Limiting Your Laravel API | Laravel API Course Ep. 6
Don't let anyone flood your API with endless requests. In this short episode we add rate limiting to protect the Ping API and keep it fair for everyone who uses it.
PHP & Laravel
Codehttp-auth-strategies
A simple PHP package that is used to create different Http Auth Headers
API Design
TalkThe 10 REST Commandments: Principles for Better API Design
API Design