Handling requests safely · mid
Rate limiting middleware
Rate limiting caps how many requests a client can make in a time window and answers 429 Too Many Requests with Retry-After; with more than one server instance, the counters must live in a shared store such as Redis.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- express-rate-limit options: windowMs, limit (the old name is max), standardHeaders ('draft-8' sends RateLimit-Policy and RateLimit headers), legacyHeaders: false, keyGenerator, store. Default status is 429.
- The default MemoryStore is per process: with 4 instances each client effectively gets 4x the limit, and limits reset on every restart. Use a Redis store.
- Behind a proxy or load balancer, req.ip is the proxy's address unless you set app.set('trust proxy', ...) correctly. Trusting too much lets clients fake X-Forwarded-For.
- Key by what matters: user id or API key for logged-in traffic, IP for anonymous traffic (express-rate-limit masks IPv6 to a /56 subnet by default).
- Different limits per route: strict for login, OTP and password reset (brute force); looser for reads.
- Also limit at the edge (API gateway, CDN/WAF) for floods; app-level limits protect business rules.
The red pen
Common traps: mistake → fix
Mistake: An in-memory limiter works the same with 5 pods
Fix: each pod counts separately.
Mistake: Limiting by IP is always fair
Fix: many users share one IP (offices, mobile carrier NAT); key by user or API key when you can.
Mistake: A bare 429 is enough
Fix: send Retry-After so well-behaved clients back off.
Easy to hard
Questions interviewers ask, easy to hard
- How would you add rate limiting to a login endpoint?
- What breaks when you scale from one instance to five?
- Which status code and headers do you return?
- How does the 'trust proxy' setting affect rate limiting?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.