Someone is trying to guess one of your users' passwords. Not once or twice, but thousands of times a minute, and your server patiently answers every try. What stops it is rate limiting: a cap on how many requests one sender may send in a span of time.
Picture the office coffee machine that only gives out 5 cups per 10 seconds for one employee card. The sixth cup is refused, and the screen says "try again in 9 seconds". Each cup is one request. The card is the key: what identifies the sender, such as an IP or a user (not an encryption key). 5 per 10 seconds is the limit, and the message on the screen is the Retry-After header.
Why an API needs a limit
With no limit, anyone can send as many requests as they like, as fast as they like:
- Brute force login: trying thousands of passwords a minute against one account.
- Credential stuffing: trying email and password pairs leaked from other sites, thousands at a time.
- Scraping and spam: scraping copies all the data automatically, and spam floods a form.
- DoS and DDoS: flooding the server with requests until its CPU, memory or bandwidth (network capacity) is used up, and real users aren't served. DoS (Denial of Service) comes from one source, while DDoS (Distributed Denial of Service) comes from many sources at once.
Rate limiting is one layer of defence against all of these. For a big DDoS, rate limiting is helped by other layers such as a CDN (a network of servers in many places that receives requests first) and a firewall (a filter for network traffic). The reason: even requests that rate limiting refuses still reach the server and put load on it.
What the server sends when the limit is used up
Calculate it before you look at the table: the limit is 5 requests per 10 seconds, and you send 6 requests within 1 second. What status does the sixth request get, and how many seconds do you have to wait?
This is a record from the Lab: a limit of 5 per 10 seconds, counted with a sliding window (how it counts is in the next section). Time is counted from the first request. A request that passes is one the server accepts.
| Request | Time | Passed in the last 10 seconds | Server's answer |
|---|---|---|---|
| 1 | 0.0 s | 0 | 200 OK, RateLimit-Remaining: 4 |
| 2 | 0.2 s | 1 | 200 OK, RateLimit-Remaining: 3 |
| 3 | 0.4 s | 2 | 200 OK, RateLimit-Remaining: 2 |
| 4 | 0.6 s | 3 | 200 OK, RateLimit-Remaining: 1 |
| 5 | 0.8 s | 4 | 200 OK, RateLimit-Remaining: 0 |
| 6 | 1.0 s | 5 | 429 Too Many Requests, Retry-After: 9 |
| 7 | 10.1 s | 4 (the one at 0.0 s is now over 10 seconds old) | 200 OK, RateLimit-Remaining: 0 |
The sixth request gets 429 Too Many Requests with Retry-After: 9. What is counted is a 10 second window: the last 10 seconds up to now. The first request (at 0.0 s) only leaves that window at 10.0 s. It's now 1.0 s, so 9 seconds are left.
429is the HTTP status made for "too many requests".Retry-Afterholds how many seconds the client must wait. A well-behaved client reads it and waits until then.RateLimit-LimitandRateLimit-Remainingtell the limit and what's left of it, so a client can slow down before it gets a 429. These two names come from an older IETF draft (a proposed standard), and these headers are not a standard yet. The newer draft-11 (May 2026) uses two other headers:RateLimitandRateLimit-Policy. Laravel uses the namesX-RateLimit-LimitandX-RateLimit-Remaining.429andRetry-Afterare already standard.
Three ways to count
Example: a limit of 5 per 10 seconds, then 5 requests at second 9.5 and 5 more at second 10.5.
| Way | How it works | In that example |
|---|---|---|
| Fixed window | A counter per fixed window (0 to 10 s, 10 to 20 s), back to 0 for each new window | 10 pass within 1 second |
| Sliding window | Counts the requests that passed in the last 10 seconds, counted back from now | 5 pass, 5 get a 429 |
| Token bucket | A bucket of 5 tokens, refilled with 1 token every 2 seconds. Each request uses 1 token | 5 pass, then 1 passes every 2 seconds |
- Fixed window is the simplest, but it has a gap at the window's edge. Its counter resets to 0 at second 10. So the 5 requests at 9.5 s fall in the first window, the 5 at 10.5 s fall in the second window, and 10 requests pass very close together.
- Sliding window closes that gap, because its window is always "the last 10 seconds from now".
- Token bucket allows a small burst, up to what the bucket holds, then a steady rate. A token here is the allowance for one request, not a login token. In that example, at 10.5 s the bucket has refilled only half a token, so
Retry-After: 1. At 11.5 s, one request passes.
Sliding window code in JavaScript
This code records the time of each request that passes, per key, then counts how many are still in the window:
const LIMIT = 5
const WINDOW_MS = 10_000 // 10 seconds
const hits = new Map() // key (IP or user id) -> times of the requests that passed
function rateLimit(key, now = Date.now()) {
const recent = (hits.get(key) ?? []).filter((t) => t > now - WINDOW_MS)
if (recent.length >= LIMIT) {
const retryAfter = Math.ceil((recent[0] + WINDOW_MS - now) / 1000)
return { status: 429, headers: { 'Retry-After': String(retryAfter) } }
}
recent.push(now)
hits.set(key, recent)
return { status: 200, headers: { 'RateLimit-Limit': String(LIMIT), 'RateLimit-Remaining': String(LIMIT - recent.length) } }
}
hits.get(key) ?? []takes the record for that key, or an empty array if there is none yet.filter((t) => t > now - WINDOW_MS)throws away times older than 10 seconds. What's left are the requests in the current window.recent.length >= LIMITmeans the allowance is used up: return 429 without recording this request.recent[0]is the oldest request in the window. That request leaves the window atrecent[0] + WINDOW_MS. So the difference fromnow, rounded up, isRetry-After.hitslives in the memory of one process. If you run more than one server, keep the counts in Redis, so all servers share the same numbers. In Express, theexpress-rate-limitpackage already does all of this.
In Laravel
Laravel adds rate limiting through the throttle middleware:
// routes/api.php: 60 requests per 1 minute
Route::middleware('throttle:60,1')->group(function () {
Route::get('/data', [DataController::class, 'index']);
});
// AppServiceProvider::boot()
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)->by($request->ip());
});
Route::post('/login', [AuthController::class, 'login'])->middleware('throttle:login');
throttle:60,1means 60 requests per 1 minute.by(...)sets the key the counting uses.$request->user()?->id ?: $request->ip()means: if the user is logged in, count per user id. If not, count per IP.- The login endpoint gets a much tighter limit (5 per minute) than the ordinary API.
- Past the limit, Laravel answers
429with aRetry-Afterheader by itself.
The login limiter above counts per IP only, but an attacker can try one account from many IPs. A stronger version sets two limits at the same time:
// AppServiceProvider::boot(): login counted per email AND per IP
RateLimiter::for('login', function (Request $request) {
$email = Str::lower((string) $request->input('email'));
return [
Limit::perMinute(5)->by('email:'.$email), // one account, many IPs
Limit::perMinute(20)->by('ip:'.$request->ip()), // one IP, many accounts
];
});
A request is refused when either limit is used up. The prefixes email: and ip: keep the two keys different. The per-IP limit is looser, because a whole office can share one IP. For example, with 25 login attempts on one account from 25 IPs within one minute, the by($request->ip()) version lets 25 through, while this version lets only 5 through.
⚠️ Setup mistakes that make the limit leak
- The same limit for every endpoint. Login, password reset and payments need a far tighter limit than a product list.
- Only per IP. A whole office can share one IP, so many honest users get a 429 together. An attacker can also use many IPs. Combine per IP with per user, and for login, per email being tried.
- Counting in memory with several servers. Each server counts on its own, so the limit multiplies. Use Redis.
- Not telling the app about the proxy. Behind a proxy such as Nginx, Cloudflare or a load balancer (a server that divides requests among several servers),
req.ipand$request->ip()hold the proxy's IP. As a result, all visitors share one counter. In Express, writeapp.set('trust proxy', 1)(one proxy in front of the app). In Laravel, write$middleware->trustProxies(at: '10.0.0.5')inbootstrap/app.php, with your proxy's address.at: '*'is safe only when the app cannot be reached directly, because theX-Forwarded-Forheader (the visitor's real IP, written by the proxy) can be forged. - Forgetting
Retry-After. Without that header, the client doesn't know when it may try again, and it keeps sending.
TL;DR: Rate limiting caps the number of requests per key (what identifies the sender, such as an IP or a user id) in a span of time. It holds back brute force, credential stuffing (trying email and password pairs leaked from other sites), scraping (copying data), and DoS or DDoS (a flood of requests that uses up the server's resources). Past the limit, the server answers 429 Too Many Requests with Retry-After (how many seconds to wait). While requests are still allowed, the server sends RateLimit-Limit and RateLimit-Remaining (the limit and what's left). There are three ways to count. Fixed window (a counter per fixed time window) has a gap at the window's edge. Sliding window counts the most recent span up to now (the last 10 seconds, for example). Token bucket (a bucket of tokens, each one the allowance for a request, that slowly refills) allows a burst (a small spike), then a steady rate. In Laravel: throttle:60,1 (60 requests per minute), and Limit::perMinute(60)->by($request->user()?->id ?: $request->ip()) (count per user, or per IP before login). Make the login endpoint tighter, and keep the counts in Redis when you run more than one server.
⚡ A limit per key
Meaning: Rate limiting caps how many requests may come in per key (what identifies the sender, such as an IP or a user) in a span of time. The limit holds back brute force login, credential stuffing (trying email and password pairs leaked from other sites), scraping (copying data), and DoS (flooding the server until it can't serve users).
⚡ 429 and Retry-After
Guess first: the limit is 5 requests per 10 seconds, and you send 6 requests within 1 second. What does the sixth get?
429 Too Many Requests with Retry-After: 9. The first request (at 0.0 s) only leaves the 10 second window (the last 10 seconds that are counted) at 10.0 s, and the sixth arrives at 1.0 s.
Meaning: 429 is the status for "too many requests". Retry-After tells the client how many seconds to wait. RateLimit-Remaining tells it what's left of its allowance.
⚡ Three ways to count
Meaning: A fixed window counts per fixed time window (0 to 10 s, then 10 to 20 s). It has a gap at the window's edge: 10 requests can pass within 1 second (5 just before second 10, 5 just after). A sliding window closes it by counting the last 10 seconds from now. A token bucket (a bucket of tokens, each one the allowance for a request, that slowly refills) allows a small burst, then a steady rate.
⚡ In Laravel
Write:
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)->by($request->ip());
});
Meaning: This code limits login to 5 tries per minute for each IP. The login endpoint gets a far tighter limit than the ordinary API. With more than one server, keep the counts in Redis (a fast in-memory database), so all servers use the same numbers.