Rate Limiting & Brute Force

Difficulty: Beginner

Question

How would you protect a login endpoint from brute-force and credential-stuffing attacks?

Answer

Protect a login endpoint with layered controls: rate limiting per IP and per account, progressive delays or CAPTCHA after failed attempts, multi-factor authentication, and breached-password checks. No single control is enough because attackers spread attempts across thousands of IPs (credential stuffing) or target one account slowly. The goal is to make guessing too slow and noisy to succeed while keeping real users unblocked.

Know the attack you are defending against

  • Brute force: many passwords tried against one account.
  • Password spraying: one common password (like Password@123) tried against many accounts, staying under per-account limits.
  • Credential stuffing: username and password pairs leaked from other sites replayed against yours, usually through botnets and residential proxies.

Per-IP limits alone stop the first only partially, and barely touch the third.

A layered design

  1. Rate limit per IP and per account key. For example, 10 attempts per minute per IP and 5 failures per 15 minutes per email. Store counters in Redis so every app instance shares them.
  2. Progressive friction, not hard lockout. After 3 failures show a CAPTCHA (or Cloudflare Turnstile); after more, add exponential delays. Permanent lockout lets an attacker lock out real users on purpose, which is a denial-of-service.
  3. MFA. TOTP apps, passkeys or OTP make a guessed password useless on its own. Passkeys (WebAuthn) are phishing-resistant and increasingly the recommended default.
  4. Breached-password check. Reject passwords found in known breaches using the Have I Been Pwned k-anonymity API, as NIST SP 800-63B recommends.
  5. Uniform responses. Return the same message and similar response time for "wrong email" and "wrong password" to avoid user enumeration.
  6. Monitoring. Alert on spikes in failed logins, many accounts from one IP or many IPs for one account.
  7. Edge protection. A WAF or bot management layer (Cloudflare, AWS WAF) can drop known bad traffic before it reaches your app.

Rate limiting algorithms

AlgorithmHow it worksTrade-off
Fixed windowCount requests per clock minuteSimple; allows bursts at window edges
Sliding windowCount over the last N secondsSmoother, slightly more storage
Token bucketTokens refill at a fixed rate; each request spends oneAllows controlled bursts; common in API gateways

OTP endpoints need this too

OTP verification is a classic Indian-app weak spot: a 6-digit OTP has only a million combinations. Limit attempts per OTP (for example 5), expire it in a few minutes, and rate limit OTP sending too, or attackers will burn your SMS budget and spam users.

Gotchas

  • Behind a load balancer, req.ip may be the proxy's IP. Configure trust proxy correctly, or every user shares one bucket.
  • Do not trust a client-supplied X-Forwarded-For unless it comes from your own proxy.
  • Return 429 Too Many Requests with a Retry-After header for legitimate clients.
Layered login defence. Each layer filters attempts before the password is even checked.
  1. Edge WAF / bot filter: Drops known bad IPs and bots.
  2. Per-IP rate limit: Caps attempts from one address.
  3. Per-account limit + CAPTCHA: Adds friction after failures.
  4. Password check: Slow hash compare, uniform error.
  5. MFA challenge: Stops attackers with a correct password.

Code examples

Per-IP and per-account limits with Redis

import { RateLimiterRedis } from 'rate-limiter-flexible';

const byIp = new RateLimiterRedis({
  storeClient: redis, keyPrefix: 'login_ip', points: 10, duration: 60,
});
const failsByEmail = new RateLimiterRedis({
  storeClient: redis, keyPrefix: 'login_fail', points: 5, duration: 15 * 60,
});

app.post('/login', async (req, res) => {
  const email = String(req.body.email).toLowerCase();
  try {
    await byIp.consume(req.ip);
    const state = await failsByEmail.get(email);
    if (state && state.remainingPoints <= 0) throw state;
  } catch (rej) {
    res.set('Retry-After', String(Math.ceil((rej.msBeforeNext ?? 60000) / 1000)));
    return res.status(429).json({ error: 'Too many attempts' });
  }

  const user = await verifyCredentials(email, req.body.password);
  if (!user) {
    await failsByEmail.consume(email); // count only failures
    return res.status(401).json({ error: 'Invalid email or password' });
  }
  await failsByEmail.delete(email);
  // continue to MFA step...
});

The IP limiter caps raw volume, while the per-email counter only increments on failures and resets on success, so real users are rarely affected.

Key points

  • Combine per-IP and per-account rate limits; store counters in Redis for multiple instances.
  • Prefer CAPTCHA and progressive delays over permanent lockout to avoid denial-of-service.
  • MFA (ideally passkeys) makes a guessed password insufficient.
  • Check new passwords against breach lists, as NIST SP 800-63B recommends.
  • OTP verify and OTP send endpoints need strict limits too.

Common follow-up questions

  • How would you rate limit across multiple server instances?
  • What is the difference between brute force, password spraying and credential stuffing?
  • Why can account lockout be a security problem in itself?
  • How would you implement a token bucket rate limiter?

Interview tips

  • Frame the answer as defence in depth; listing only "rate limiting" sounds shallow.
  • Mention credential stuffing explicitly; it is the most common real-world login attack.
  • Talk about the trust proxy and X-Forwarded-For gotcha if you have deployed behind a load balancer.

Concepts covered

Rate Limiting, Credential Stuffing, Token Bucket, Redis, Account Lockout, MFA

More Web Security (OWASP, JWT, XSS, CSRF) questions