Rate Limiting
Cap how fast a client can hit you, so one caller can't starve everyone else or melt your backend.
Rate limiting in 30 seconds
- What: cap how fast a client can hit you, so one caller can't starve everyone else or melt the backend.
- How: count requests against an allowance and reject over-the-line traffic with HTTP 429, ideally with a Retry-After header.
- Algorithms: fixed window (simple, 2x edge burst), sliding window (smooth), token bucket (controlled bursts), leaky bucket (smooth output).
- Where: at the edge or API gateway — the cheapest place to shed load before it reaches your app.
- Shared counter: in a distributed deployment the count must live in a fast shared store (Redis), or per-instance counters multiply the real limit.
- Not the same as shedding: rate limiting is per-client fairness; load shedding drops low-priority work under global overload.
The all-you-can-eat buffet with one rule
Picture a popular buffet. The food is plentiful, but there's one unspoken rule: take a reasonable plate, eat, come back for more. The system works because everyone paces themselves. Now imagine one person parks a shopping cart at the carving station and shovels everything in as fast as they can. Within minutes the trays are empty and everyone else goes hungry — not because there wasn't enough food, but because one person consumed it faster than the kitchen could refill. Rate limiting is the staff member who says 'one plate at a time, please.' It doesn't ration the total food; it caps how fast any single guest can take it, so the shared resource stays available to all.
The problem it solves
Without a limit, a single buggy script, an abusive user, or a traffic spike can consume all your capacity and take the service down for everyone. Rate limiting sets a ceiling on requests per client per unit time. It protects the backend, enforces fair usage across tenants, and defends against brute-force and denial-of-service abuse.
There are really three distinct dangers it guards against, and naming them separately helps you reason about where to apply it. The first is the accident — a client with a retry loop gone wrong, hammering you thousands of times a second without malice. The second is unfairness — in a shared, multi-tenant service, one heavy customer can crowd out everyone else unless each has a cap. The third is abuse — someone deliberately brute-forcing passwords or trying to flood you offline. One mechanism, a cap on request rate, addresses all three.
The core idea, plainly
You count a client's requests against an allowance and reject (or delay) anything over the line, usually answering with HTTP 429 Too Many Requests. The interesting part is how you count: in fixed windows, sliding windows, or with a bucket that refills over time. Each handles bursts and boundaries differently.
The simplest counter — and the gap it can't fill
The most obvious approach is a fixed window: count how many requests a client made this minute, reset to zero when the clock ticks over, reject anything past the cap. It's trivial and cheap. But it has a sneaky flaw that's a favourite interview question, and seeing the flaw motivates every smarter algorithm.
# One counter per key per time window. Reset when the window rolls over.
def allow(key, limit, window_s, now):
window = now - (now % window_s) # start of the current window
field = f"{key}:{window}"
count = redis.incr(field) # atomic increment
if count == 1:
redis.expire(field, window_s) # auto-clean when window ends
return count <= limit # over the cap? reject (429)
# Flaw: a client can send `limit` at :59 and another `limit` at :00 --
# that's 2x the limit across a ~1s span. Sliding window fixes this.Walk the flaw through slowly. Say the limit is 100 per minute. A client sends 100 requests at 12:00:59 — all allowed, that minute's counter hits 100. One second later the clock rolls to 12:01:00, the counter resets to zero, and the client fires another 100. In the span of about two seconds they got through 200 requests — double the cap — purely because the boundary between windows reset the count at the worst moment. The limit held for each window but failed across the seam between them.
The token bucket: allowing honest bursts
The most popular fix is the token bucket, and it's worth understanding because its behaviour matches what real APIs actually want. Imagine a bucket that holds up to capacity tokens and refills at a steady rate. Every request must take one token to proceed; if the bucket is empty, the request is rejected. Because the bucket can be full, a client who's been quiet can spend a burst all at once — but once drained, they're throttled to the steady refill rate.
def allow(client_id, rate, capacity, now):
b = bucket.get(client_id) or {"tokens": capacity, "ts": now}
# refill based on elapsed time, capped at capacity
b["tokens"] = min(capacity, b["tokens"] + (now - b["ts"]) * rate)
b["ts"] = now
if b["tokens"] >= 1:
b["tokens"] -= 1
bucket.set(client_id, b)
return True # allowed
return False # 429 Too Many RequestsThis is why token bucket feels fair to real users. A person loading a page fires a handful of requests in a quick burst, then goes quiet — the full bucket absorbs that burst gracefully. A runaway script, by contrast, drains the bucket and then hits the refill ceiling, getting throttled to exactly the sustained rate you allow. You get burst tolerance for legitimate spikes and a hard cap on sustained abuse, from two simple parameters.
Algorithms and their trade-offs
| Algorithm | How it works | Pros | Cons | Use when |
|---|---|---|---|---|
| Fixed window | Count per clock window (e.g. per minute). | Trivial to implement; low memory. | Allows 2x burst at window edges. | Rough limits where edge bursts are harmless. |
| Sliding window | Weighted count over a moving interval. | Smooths the boundary burst problem. | A bit more state and computation. | You need accurate, steady limits. |
| Token bucket | Tokens refill at a rate; each request spends one. | Allows controlled bursts; intuitive. | Two parameters (rate + capacity) to tune. | APIs that should tolerate short bursts. |
| Leaky bucket | Requests drain at a fixed rate from a queue. | Perfectly smooth output rate. | Delays rather than bursts; can add latency. | Protecting a downstream with a hard fixed rate. |
The pair that confuses people is token bucket vs leaky bucket — both use a 'bucket,' but they're opposites in spirit. A token bucket meters input: it lets a burst through as long as there are tokens, so the output can be spiky. A leaky bucket meters output: requests queue up and drain at a perfectly fixed rate, like water leaking from a hole, so no matter how bursty the arrivals, the downstream sees a smooth, constant trickle. Use token bucket when bursts are fine; use leaky bucket when a fragile downstream needs a strictly steady rate.
The gap a per-instance counter can't fill
Here's the mistake that silently defeats rate limiting in the real world. You write a perfect token-bucket limiter, deploy it, and it keeps a counter in each server's local memory. It tests fine. Then you scale out to four servers behind a load balancer — and your '100 per minute' limit quietly becomes '400 per minute,' because each server is counting independently and a client's requests get spread across all four.
The fix is a shared counter: the count must live in one fast store that every server reads and writes, so a client's requests are tallied against a single allowance no matter which server handles them. A fast in-memory store like Redis is the usual home, and the increment-and-check has to be atomic so two simultaneous requests can't both read '99' and both decide they're allowed.
-- Runs atomically inside Redis, so every app server shares one count.
-- Without this, 4 servers each keep a local counter and a client gets
-- 4x the intended limit -- the cap silently means nothing.
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local count = redis.call('INCR', key) -- one counter, all servers
if count == 1 then
redis.call('EXPIRE', key, window)
end
if count > limit then
return 0 -- reject -> 429
end
return 1 -- allowWhere to enforce it
Rate limiting lives most often at the edge or API gateway, before requests reach your application — cheapest place to shed load. The logic is the same as a bouncer at the door rather than deep inside the club: the earlier you reject an over-the-line request, the less of your valuable backend capacity it wastes. A request that's going to be rejected should die at the cheapest possible point.
Choosing: a quick decision guide
| Situation | Reach for | Why |
|---|---|---|
| Public API, bursts are normal | Token bucket | Tolerates honest spikes, caps sustained rate. |
| Must protect a fragile downstream | Leaky bucket | Emits a perfectly smooth, fixed rate. |
| Need precise, steady limits | Sliding window | No edge-of-window double burst. |
| Rough cap, simplicity wins | Fixed window | Trivial and cheap when edge bursts are harmless. |
| LLM / cost-sensitive API | Token/quota on tokens | Requests differ 100x in cost — limit on work, not count. |
Rate limiting is how a shared service stays fair and alive under pressure — it's the guardrail that keeps one noisy, buggy, or hostile client from spending everyone else's capacity.
Why it matters
- It enforces fairness across tenants so no single caller can monopolize a shared backend.
- It's a frontline defense against brute-force and denial-of-service abuse, shedding bad traffic cheaply at the edge.
- It protects expensive or fragile downstreams by capping the rate they ever have to absorb.
If ignored
- One buggy script or abusive user consumes all capacity and takes the service down for everyone.
- Per-instance counters quietly multiply the real limit by your server count, so the cap means nothing.
- A naive fixed window lets through double the intended traffic right at the window boundary.
Where it fits
- Sits at the edge or API gateway, before requests reach application logic — the cheapest place to say no.
- Relies on a shared fast store (like Redis) so the count is consistent across a server pool.
- Complements load shedding, which handles global overload rather than per-client fairness.
Related topics
- API gateway: the usual enforcement point for per-client limits
- Caching: the shared fast store that holds the distributed counter
- Message queues: queue overflow lets a burst wait instead of being hard-rejected
- Load balancing: spreads traffic, but needs a shared counter so limits still hold
Interview lens
Questions it unlocks
- Design a rate limiter for a public API.
- How do you stop one client from degrading service for everyone?
- Why did your 'per minute' limit let through double the traffic at :59?
60-second answer
I'd enforce limits at the API gateway with a token bucket, because it allows short, controlled bursts while capping the sustained rate. The counter has to live in a shared fast store so a client is limited across all servers, not per instance — a per-instance counter silently multiplies the limit by your server count. I'd avoid a naive fixed window because it permits a double burst at window edges; a sliding window or token bucket fixes that. Over the limit returns 429, ideally with a Retry-After header. Separately, I'd add load shedding so the system degrades gracefully under global overload, not just per-client.
Common traps
- Keeping per-instance counters so the real limit is multiplied by server count.
- Using a fixed window and getting caught by edge-of-window bursts.
- Confusing per-client rate limiting with system-wide load shedding.