How many times a minute may the School Portal login form be tried? If the answer is "no limit", one script can keep trying Siti's password without ever stopping.
Rate limiting for authentication puts a limit on how many times the login form may be tried in a span of time. The attempts are counted per key, the counting key (a tag that identifies the sender): per account from one IP, and per IP. Once the limit is exceeded, the server refuses with 429 without checking the password at all. Picture the guard at the school gate. A visitor who gets a teacher's name wrong may try again, but after five tries in a minute, they are asked to wait at the guard post. Everyone on one bus also shares one allowance of tries. A visitor who got it wrong three times has to show an ID card first. In this picture, the guard is the server, each visitor is one account being tried, and a wrong name is a wrong password. Waiting at the post is the 429 answer, one bus is one IP, and the ID card is the captcha.
Why login needs a limit of its own
Login is the main endpoint that takes password guesses. Every attempt is also expensive for the server: password hashing is slow on purpose (the Password Hashing lesson), so a thousand attempts a minute means a thousand slow hashes a minute. That is why the limit sits before the password is checked, and is far stricter than on other endpoints. The Account Recovery & Lockout lesson holds back an email|IP pair after 5 wrong passwords. This lesson adds a limit on every attempt, right or wrong, per email|IP and per IP, and a captcha per account. The attack side, brute force and credential stuffing (trying email and password pairs leaked from other sites), is covered in the Rate Limiting & Throttling lesson of the Security track. Here we build the limit for School Portal.
Two keys: per account and per IP
| Counting key | Limit in the Lab | What it holds back |
|---|---|---|
email|IP, for example [email protected]|198.51.100.23 |
5 per 60 seconds | one account tried over and over from one IP |
IP, for example 198.51.100.23 |
10 per 60 seconds | one IP trying many accounts |
the account alone, [email protected] |
a captcha after 3 failures within 15 minutes | one account tried from many IPs |
- A limit per IP alone isn't enough. One person can switch IPs through a VPN (a service that sends the connection through another server) or a proxy (a go-between server), and get a fresh allowance. On the other hand, many legitimate users can share one IP. For example, 30 students in the school's computer lab: the school's router uses NAT, so all of them reach the internet through one public IP. That is why the per-IP limit has to be loose, and the strict one is
email|IP. - The per-account limit doesn't block, it only adds one step: a captcha. If the per-account limit blocked, anyone who knows Siti's email could stop Siti from logging in. That is the same problem as the permanent lock per account in the Account Recovery & Lockout lesson.
A sliding window on every attempt
This is the rate limiter, with a sliding window that records every attempt:
function createRateLimiter(windowMs, maxRequests) {
const hits = new Map(); // key -> [attempt time, ...]
return function allow(key, now) {
const recent = (hits.get(key) || []).filter((t) => t > now - windowMs); // the moving window
recent.push(now); // recorded, even if it is refused
hits.set(key, recent);
return recent.length <= maxRequests;
};
}
const perEmailIp = createRateLimiter(60 * 1000, 5);
const perIp = createRateLimiter(60 * 1000, 10);
allow(key, now) answers true (passes) or false (refused) for one counting key.
filter((t) => t > now - windowMs): only the attempts of the last 60 seconds count, measured back from now. An attempt exactly atnow - windowMshas already left the window.recent.push(now)before deciding: refused attempts are recorded too. A client that sends without stopping keeps filling its own window, so it stays held back. A client that waits as long asRetry-Aftersays can pass again.recent.length <= maxRequests: with a limit of 5, the fifth attempt still passes, and the sixth is refused.- Compare a fixed window: one counter for each minute (07:00:00 to 07:00:59), which goes back to zero when the minute changes. Five attempts at second 59 and five more at second 00 of the next minute all pass: 10 attempts in 2 seconds, twice the limit. A sliding window always counts the last 60 seconds from now, so it has no gap when the minute changes.
School Portal's limit is 5 attempts per 60 seconds per email|IP. From an internet cafe, Siti sends a login every 2 seconds starting at 07:00:00. Her first six attempts all fail or are refused. Before you look at the trace, guess: what does the sixth attempt, at 07:00:10, get back, and what is its Retry-After?
Here is a trace from the Lab, all from the internet cafe at 198.51.100.23:
| Time | Attempt | email|IP in 60 seconds |
Account failures | Answer |
|---|---|---|---|---|
| 07:00:00 | Siti, wrong password | 1 | 1 | 401 |
| 07:00:02 | Siti, wrong password | 2 | 2 | 401 |
| 07:00:04 | Siti, wrong password | 3 | 3 | 401, "captcha_required": true |
| 07:00:06 | Siti, wrong, no captcha | 4 | 3 | 422, password not checked |
| 07:00:08 | Siti, wrong, with captcha | 5 | 4 | 401 |
| 07:00:10 | Siti, right password | 6 | 4 | 429, Retry-After: 52 |
| 07:01:02 | Siti, right, with captcha | 5 | 0 | 200 |
The sixth attempt gets 429 Too Many Requests with Retry-After: 52, even though the password is right. Why 52? The window holds six records: seconds 0, 2, 4, 6, 8 and 10, including the refused one at second 10. The next attempt is recorded too, so for it to pass, at most four old records may remain: the records at seconds 0 and 2 have to leave. The record at second 2 leaves at second 62, and 62 minus 10 is 52.
In the exercise, the result of createRateLimiter(60000, 3) (3 attempts per 60 seconds) is stored in limit. This limit function is called with the counting keys 'ip1' and 'ip2', and time is a number of milliseconds. Different counting keys keep their own records. Because refused attempts are recorded too, limit('ip1', 62500) is still false: the records at 3000, 4000 (the refused one) and 62000 are still in the window.
The 429 answer and Retry-After
This is the server's answer to Siti's sixth attempt. X-RateLimit-Limit is the limit, and X-RateLimit-Remaining the attempts left:
HTTP/1.1 429 Too Many Requests
Retry-After: 52
X-RateLimit-Limit: 5
X-RateLimit-Remaining: 0
Content-Type: application/json
{"message": "Too Many Attempts."}
429 Too Many Requestsis the status code made for a limit that was exceeded. Not403(no permission) and not503(the server can't serve requests right now).Retry-Afterhere holds how many seconds the client must wait. School Portal's login form reads it and shows a countdown, not a button that can be clicked again and again.- This answer is the same for registered and unregistered emails, so it still reveals nothing about who has an account.
A captcha after 3 failures
Failures per account are counted with a 15-minute sliding window, as in the Account Recovery & Lockout lesson. But here the counting key is the email alone, without the IP. Once there are 3 failures, the 401 answer carries "captcha_required": true, and the form shows a captcha. The next attempt without a captcha gets 422 before the password is checked. The captcha step follows the account, so switching IPs doesn't remove it. Siti herself can still log in: she just fills in the captcha. A successful login clears the failure count.
handleLogin below puts it all together. recordFailure, recentFailures and clearFailures handle the failures per account, and checkPassword checks the password:
function handleLogin({ email, password, captcha }, ip, now) {
const okEmailIp = perEmailIp(`${email}|${ip}`, now); // both are always called,
const okIp = perIp(ip, now); // so both record the attempt
if (!okEmailIp || !okIp) return { status: 429 };
if (recentFailures(email, now) >= 3 && !captcha) return { status: 422, captcha_required: true };
if (!checkPassword(email, password)) {
recordFailure(email, now);
return { status: 401, captcha_required: recentFailures(email, now) >= 3 };
}
clearFailures(email);
return { status: 200 };
}
In Laravel
In Laravel, the two limits become one named rule:
// app/Providers/AppServiceProvider.php, in the boot() method
RateLimiter::for('login', function (Request $request) {
$email = Str::lower((string) $request->input('email'));
return [
Limit::perMinute(5)->by('email-ip:'.$email.'|'.$request->ip()),
Limit::perMinute(10)->by('ip:'.$request->ip()),
];
});
// routes/web.php
Route::post('/login', [LoginController::class, 'store'])->middleware('throttle:login');
// LoginController@store, before Auth::attempt: a captcha after 3 account failures
$failures = 'login-failures:'.Str::lower($request->input('email'));
if (RateLimiter::attempts($failures) >= 3) {
$captcha = Http::asForm()->post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [
'secret' => config('services.turnstile.secret'),
'response' => $request->input('cf-turnstile-response'),
'remoteip' => $request->ip(),
]);
if (! $captcha->json('success')) {
return response()->json(['message' => 'Complete the captcha first.', 'captcha_required' => true], 422);
}
}
RateLimiter::for('login', ...)gives the rule a name, andthrottle:loginputs it on the route.Limit::perMinute(5)means 5 attempts per minute, andby(...)sets its counting key. An array of twoLimits is checked in order. Theemail-ip:andip:prefixes make sure the two counting keys are never the same, so their counts never mix.- Once the limit is exceeded, Laravel answers
429with{"message": "Too Many Attempts."}and the headersRetry-After,X-RateLimit-LimitandX-RateLimit-Remaining. - There are two differences from
createRateLimiterabove. First, thethrottlemiddleware does not record refused requests. Second, Laravel's RateLimiter starts its window at the first attempt, then drops the whole count at once when that window ends. The result is similar, but theRetry-Afternumber can differ. - After
Auth::attemptfails, callRateLimiter::hit($failures, 15 * 60)(15 minutes, in seconds). When it succeeds, callRateLimiter::clear($failures). - The captcha is Cloudflare Turnstile: the server sends the token from the captcha box to Cloudflare's
siteverify, then readssuccess. - If School Portal runs on more than one server, keep the counts in a shared cache (a store for short-lived data) such as Redis, so every server reads the same numbers.
⚠️ Limits that stop the wrong people, or come too late
- A limit per IP alone. One person switches IPs and gets a fresh allowance, while a whole school behind NAT gets held back. The strict limit is per
email|IP, and the per-IP limit is loose. - Blocking per account. Anyone could stop the owner from logging in. Per account, asking for a captcha is enough.
- Checking the password first, then the limit. The slow hash still runs for every attempt. Check the limit first.
- Forgetting to record refused attempts, which the exercise asks for:
limit('ip1', 62500)must befalse.
TL;DR: Login is limited before the password is checked, with two counting keys (tags that identify the sender): email|IP with a strict limit (5 per 60 seconds in the Lab) and the IP with a loose one (10 per 60 seconds). A limit per IP alone isn't enough: one person can switch IPs, and many legitimate users share one public IP behind NAT. The count is a sliding window: only the attempts of the last 60 seconds count, one made exactly 60 seconds ago no longer counts, and refused ones are recorded too. Once the limit is exceeded: 429 Too Many Requests with Retry-After (how long to wait). An account isn't blocked: it is asked for a captcha after 3 failures within 15 minutes. In Laravel: RateLimiter::for('login') holding several Limit::perMinute(...)->by(...), attached with throttle:login, plus RateLimiter::attempts, hit and clear for the captcha.
⚡ Login needs a limit of its own
Meaning: With no limit, one script can keep trying Siti's password without ever stopping. Every attempt is also expensive for the server, because password hashing is slow on purpose. That is why the limit is checked before the password.
⚡ Per IP alone isn't enough
Meaning: An attacker can switch IPs through a botnet (many devices they control), a proxy (a go-between server) or a VPN (a service that sends the connection through another server). On the other hand, many legitimate users share one IP: 30 students in the school's computer lab reach the internet through one public IP (NAT). So the per-IP limit is loose. The strict limit is counted per email|IP, that is, one email from one IP. Per account, the server doesn't block: it asks for a captcha after 3 failures.
⚡ A sliding window on every attempt
Write:
function createRateLimiter(windowMs, maxRequests) {
const hits = new Map(); // key -> [attempt time, ...]
return function allow(key, now) {
const recent = (hits.get(key) || []).filter((t) => t > now - windowMs); // the moving window
recent.push(now); // recorded, even if it is refused
hits.set(key, recent);
return recent.length <= maxRequests;
};
}
Guess first: this limiter is used with a limit of 5 attempts per 60 seconds. Siti tries to log in every 2 seconds, and her sixth attempt (10 seconds after the first) has the right password. What does it get back?
429 Too Many Requests with Retry-After: 52, even though the password is right. The window holds six records (seconds 0 to 10). The next attempt is also recorded, so for it to pass (5 records at most), the two oldest records (seconds 0 and 2) have to leave first. The record at second 2 leaves at second 62, and 62 minus 10 is 52. Refused attempts are recorded too, so a client that keeps sending without waiting stays held back.