What it is
A rate limiter caps how many requests a client may make in a period of time. Requests within the limit pass; requests above it are refused immediately, usually with HTTP 429 Too Many Requests and a Retry-After header saying when to try again. Limits are typically enforced at the edge (API gateway, reverse proxy) and often again inside services.
Why it exists
Servers have finite capacity and it is shared by every client. Without limits, a single buggy script, a scraper or a retry loop can consume all of it, and the servers' queues fill with that client's requests, so everyone else starts seeing timeouts and errors too. A rate limiter makes overload predictable: it refuses the excess at the door, cheaply, before it reaches the expensive parts. It also enforces fairness and commercial quotas (free tier versus paid).
How it works
Token bucket. The most common algorithm. Each client has a bucket that holds up to burst tokens and refills at rate tokens per second. Every request takes one token; if the bucket is empty the request is refused. A client that has been quiet can send a short burst (up to the bucket size), but over time it cannot exceed the refill rate. It needs only two numbers per client: the token count and the time of the last refill.
Other algorithms.
- Fixed window: count requests per calendar minute. Simple, but a client can send twice the limit around a window boundary.
- Sliding window log or counter: smooth out the boundary effect at slightly more cost.
- Leaky bucket: requests drain at a constant rate, which smooths output but adds queueing delay instead of refusing.
What to key on. Per API key or user is the usual choice for authenticated APIs; per IP for anonymous traffic (careful with NAT and proxies); per endpoint for expensive operations. Combine them: a per-client limit for fairness, plus a global limit sized to what the servers can actually handle, as a last line of defence.
Distributed limits. With several gateway instances, each in-memory bucket only sees its share of traffic, so the effective limit multiplies. Either keep counters in a shared store (Redis with atomic increments or a Lua script), or give each instance a fraction of the limit and accept some imprecision.
Responding. Return 429 (not 500 or 503, which suggest the server is broken), include Retry-After, and ideally headers showing the limit and remaining quota. Document the limits so clients can pace themselves.
When to use it
- Any public or partner-facing API.
- Expensive endpoints (search, exports, login attempts, AI calls) even for trusted clients.
- In front of shared internal services that several teams depend on.
- To enforce plan quotas and protect against abuse (credential stuffing, scraping).
When not to
- As a substitute for capacity: if legitimate traffic exceeds what you can serve, a limit just turns customers away.
- With a single shared limit when fairness matters; it penalises well-behaved clients as much as the noisy one.
- Where requests cannot be retried or deferred and dropping them is worse than slowing down; consider queueing or prioritised load shedding.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Per-client limits | Fairness; one client cannot starve others | State per client; choosing the right key |
| Global limit only | Simple, protects servers | Everyone suffers when one client floods |
| Large burst | Tolerates bursty but legitimate clients | Short spikes can still hit the servers |
| Small burst | Smooth, predictable load | Refuses normal batches |
| Shared counters (Redis) | Accurate limits across instances | A network call per request; a dependency to keep available |
| Local counters | Fast, no dependency | Limit scales with the number of instances |
Alternatives
- Load shedding: refuse work based on current server load (queue length, latency) rather than a fixed per-client rate; protects capacity but not fairness.
- Queueing / leaky bucket: delay rather than refuse excess requests.
- Concurrency limits: cap requests in flight per client instead of requests per second.
- Priority classes: keep capacity for critical traffic and shed the rest first.
- Circuit breakers on the client side: callers stop sending when the server is failing.
Failure modes
- Retry storms: clients that treat 429 like any error and retry immediately multiply their traffic without getting more through.
- Limiter as a single point of failure: if the shared counter store is down, decide in advance whether to fail open (allow) or fail closed (refuse).
- Wrong key: limiting by IP blocks a whole office behind one NAT; limiting by a header clients can change does nothing.
- Limits above capacity: per-client limits that are each reasonable but sum to more than the servers can handle; the global limit catches this.
- Silent throttling: refusing without telling clients why or when to retry leads to blind retries.
In production
Enforce limits at the gateway, keyed by API key or user, with a global limit sized from load tests. Use token buckets with explicit rate and burst values per plan. Share counters across instances. Return 429 with Retry-After and quota headers. Ship SDKs that honour Retry-After and back off with jitter. Monitor refusals per client and alert when important clients are throttled. Review limits as capacity changes.
Common misconceptions
- "Rate limiting is only for abuse." It is also capacity protection and fairness for ordinary clients.
- "One global limit is enough." It protects the servers but not the well-behaved clients.
- "Retrying a 429 quickly gets the request through." The bucket refills at its own rate; quick retries only waste requests.
- "With a rate limit, capacity planning is optional." The limit refuses traffic; it does not serve it.
Interview angle
Rate limiting comes up both as a component ("put a rate limiter in the gateway") and as a full design problem ("design a distributed rate limiter"). Be ready to explain token bucket versus sliding window, what you key on, where the counters live and how they stay consistent across instances, what happens when the counter store fails, and how clients should react to 429. Mentioning per-client plus global limits, and Retry-After with client backoff, covers the usual follow-ups.
Model assumptions
The simulation is a simplified model, not a benchmark. Two API servers each have 6 workers, an 80 ms mean service time (lognormal, cv 0.35) and room for 12 waiting requests, about 150 requests per second together; the gateway balances by least connections. Rate limits are token buckets that refill continuously; a refused request fails at once with 429. The engine keeps one bucket per node, so the scraper's per-key bucket is drawn as its own box in front of the gateway; a real gateway keeps one bucket per key internally. The scraper's retries use 4 attempts with 10–40 ms delays and no jitter. Arrivals are Poisson. Latency percentiles (P50, P95, P99) are computed over the requests that succeeded in the last 5 simulated seconds: failed, rejected and timed-out requests are not in them and are counted in the Errors tile, which is always shown next to them. Rejecting or timing out the slowest requests therefore improves the percentiles while making the system less reliable, so read the two together. Numbers show behaviour and orders of magnitude only.