Nginx and API gateways · Build it
Rate-limit the OTP endpoint at Nginx
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
Write the Nginx config to protect POST /auth/otp/send: at most 20 requests a minute per IP, and a JSON 429 when the limit is hit. Nginx is behind a load balancer. Then tell me what Nginx can't do here.
Then
Follow-ups the interviewer asks next
- Why trust
X-Forwarded-Foronly from the load balancer? - What do
burstandnodelaychange? - We also want at most 3 OTPs per phone number per 10 minutes. Can Nginx do that?
- Thousands of Jio or Airtel users can share one public IP. What does that mean for your limit?
- We run 4 Nginx instances. What's the real limit?
- How do you roll it out without blocking real users?
The answer
What a strong answer covers
- Real IP:
set_real_ip_from 10.0.0.0/16; real_ip_header X-Forwarded-For; real_ip_recursive on;, trusted only from the balancer's range, or anyone can send a fake header and get a fresh bucket. - Zone:
limit_req_zone $binary_remote_addr zone=otp_ip:10m rate=20r/m;(10 MB holds tens of thousands of addresses). - Location:
location = /auth/otp/send { limit_req zone=otp_ip burst=5 nodelay; limit_req_status 429; error_page 429 = @otp_limited; proxy_pass http://app; }. - JSON answer:
location @otp_limited { default_type application/json; add_header Retry-After 60 always; return 429 '{"error":"too_many_requests"}'; }. burst=5 nodelaylets a short burst through at once and then rejects; withoutnodelay, extra requests are delayed instead.- Per phone number: the number is inside the JSON body, which
limit_reqcan't key on (without njs or Lua). That limit belongs in the app: a Redis counter per number and per device, a cooldown and a daily cap. - Carrier-grade NAT: many mobile users in India share public IPs, so per-IP limits must be generous; the per-number and per-device limits do the real work.
- Each Nginx keeps its own counters, so 4 instances allow up to 4x. For an exact global limit, count in Redis (in the app or a gateway plugin).
- Rollout:
limit_req_dry_run on;first, watch the dry-run log lines and a dashboard of would-be 429s, then enforce.
The red pen
Common traps
Avoid:keying on $remote_addr behind the balancer; only an IP limit for OTPs; answering 503, which clients retry at once.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.