Lesson 11 of 38Building blocks
Rate Limiting
Protect APIs with fixed window, sliding window, token bucket, and leaky bucket limits, enforced at the gateway with Redis.
Without a limit, one buggy script in a retry loop, one scraper, or one attacker guessing passwords can use up all your capacity and take the service down for everyone else. Rate limiting caps how many requests a client can make in a period of time. It shows up in every public API, it is a classic interview question in its own right ("design a rate limiter"), and it is a building block in most other designs.
Why rate limit
- Abuse and security: slow down credential stuffing on
/login, scraping, and denial-of-service floods. - Fairness: one heavy customer should not starve the others sharing the same servers.
- Cost: every request costs compute, and some cost real money downstream (SMS messages, AI model calls, paid third-party APIs).
- Stability: shed excess load early and cheaply instead of letting it overload the database.
A limit has three parts: who is limited (the key: API key, user id, IP address, or a combination), how much (100 requests per minute, 5 login attempts per 15 minutes), and what happens when they go over (usually reject with 429 Too Many Requests).
Where to enforce it
Client-side limits are polite but anyone can bypass them. The real enforcement belongs on the server, as early as possible: at the API gateway or edge, before the request costs you anything. Because there are many gateway instances, they share counters in a fast central store, almost always Redis.
A request arrives. The gateway increments the client's counter in Redis: INCR rl:key_abc:1728000060 returns 12. The limit is 100 per minute, so it is allowed.
The algorithms
There are four classic algorithms (one with two variants). Step through each with a limit of 3 requests per second.
Fixed window counter: split time into fixed windows (each whole second, each minute) and count requests in the current one. One counter per client per window; it resets when the window changes. It is the simplest to build, and the flaw shows up at the edges of windows.
Three requests late in the first window (0 to 1 s). Count hits 3, the limit.
Sliding window log: store the timestamp of every request. On each new request, drop timestamps older than one window, and allow it if fewer than the limit remain. Exact, but it stores every timestamp (memory grows with the limit).
Three accepted requests are in the log. The limit is reached.
Sliding window counter: a cheap approximation of the log. Keep just two counters, the previous window and the current one, and weight the previous one by how much of it still overlaps the sliding window.
estimate = previous_count × (1 − elapsed_fraction) + current_count
If the limit is 10 per minute, the previous minute had 8 requests, the current minute has 3, and we are 25% into it, then the estimate is 8 × 0.75 + 3 = 9, so the request is allowed. Two integers per client, and close to exact in practice. This is what many production limiters use.
Token bucket: each client has a bucket holding up to capacity tokens. Tokens drip in at a steady rate. Each request spends one token; no token, no request. It allows short bursts (up to the capacity) while enforcing the long-run average rate. AWS API Gateway and Stripe use token buckets.
The bucket starts full: 3 tokens.
Leaky bucket: requests enter a queue (the bucket) and are processed at a fixed rate, like water leaking from a hole. If the queue is full, new requests are dropped. Output is perfectly smooth, which suits protecting a fragile downstream system, but bursts wait in line instead of being served quickly.
Sliding window counter: previous window had 8 requests, current has 3, we are 25% into the current window. What is the estimate?
print(8 * 0.75 + 3)
| Algorithm | Memory per client | Bursts | Accuracy | Notes |
|---|---|---|---|---|
| Fixed window | 1 counter | Up to 2x at window edges | Rough | Simplest; INCR + EXPIRE |
| Sliding window log | Every timestamp | None | Exact | Expensive at high limits |
| Sliding window counter | 2 counters | Smoothed | Close to exact | Good default |
| Token bucket | Tokens + timestamp | Allowed up to capacity | Exact average rate | Most popular for APIs |
| Leaky bucket | A queue | Queued, output smooth | Exact output rate | Shapes traffic to a fixed rate |
Pick the algorithm for each requirement.
Token bucket in code
You never need a background timer. Each time a request arrives, compute how many tokens dripped in since the last request, add them (capped at capacity), then try to spend one.
Press Run (⌘ Enter) to see what happens.The burst of 5 passes, the next 3 are rejected, and after that exactly 2 requests per second get through.
Distributed rate limiting with Redis
With many gateway instances, the bucket or counter lives in Redis. A fixed window is two commands:
INCR rl:{api_key}:{current_minute} -> returns the new count
EXPIRE rl:{api_key}:{current_minute} 60 (only when the count is 1)For a token bucket, reading the tokens, refilling, and spending must happen atomically, or two gateways can both read "1 token left" and both allow a request. The standard way is a small Lua script that Redis runs as one atomic operation (or a library like redis-cell that does it for you).
Two practical decisions:
- Fail open or closed? If Redis is unreachable, most APIs fail open (allow requests) so a cache outage does not become a full outage. Login and payment endpoints may fail closed.
- Latency: one Redis round trip (about 0.5 ms in the same region) per request is usually fine. At extreme scale, gateways keep local counters and sync to Redis every few hundred milliseconds, accepting slightly fuzzy limits.
Telling clients: 429 and Retry-After
A rejected request gets 429 Too Many Requests, and good APIs say when to try again and how much quota is left, so well-behaved clients can slow down instead of hammering you.
GET /v1/search?q=boots
Put a gateway's rate limit check in order.
- Tap the steps below in the right order.
Design a rate limiter service: a 10-minute walkthrough
"Design a rate limiter" is often a full interview, or the deep dive inside a bigger one. You already have the algorithms. What the interviewer is testing now is whether you can turn them into a service that many teams use, that adds almost no latency, and that does something sensible when it breaks. Here is how to spend ten minutes on it.
Minutes 0 to 2: pin down the requirements
Ask before you draw. The answers change the design.
- What is limited, by what key? Per API key on a public API, per user on an app, per IP on login, per tenant for fairness. Often several at once.
- Hard or soft limits? A limit protecting a fragile database must be close to exact. A limit on a free tier can be off by a few percent and nobody cares.
- Scale. For example: 500,000 requests per second across 40 gateway instances in 3 regions, 20 million active keys.
- Latency budget. The limiter sits on every request, so it gets a tiny budget: well under a millisecond at p99 in the common case.
- What happens on failure? Ask it now, because the answer shapes everything below.
Say the numbers out loud: 20 million keys at roughly 100 bytes each (key name, two counters, an expiry) is about 2 GB, which fits in a small Redis cluster. 500,000 checks per second is too many for a single Redis node to handle comfortably with headroom, so the counters will be sharded.
Minutes 2 to 4: rules as configuration, not code
Teams should be able to add or change limits without a deploy. Limits live in a config file or a small rules store, the limiter reloads them on change, and each rule matches on descriptors (attributes of the request: route, plan, API key, IP). This is the shape Envoy's open source global rate limit service uses:
domain: public_api
descriptors:
# Every API key on the free plan: 100 requests per minute
- key: plan
value: free
descriptors:
- key: api_key
rate_limit: { unit: minute, requests_per_unit: 100 }
# Paid plan: 2,000 per minute
- key: plan
value: pro
descriptors:
- key: api_key
rate_limit: { unit: minute, requests_per_unit: 2000 }
# Login, per IP, regardless of plan: 5 per minute
- key: route
value: login
descriptors:
- key: remote_ip
rate_limit: { unit: minute, requests_per_unit: 5 }Two design points to mention. A single request usually checks several rules (a per-second burst limit, a per-day quota, and a per-IP rule on login), and it is allowed only if it passes all of them. And rules should support a shadow mode that logs "would have rejected" without rejecting, so a new limit can be tested against real traffic before it blocks paying customers.
Minutes 4 to 6: where the limiter runs
There are three placements, and the trade-off is latency against consistency.
| Placement | How it works | Good | Bad |
|---|---|---|---|
| In-process library | Each service imports a library that talks to Redis | No extra hop; simple for one team | Every language needs a library; every team configures it differently |
| Sidecar or gateway filter | A proxy next to each service (or the API gateway) calls the limiter before forwarding | One implementation for every language; central rules | One more component on the request path |
| Central limiter service | Gateways make an RPC to a dedicated rate limit service, which owns Redis | Single place for rules, metrics and storage | An extra network hop on every request; must be as available as the gateway |
A common production answer combines the last two: the gateway or sidecar (Envoy, for example) calls a central rate limit service over gRPC, and that service holds the rules and talks to a sharded Redis. Teams get one consistent behavior, and the storage details are hidden behind one API: "may this request with these descriptors proceed?"
A request arrives. The gateway extracts descriptors: plan=free, api_key=k_81, route=search.
Minutes 6 to 8: scaling the counters
Sharding. Spread counters across a Redis Cluster by key. Redis Cluster has 16,384 hash slots, and the key decides the slot, so one client's counters land on one node and the Lua script can run atomically there. If a script touches several keys, they must be on the same slot; a hash tag in braces (rl:{k_81}:minute, rl:{k_81}:day) forces that.
Hot keys. One huge customer, or one IP behind a big corporate NAT, can send a large share of all traffic, and all of it hits one Redis shard. Local counting and a deny cache take most of that pressure off.
Local counts with async sync. Instead of calling Redis on every request, each gateway counts locally, pushes its deltas to Redis every N milliseconds, and pulls back the global total. Latency drops to near zero and Redis load drops by orders of magnitude. The price is overshoot: between syncs, every gateway is working from a slightly old total, so the client can exceed the limit by roughly its request rate times the sync interval. Run it.
Press Run (⌘ Enter) to see what happens.A shared counter is exact. Syncing every 100 ms lets about 1% extra through; every 2 seconds, about 14%. For a free-tier quota that is a great trade. For "5 login attempts per minute" it is not, so strict, low-volume rules keep checking Redis directly while high-volume, soft rules use local counts. Saying that split out loud is a strong senior signal.
Minutes 8 to 10: failure modes and the edges
Fail open or fail closed, per rule. If Redis or the limiter service is slow or down, the gateway must decide in milliseconds. Set a tight timeout (a few milliseconds) and wrap the call in a circuit breaker, so a sick Redis is skipped quickly instead of adding latency to every request. Most rules fail open, because rejecting all traffic turns a limiter outage into a full outage. Rules that protect against abuse or cost (login attempts, password resets, sending SMS, expensive AI calls) fail closed or fall back to a strict local limit per gateway. Make it a field on the rule, not a global switch.
Multi-region. A single global Redis means cross-region round trips on every check, which breaks the latency budget. The usual answer is per-region counters with the quota split across regions (or a region-local limit plus a looser global reconciliation for daily quotas). Most clients are served from one region anyway, so the error is small.
Time. Fixed windows depend on agreeing what minute it is. Let Redis decide: compute the window inside the Lua script from Redis's own clock, rather than trusting 40 gateway clocks that drift.
Layers. A rate limiter is one layer of defense, not all of it. Volumetric floods are absorbed at the CDN or WAF before they reach you. The gateway enforces per-key limits. Inside each service, a concurrency limit or load shedder protects against the case where traffic is within every quota but the service is still overloaded. Covering all three shows you think about the system, not just the algorithm.
Token bucket rate limiter
Implement a token bucket, the rate limiter behind most API gateways.
- The bucket holds at most
capacitytokens and starts full. - Tokens refill continuously at
ratetokens per second, never abovecapacity. allow(now)is called for each request, withnowas the time in seconds. If at least one token is available, spend one and returntrue. Otherwise returnfalse(the API would answer429 Too Many Requests).
Time is passed in so the limiter is easy to test. now never goes backwards.
b = TokenBucket(capacity=2, rate=1)
b.allow(0) # True (2 -> 1 token)
b.allow(0) # True (1 -> 0)
b.allow(0) # False (empty)
b.allow(1) # True (refilled 1 token after 1 second)- rate limiting
- Capping how many requests a client can make per period, to protect capacity, fairness, and cost.
- fixed window
- Count requests per fixed time slot. Simple, but allows 2x bursts at window edges.
- sliding window counter
- Weights the previous window's count by its overlap to approximate a true sliding window cheaply.
- token bucket
- Tokens refill at a steady rate up to a capacity; each request spends one. Allows bursts, caps the average.
- leaky bucket
- Requests queue and drain at a fixed rate, smoothing traffic. Excess is dropped when the queue is full.
- 429 + Retry-After
- The response for a rate-limited request, telling the client how many seconds to wait.
- descriptor
- A request attribute (route, plan, API key, IP) that limiter rules match on.
- deny cache
- A gateway's local memory of keys already over their limit, so repeat offenders are rejected without a Redis call.
- fail open / fail closed
- Whether requests are allowed or rejected when the limiter itself is unavailable. Chosen per rule.