Video in progress
Someone is guessing passwords against your login endpoint (brute force, credential stuffing). How do you build the rate limiting?
A per-IP limit isn't enough: the attack comes from thousands of IPs with one or two attempts per account. I put limits on several dimensions (account, IP, and the overall share of failures) and I slow attackers down and show a CAPTCHA instead of hard-blocking.
📖 Answer
In credential stuffing, the attacker tries a list of "login+password" pairs stolen from another site. One attempt per account, but across a million accounts and 50,000 IPs. A rule like "10 per minute per IP" doesn't see this at all.
So I use several counters, all in Redis:
| Key | What it catches | Example limit |
|---|---|---|
login:fail:user:{login} |
password guessing on a single account | 5 failures in 15 minutes |
login:fail:ip:{ip} |
many accounts from one source | 50 failures per hour |
login:fail:global |
the overall failure rate jumps sharply | alert + CAPTCHA mode |
String key = "login:fail:user:" + login.toLowerCase();
Long fails = redis.opsForValue().increment(key); // only on a wrong password
if (fails != null && fails == 1) redis.expire(key, Duration.ofMinutes(15));
// before the next attempt: if fails > 5, require CAPTCHA
One subtle point: locking an account completely after 5 failures is a DoS in itself. If an attacker knows anyone's login, they can lock that user out on purpose. I escalate instead: slow the response down after 3 failures, CAPTCHA after 5, and an email confirmation if it looks suspicious.
A few more rules:
- the error response is always the same ("wrong login or password") and takes about the same time, otherwise the attacker learns which logins exist;
- a successful login clears the account counter, not the IP counter;
- the first layer sits in the gateway/WAF (IP reputation, bot signals), while the account level lives in the application, because only the application knows who is being targeted;
- bcrypt or Argon2 is deliberately slow and eats CPU during an attack, so the limit check goes before the hash.
Still, the strongest defense isn't a limit at all. It's MFA plus checking passwords against lists of leaked ones.
Sign up to mark studied questions and save your progress.