Lesson 8 of 14
25. Rate Limiting

25.7 How do you handle bots and abuse?

3 min read+10 XP

At the club: A gang tries to get in again and again using many fake IDs, one at a time, each looking like a new person. A per-face limit doesn't catch them. The bouncer notices that they're all asking for the same VIP table, and limits that.

In the system: Rate limits are a key defence against abuse, but attackers adapt:

  • Credential stuffing: trying leaked username/password pairs from thousands of IPs. A per-IP limit of 10 attempts per 15 minutes does nothing when each IP tries only a few times. In the chapter's code, 10,000 guesses at one account from 1,000 IPs all pass a per-IP limit; a per-account limit of 5 lets only 5 through.
  • OTP guessing: limit attempts per phone number and per OTP, and expire OTPs quickly.
  • Scraping: someone copying your catalogue through the API or website. Limit per key and per IP range, watch for unusual patterns (sequential IDs, no images loaded), and require accounts for heavy access.
  • Signup and review spam: limit per IP, per device and per account age.
  • Expensive endpoints: search, report generation and AI features get lower limits or a cost per call (token bucket with weighted costs).

Choose the key to match the attack:

  • Per IP for floods from a few sources (careful: many people share one IP behind mobile carriers and offices).
  • Per account or target (the phone number, the email) for guessing attacks.
  • Per API key or user for fair use.
  • Combinations (IP + account) for tighter control.

Beyond counting:

  • Progressive responses: slow down (add delay), then challenge (CAPTCHA), then block temporarily, rather than an instant hard block.
  • Lockouts with care: locking an account after 5 failures lets attackers lock out real users. Prefer per-account delays and step-up checks.
  • Bot management at the edge (CDN/WAF services) uses signals like browser fingerprints and behaviour, beyond simple rates.

Memory code: "Limit what the attacker wants, not just who they claim to be."