Rate Limiting

Protecting APIs from abuse and overload: token bucket, sliding window, 429 responses, distributed limiting.

Intermediate6 min read
Language
Theme
Token bucketrefill 10/sec1 request = 1 token, bursts allowedRequesttoken?Allowed429 + Retry-AfterDistributedcentral counter in Redis
Key idea at a glance
INTERACTIVE

Playground: the 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.

capacity 5, refill 1/sec

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.

Key takeaways

Interview pointer

This is a classic standalone question: 'design a rate limiter.' Structure the answer: requirements (per user? per IP? dynamic rules?), algorithm choice (token bucket, and why), storage (Redis, and why), distributed behavior, and the 429 response contract. This framework works for every design question.