Skip to content

Interview PrepAbuse · Core

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":

AttackWhat the attacker doesWhat stops it
Brute forceMany passwords against one accountPer-account limit, lockout, MFA
Password sprayingOne common password, such as Summer2026!, against many accountsBreached-password check, per-IP limit, MFA
Credential stuffingEmail and password pairs leaked from another siteBreached-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:

  1. Delay that grows: 1 second after the third failure, then 2, 4, 8, capped at a few minutes.
  2. Temporary lock: 15 minutes, then the counter resets.
  3. 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
}
  1. Use a dummy hash when the user does not exist, so the slow hash check still runs.
  2. Always do the slow comparison, so "no such user" takes as long as "wrong password".
  3. 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)
  1. Read the real client IP from X-Forwarded-For when 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).
  2. The window and the limit: 5 requests per 15 minutes.
  3. Send the standard RateLimit headers, so clients can see how many requests remain and when the window resets.
  4. Key by IP and email together. ipKeyGenerator groups 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).
  5. Count only failures, so a user who logs in successfully is not penalised.
  6. Only on the login route, after the JSON parser so the email is available.

The common counting methods:

MethodHow it countsTrade-off
Fixed windowCounter resets every 15 minutesSimple. A burst at the window edge allows double the limit
Sliding windowCounts the last 15 minutes from nowSmoother. Slightly more storage
Token bucketTokens refill at a steady rate; each request spends oneAllows 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.

in memory: 3 × 5 = 15 attemptsload balancerinstance Acount 5instance Bcount 5instance Ccount 5each counter only sees its own shareshared Redis: 5 attempts totalinstance Ainstance Binstance CRedisrl:login:… = 5
One counter, wherever the request lands. On the left, the load balancer spreads attempts across three private counters, so the real limit is three times what you wrote. On the right, every instance increments the same Redis key, so the limit means what it says.

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)
  }),
})
  1. Every instance talks to the same Redis, so they share counters.
  2. 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 }
}
  1. INCR is 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.
  2. 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 NX before the INCR. Otherwise a crash between the two lines leaves a key that never expires.

Decisions an interviewer will ask about:

QuestionUsual 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

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Web & API Security
Attacks
Browser rules
Abuse
Secrets
Architecture
Other topics
Nothing picked yet