Playground: the token bucketPlayground: token bucket
The bucket holds 5 tokens and refills 1 per second. Each request spends one. Fire a burst and watch requests get rejected (429) once the bucket is empty.Bucket mein 5 tokens hain aur har second 1 refill hota hai. Har request ek token kharch karti hai. Burst fire karo aur dekho bucket khali hote hi requests reject (429).
Why every serious API rate-limits
A public API without limits is one buggy script away from an outage: one user with a retry loop can consume your entire capacity. Rate limiting assigns each user/IP/API key a fair quota ("100 requests/minute") and rejects the excess cheaply. It defends against abuse, brute-force logins, scraping, accidental infinite loops, and keeps one noisy customer from degrading everyone.
The algorithms, with real tradeoffs
- Token bucket: a bucket refills at a fixed rate (10 tokens/sec) up to a capacity (100). Each request costs a token; empty bucket = reject. Allows natural bursts (idle 10s, then burst 100) while capping the sustained rate. Used by AWS, Stripe-style APIs. The default choice.
- Leaky bucket: requests enter a queue and are processed at a fixed rate. Output is perfectly smooth; bursts queue up (or overflow and drop). Use when the downstream needs a constant rate (an SMS provider with a hard cap).
- Fixed window: "100 per minute", counter resets each minute. Simple, but the boundary attack: 100 requests at 11:59:59 plus 100 at 12:00:00 = 200 in 2 seconds.
- Sliding window log/counter: keep a rolling 60-second window (exact: timestamped log in a Redis sorted set; approximate: weighted sum of current + previous window counters). Fixes the boundary attack at slightly higher cost.
Rejecting well is a feature
Return 429 Too Many Requests with Retry-After: 30 and X-RateLimit-Remaining: 0 headers so good clients back off automatically. Rejection must be cheaper than processing: check the limit before auth-heavy work or DB queries. For severe abuse, fail even earlier at the edge (CDN/WAF) so the request never reaches your servers.
Distributed rate limiting (the interview deep-dive)
With 10 API servers and a per-user limit of 100/min, naive per-server counters allow 1,000/min. Options:
- Central counter in Redis: atomic INCR + EXPIRE per key per window. Accurate; adds ~1 ms per request; Redis itself must be redundant.
- Token bucket in Redis via Lua: the whole bucket update is one atomic script: the standard production approach.
- Approximate local + sync: each server counts locally and syncs periodically: fewer Redis calls, slightly lenient limits. Fine when 110/min vs 100/min does not matter.
- Sticky routing: route a user to the same server, then local counting is exact, but you inherit stickiness problems.
Design dimensions to mention
- Who is limited: per user, per IP, per API key, per tenant, or global. Login endpoints: per IP + per account. Public APIs: per API key with tiers (free 100/min, paid 10k/min).
- Where it runs: edge (Cloudflare/NGINX) for coarse per-IP limits; API gateway (Kong, Envoy) for per-key; app code for business rules ("3 password resets/day").
- Dynamic rules: limits as config, hot-reloadable, per-endpoint: a DDoS at 2 AM is not when you want to deploy.
Worked example
Login API: per-IP 10/min (token bucket, Redis Lua), per-account 5/hour, global edge limit 50k RPS. Exceed: 429 + Retry-After + generic error (never reveal whether the limit was IP or account, that hints at account existence to attackers).
Common interview traps
- Fixed window without naming the boundary burst.
- Per-server counters in a multi-server deployment.
- Rejecting with 500, or rejecting after doing the expensive work.
- One global limit instead of per-identity quotas.
Interview Q&A
Q: Design a rate limiter for 1M RPS across 50 servers. Storage?
A: Redis Cluster (sharded by user key) with Lua-implemented token buckets; ~1 ms added latency. If Redis capacity is a concern, approximate local counting with periodic central sync, accepting ~5-10% leniency. Mention both and the accuracy/latency tradeoff.
Q: How is rate limiting different from throttling and load shedding?
A: Rate limiting: per-identity quotas, always on. Throttling: slowing everyone when the system is hot. Load shedding: dropping low-priority traffic (or returning 503) when the system is overloaded, regardless of who sent it. They stack: limits in normal times, shedding in emergencies.
Har serious API rate-limit kyun karti hai
Bina limits ka public API ek buggy script se outage door hai: retry loop wala ek user tumhari poori capacity kha sakta hai. Rate limiting har user/IP/API key ko fair quota deta hai ("100 requests/minute") aur excess ko sasti mein reject karta hai. Ye abuse, brute-force logins, scraping, accidental infinite loops se bachata hai, aur ek noisy customer ko sabka experience bigaadne se rokta hai.
Algorithms, asli tradeoffs ke saath
- Token bucket: bucket fixed rate se refill hota hai (10 tokens/sec), capacity tak (100). Har request ek token leti hai; khaali bucket = reject. Natural bursts allow karta hai (10s idle, phir 100 burst) par sustained rate cap rakhta hai. AWS, Stripe-style APIs use karte hain. Default choice.
- Leaky bucket: requests queue mein aati hain aur fixed rate par process hoti hain. Output perfectly smooth; bursts queue hoti hain (ya overflow ho to drop). Jab downstream ko constant rate chahiye (hard cap wala SMS provider).
- Fixed window: "100 per minute", counter har minute reset. Simple, par boundary attack: 11:59:59 par 100 + 12:00:00 par 100 = 2 seconds mein 200.
- Sliding window log/counter: rolling 60-second window (exact: Redis sorted set mein timestamped log; approximate: current + previous window counters ka weighted sum). Boundary attack fix karta hai, thodi zyada cost par.
Achhe se reject karna bhi feature hai
429 Too Many Requests do Retry-After: 30 aur X-RateLimit-Remaining: 0 headers ke saath taaki acche clients apne aap back off karein. Rejection processing se sasti honi chahiye: auth-heavy kaam ya DB queries se pehle limit check karo. Severe abuse ke liye edge (CDN/WAF) par hi fail karo taaki request servers tak pahunche hi nahi.
Distributed rate limiting (interview deep-dive)
10 API servers aur per-user limit 100/min ho to naive per-server counters effectively 1,000/min allow karte hain. Options:
- Central counter Redis mein: har key har window par atomic INCR + EXPIRE. Accurate; har request par ~1 ms add; Redis ko bhi redundant chahiye.
- Redis mein token bucket via Lua: poora bucket update ek atomic script: production ka standard approach.
- Approximate local + sync: har server locally gine aur periodically sync kare: kam Redis calls, thoda lenient limits. Jab 110/min vs 100/min matter na kare.
- Sticky routing: user ko same server par route karo, local counting exact ho jaati hai, par stickiness ke problems inherit hote hain.
Design dimensions jo mention karne hain
- Kise limit karna hai: per user, per IP, per API key, per tenant, ya global. Login endpoints: per IP + per account. Public APIs: per API key, tiers ke saath (free 100/min, paid 10k/min).
- Kahan chalega: edge (Cloudflare/NGINX) coarse per-IP limits ke liye; API gateway (Kong, Envoy) per-key ke liye; app code business rules ke liye ("3 password resets/day").
- Dynamic rules: limits config mein, hot-reloadable, per-endpoint: raat 2 baje DDoS ho to deploy nahi karna hota.
Worked example
Login API: per-IP 10/min (token bucket, Redis Lua), per-account 5/hour, global edge limit 50k RPS. Exceed par: 429 + Retry-After + generic error (kabhi mat batao limit IP ka tha ya account ka, ye attackers ko account existence ka hint deta hai).
Common interview traps
- Fixed window, boundary burst ka zikr nahi.
- Multi-server deployment mein per-server counters.
- 500 se reject karna, ya mehenga kaam karne ke baad reject karna.
- Per-identity quotas ki jagah ek global limit.
Interview Q&A
Q: 50 servers par 1M RPS ke liye rate limiter design karo. Storage?
A: Redis Cluster (user key se sharded) Lua-implemented token buckets ke saath; ~1 ms added latency. Redis capacity concern ho to approximate local counting + periodic central sync, ~5-10% leniency accept karke. Dono bolo aur accuracy/latency tradeoff batao.
Q: Rate limiting, throttling aur load shedding mein farak?
A: Rate limiting: per-identity quotas, hamesha on. Throttling: system garam ho to sabko slow karna. Load shedding: overload par low-priority traffic drop karna (ya 503), bhejne wala koi bhi ho. Ye stack hote hain: normal times mein limits, emergencies mein shedding.