Appearance
Brute Force and Rate Limiting
27. How can an application defend against brute-force attacks?
The short answer
Use several layers, because each one alone can be dodged. Rate limit login attempts per account and per IP address. Slow down or temporarily lock an account after repeated failures, without letting attackers lock real users out forever. Add a CAPTCHA or a proof-of-work challenge after a few failures. Turn on multi-factor authentication so a guessed password is not enough. Check new passwords against lists of breached passwords. Store passwords with a slow hash so a stolen database cannot be brute-forced offline. Return the same error for "no such user" and "wrong password".
Three kinds of attack hide behind the word "brute force":
| Attack | What the attacker does | What stops it |
|---|---|---|
| Brute force | Many passwords against one account | Per-account limit, lockout, MFA |
| Password spraying | One common password, such as Summer2026!, against many accounts | Breached-password check, per-IP limit, MFA |
| Credential stuffing | Email and password pairs leaked from another site | Breached-password check, bot detection, MFA |
Why per-IP limits alone fail. Real attackers use thousands of IP addresses rented from botnets or residential proxy services. Each IP makes only a few attempts, well under any per-IP limit. A per-account counter catches the many attempts against one account. A global failure-rate alert catches the spray across many accounts.
Lockout without handing attackers a weapon. A permanent lock after five failures lets anyone lock your users out on purpose. Safer options:
- Delay that grows: 1 second after the third failure, then 2, 4, 8, capped at a few minutes.
- Temporary lock: 15 minutes, then the counter resets.
- Challenge instead of block: after five failures, require a CAPTCHA, or an emailed one-time link.
Do not reveal which part was wrong. "Invalid email or password" for both cases, with the same response time. Different messages, or a fast reply when the user does not exist, let an attacker discover which emails have accounts. This is called user enumeration.
ts
async function login(email: string, password: string) {
const user = await users.findByEmail(email)
const hash = user?.passwordHash ?? DUMMY_HASH // (1)
const ok = await argon2.verify(hash, password) // (2)
if (!user || !ok) throw new HttpError(401, 'Invalid email or password') // (3)
return user
}- Use a dummy hash when the user does not exist, so the slow hash check still runs.
- Always do the slow comparison, so "no such user" takes as long as "wrong password".
- One message for both failures.
28. What is rate limiting, and how does express-rate-limit work?
The short answer
Rate limiting caps how many requests a client may make in a time window, such as 5 login attempts per 15 minutes, and rejects the rest with 429 Too Many Requests and a Retry-After header. It protects against brute force, scraping and one noisy client starving everyone else. express-rate-limit is middleware that, for each request, builds a key, by default the client IP, increments a counter for that key in a store, and blocks the request if the counter is over the limit for the current window. The default store is in memory.
ts
import { rateLimit, ipKeyGenerator } from 'express-rate-limit'
app.set('trust proxy', 1) // (1)
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // (2)
limit: 5,
standardHeaders: 'draft-8', // (3)
legacyHeaders: false,
keyGenerator: (req) => `${ipKeyGenerator(req.ip!)}:${String(req.body?.email ?? '').toLowerCase()}`, // (4)
skipSuccessfulRequests: true, // (5)
message: { error: 'Too many login attempts. Try again later.' },
})
app.post('/auth/login', express.json(), loginLimiter, loginHandler) // (6)- Read the real client IP from
X-Forwarded-Forwhen behind one proxy. Without this, every request looks like it came from the load balancer, and one user's limit blocks everyone (the trust proxy question). - The window and the limit: 5 requests per 15 minutes.
- Send the standard
RateLimitheaders, so clients can see how many requests remain and when the window resets. - Key by IP and email together.
ipKeyGeneratorgroups IPv6 addresses by network block, because one IPv6 user can own millions of addresses and would otherwise get a fresh limit for each. Using IP and email together means one attacker cannot exhaust a real user's attempts from a different address. Pair it with a second limiter keyed by email alone for the distributed attack (question 27). - Count only failures, so a user who logs in successfully is not penalised.
- Only on the login route, after the JSON parser so the email is available.
The common counting methods:
| Method | How it counts | Trade-off |
|---|---|---|
| Fixed window | Counter resets every 15 minutes | Simple. A burst at the window edge allows double the limit |
| Sliding window | Counts the last 15 minutes from now | Smoother. Slightly more storage |
| Token bucket | Tokens refill at a steady rate; each request spends one | Allows short bursts, then a steady rate |
express-rate-limit uses a fixed window by default. For most login and API limits that is good enough.
What 429 should look like: status 429, a Retry-After header in seconds, and a short JSON error body. A well-behaved client waits that long before retrying.
29. How would you implement rate limiting across multiple application instances?
The short answer
Move the counters out of each process into one shared fast store, usually Redis, so every instance increments and reads the same counter for a key. With in-memory counters, three instances each allow 5 attempts, so an attacker effectively gets 15, and a restart resets everything. Use an atomic Redis operation, such as INCR with an expiry, or a small Lua script, so two instances cannot both read 4 and both allow a fifth. Many teams also put a coarse limit at the edge: the load balancer, API gateway or CDN.
With express-rate-limit, swap the store:
ts
import { rateLimit } from 'express-rate-limit'
import { RedisStore } from 'rate-limit-redis'
import { createClient } from 'redis'
const redis = createClient({ url: config.REDIS_URL })
await redis.connect()
const apiLimiter = rateLimit({
windowMs: 60_000,
limit: 100,
store: new RedisStore({
sendCommand: (...args: string[]) => redis.sendCommand(args), // (1)
prefix: 'rl:api:', // (2)
}),
})- Every instance talks to the same Redis, so they share counters.
- A prefix per limiter, so the login counters and API counters do not collide.
What the store does underneath, as a minimal fixed-window counter:
ts
async function hit(key: string, windowSec: number, limit: number) {
const count = await redis.incr(key) // (1)
if (count === 1) await redis.expire(key, windowSec) // (2)
return { allowed: count <= limit, count }
}INCRis atomic. Redis runs one command at a time, so two instances can never both read 4 and both write 5. Each gets its own number back.- Start the window on the first hit. The key deletes itself when the window ends, which resets the count. In production, set the counter and expiry in one step with a Lua script or
SET key 0 EX 60 NXbefore theINCR. Otherwise a crash between the two lines leaves a key that never expires.
Decisions an interviewer will ask about:
| Question | Usual answer |
|---|---|
| Redis goes down. Allow or block everything? | Usually allow, and alert. Blocking all logins is an outage. For the login limiter, some teams fall back to a small in-memory limit |
| Where does the limit live? | Coarse per-IP limit at the edge; per-user and per-route limits in the app |
| What key? | IP for anonymous traffic; user ID or API key once authenticated |
| Extra latency? | One Redis round trip, under a millisecond on the same network |