To design a rate limiter is to build a component that decides, for every incoming request, whether the caller has used up its share and must wait. A good answer explains which algorithm counts the requests, what the limit is attached to, how several servers share one count, what happens when the counting store fails, how expensive requests are charged, and how clients are told to slow down.
This lesson designs the limiter in front of ResultsAPI, the service that 60,000 students hit when their exam results are published. Six runnable programs in Java, with Python and C++ versions, test the decisions interviewers probe most: the counting algorithm, counting across nodes, the limit key, failure of the store, the cost of a request, and layered limits. All rates, failure times and capacities are assumptions chosen to make comparisons clear, not benchmarks of a product.
Key takeaways
With a limit of 20 requests per 30 s and bursts of 40 around every window boundary, a fixed window let 29 requests through in one 30 s span, a sliding window log exactly 20, a sliding window counter 24 and a token bucket 39. The log needed 20 timestamps per client, the others 2 or 3 numbers.
Reading a count and writing it back later let all 200 windows go over a limit of 100 (worst 115). One atomic increment let none go over. Splitting the limit 25 per node refused 84 requests that had quota left, because one node got 40% of the traffic.
A limit of 10 requests a minute per IP refused 8,894 students in 10 minutes, all of them behind one hostel address, and still let a rotating-IP scraper through at 2,341 a minute. A limit per account refused no student and held that scraper to 10 a minute. An attacker with 100 accounts still got 1,000 a minute, until a shared cap of 300 a minute for new accounts held that attacker to 290.
When the counter store was down for 60 s, failing open let the backend be overloaded for the whole 60 s and 65% of student requests failed. Failing closed failed 100% of them. Local counters on each node failed none.
Limiting by request count let five heavy clients push the average load to 2,382 units a second against a capacity of 1,000. Limiting by work, 100 units a second per client, brought it to 882.
A limit of 600 a minute alone let five scraper bursts push the backend over capacity for 6 seconds. Adding a limit of 40 a second removed that and refused no normal request. A limit of 20 a second refused 1,980 normal requests.
1. Clarifying Requirements
Functional requirements
Allow a limited number of requests per client in a time window, with different limits for different routes and plans.
Refuse requests over the limit quickly, with a clear status code and a hint about when to retry.
Let operators change limits without a deployment.
Non-functional requirements
The check must add only a millisecond or two to every request.
The count must be correct when many gateway nodes serve the same client.
A failure of the limiter must not take the whole API down.
Normal users must not be refused by mistake.
Ask what the limit is for: protecting the backend from overload, being fair between users, enforcing a paid plan, or stopping abuse. The answer changes the key, the algorithm and what to do when the limiter fails.
2. Back-of-the-Envelope Estimation
Traffic: 60,000 students, each refreshing every 20 s at the peak, is 3,000 requests a second.
Rule: 20 requests per 30 s per student. A normal student sends about 1.5 requests in 30 s, so a scraper stands out.
State: 60,000 keys at about 60 bytes each is 3.6 MB, and one atomic update per request is 3,000 operations a second.
The load is small for one store node. The risks are failure, races and the choice of key.
3. Core APIs
The limiter is not usually called as an API by clients. It sits in the request path and talks to them through status codes and headers.
Every reply carries
RateLimit-Limit: 20,RateLimit-Remaining: 7andRateLimit-Reset: 12, so a client can see its budget.A refused request gets
429 Too Many RequestsandRetry-After: 12(seconds).An internal rules API:
PUT /v1/rules/results-readwith{"key": "student", "limit": 20, "window_s": 30, "algorithm": "token_bucket"}. The gateway nodes load the rules and refresh them when they change.
4. High-Level Design
Each gateway node builds a key from the request (for example the student id and the rule name), updates a counter for that key and either forwards the request or answers 429. The counters live in a shared store so that all nodes see the same count. A rules service holds the limits.
A refused request never reaches the backend.
One atomic update gives the new count and the time left.
Gateway nodes, a shared store and a rules service.
Where to put it. A limiter can run in the client library (cheap, and a client can ignore it), at the gateway or load balancer (one place, sees all traffic, protects every service), or inside each service (knows the real cost of a request, and runs after the work to reach it has started). Most systems use the gateway for the coarse limit per client and a limit inside a service for its own expensive operations. Refusing early, at the edge, is what protects the backend.
5. Counting Algorithms
Four algorithms are common. A fixed window counter counts requests in each clock window and resets at the boundary. A sliding window log keeps a timestamp for every accepted request and counts those in the last window. A sliding window counter keeps the current and the previous window counts and weights the previous one by how much of it still overlaps. A token bucket holds up to a capacity of tokens that refill at a steady rate, and each request takes one.
The first program sends one client's traffic against a limit of 20 per 30 s. At every window boundary the client sends 20 requests in the 2 s before it and 20 in the 2 s after it (the burst that fixed windows handle worst), plus about one request every 3 s in between. Over 600 s that is 999 requests. The program feeds the same requests to all four algorithms and measures the most requests accepted in any 30 s span and in any 1 s span.
Output
999 requests from one client over 600 s, limit 20 per 30 s, bursts of 40 around every window boundary.
algorithm accepted rejected worst 30 s worst 1 s state per client
fixed window counter 400 599 29 15 2 numbers
sliding window log 396 603 20 13 20 timestamps
sliding window counter 400 599 24 10 3 numbers
token bucket 419 580 39 11 2 numbers
Fixed window counter: 400 accepted, and 29 in the worst 30 s span. The limit is 20 per window, but a burst at the end of one window and the start of the next gets through. The theoretical worst case is twice the limit. Here it was 29, because the ordinary traffic had already used part of the quota before the boundary burst.
Sliding window log: 396 accepted and exactly 20 in the worst span, at the cost of storing up to 20 timestamps per client.
Sliding window counter: 400 accepted and 24 in the worst span, with only 3 numbers per client. It is an approximation, because it assumes the previous window's requests were spread evenly.
Token bucket: 419 accepted and up to 39 in the worst 30 s span, with 2 numbers per client. It lets a client spend a full bucket at once and then limits the long-run rate. The most it can pass in a window is the capacity plus one window of refill.
A token bucket by hand. Take a bucket with a capacity of 4 tokens that refills at 1 token every 10 seconds (0.1 a second) and starts full. Requests arrive at seconds 0, 1, 2, 3, 4 and 10. At second 0 the bucket has 4 tokens, the request takes one and 3 are left. At second 1 it has 3.1 and 2.1 are left after the request. At second 2 it has 2.2 and 1.2 are left. At second 3 it has 1.3 and 0.3 are left. At second 4 it has 0.4, which is less than 1, so the request is refused with Retry-After: 6, because 0.6 more tokens take 6 seconds to arrive. At second 10 the bucket has 0.4 + 0.6 = 1.0 token, so the request is allowed and 0 are left. Only two numbers are stored: the token count and the time of the last update.
Strictness against state per client, and whether bursts are allowed.
Choose a token bucket when short bursts are fine and the long-run rate is what matters, which suits most public APIs. Choose a sliding window log or counter when the limit must be strict inside every window. A fixed window is the simplest and the cheapest, and it is acceptable when a boundary burst of up to twice the limit does no harm.
6. Counting Across Nodes
With several gateway nodes, the counter has to be shared or the limit is applied per node. The usual store is Redis. The trap is a check that reads the count, decides, and writes the new count in separate steps: two nodes can read the same value and both allow the request. The count and the decision have to happen in one atomic step, such as INCR on a key that expires with the window, or a short Lua script for a token bucket.
The second program runs 200 windows of 10 s with a limit of 100. Between 120 and 399 requests arrive in each window, spread over 10 s, and go to 4 limiter nodes. Node 0 gets 40% of them and the others 20% each. The shared store has a round trip of 1 to 5 ms. It compares four ways to count.
Output
200 windows of 10 s, limit 100 per window, 4 limiter nodes, 120-399 requests per window.
counting method windows over worst average requests refused
the limit accepted accepted with quota left
read, then write (not atomic) 200 115 106.3 0
atomic increment 0 100 100.0 0
split: 25 per node 0 100 99.5 84
local counts, sync every 500 ms 184 117 104.3 0
Read the count, then write it: all 200 windows went over the limit. The worst accepted 115 requests for a limit of 100 (average 106.3), because several requests read the same old count within the round trip.
One atomic increment: never over the limit. Exactly 100 were accepted in every window.
Split the limit, 25 per node: never over, but 84 requests were refused while quota was left, because node 0 saw more than a quarter of the traffic and used up its 25 early.
Local counts synced every 500 ms: 184 windows went over, worst 117. Between syncs each node spends as if it were the only one. It is fast and approximate.
Do the check and the update in one step, in one place.
A sketch in Redis
The two usual shapes are below. They are shown for the form of the call and were not run in this lesson. Both run as one script inside Redis, so the check and the update cannot be split between two nodes. The token bucket reads the time from the Redis server (TIME), not from the gateway node, so that gateway clocks that disagree cannot change the result (Redis 5 or later).
-- fixed window: KEYS[1] = key, ARGV[1] = window in seconds
local n = redis.call('INCR', KEYS[1])
if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
return n
-- token bucket: KEYS[1] = key, ARGV = capacity, tokens per second, cost
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local capacity, rate, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or capacity
local ts = tonumber(b[2]) or now
tokens = math.min(capacity, tokens + (now - ts) * rate / 1000)
local allowed, retry = 0, 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
retry = math.ceil((cost - tokens) / rate)
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / rate) * 2)
return {allowed, retry}
The script returns whether the request is allowed and, when it is not, the seconds to put in Retry-After. The key expires after the bucket would have refilled, so idle clients cost no memory. One hot key (a single client that sends a flood) lands on one Redis shard, which is acceptable because a flood is exactly what is being cut off, but it is worth watching that shard.
An atomic shared counter is the safe default. Local counters with periodic sync are a good choice when the limit is large and a small overshoot is acceptable, because they avoid a store call on every request. Splitting a limit evenly across nodes only works when the load balancer spreads traffic evenly.
7. Choosing the Key
A limit is always attached to a key: an IP address, a user or account, an API key, or a combination. The key decides who is limited and who can get around the limit. An IP address is available before login but is shared by everyone behind a NAT (a hostel, an office, a mobile carrier) and is cheap for an attacker to change. An account id is exact and needs a logged-in request. The question is who you are willing to refuse by mistake.
The third program has 1,000 students on the ResultsAPI. 200 of them live in one hostel and share one public IP; the other 800 have their own. Every student sends 1 to 8 requests a minute. Attacker A uses one account and 3,000 requests a minute over 500 rotating IPs. Attacker B has 100 accounts and sends 30 a minute from each, also over the rotating IPs. It runs for 10 minutes with four rules.
Output
1000 students (200 behind one hostel IP), attacker A: 3000 requests a minute from 1 account, attacker B: 3000 a minute from 100 accounts, 10 minutes.
limit key students of them in attacker A attacker B students refused
refused the hostel accepted per accepted per per 1000 requests
(10 min) minute minute
10 a minute per IP 8894 8894 2341 2372 198
10 a minute per account 0 0 10 1000 0
10 per account, 1000 per IP 0 0 10 1000 0
10 per account, 300 for new 0 0 10 290 0
10 a minute per IP: 8,894 student requests were refused, all from the hostel (198 per 1,000 student requests overall). Attacker A got through at 2,341 a minute and attacker B at 2,372, because each rotating IP stayed under 10.
10 a minute per account: no student was refused and attacker A was held to 10 a minute. Attacker B still got 1,000 a minute, 10 for each of its 100 accounts.
10 per account and 1,000 per IP: the same results, so a generous IP limit changes nothing for either attacker. It is still useful as a cheap backstop for requests that have no account yet.
10 per account, and 300 a minute shared by all accounts created in the last hour: no student was refused (none of them is new), attacker A still got 10 a minute, and attacker B was held to 290 a minute instead of 1,000. A and B share the 300.
An IP limit punishes shared addresses and misses rotating ones.
Use the strongest identity the request has, and a loose IP limit as a backstop. A per-key limit does not cap the total an attacker can reach by creating many keys, so limit account creation, require verification and, as in the last rule above, put a shared cap on the group of new or unverified accounts. The cap is worth having only if few real users are new at any moment. On the day a new batch of students signs up it would refuse them.
8. When the Counting Store Fails
The limiter is now on the path of every request, so its failure is an outage of the API unless you decide in advance what to do. There are three options. Fail open lets every request through. Fail closed refuses them all. A local fallback keeps limiting with an in-memory counter on each node, which cannot see the other nodes and is therefore approximate.
The fourth program runs the ResultsAPI for 600 s. The backend can serve 800 requests a second and fails the rest. Real students send 250 to 349 a second. From second 100 to 399 a scraper sends 1,800 to 2,199 a second, and while the limiter works it lets the scraper through at 100 a second. The counter store is down from second 200 to 259.
Output
The counter store is down for 60 s while a scraper is active. Backend capacity 800 requests a second.
limiter during outage student reqs student reqs scraper reqs peak load seconds backend
failed failed (%) served (a second) overloaded
fail open 12138 65 41592 2529 60
fail closed 18486 100 0 449 0
local counters per node 0 0 9600 509 0
Fail open: the scraper's requests flooded the backend. Peak load was 2,529 a second and the backend was overloaded for all 60 s. 12,138 student requests (65%) failed and 41,592 scraper requests were served.
Fail closed: the backend stayed safe at a peak of 449, and 100% of student requests failed (18,486).
Local counters on each node, 40 a second per node: no student request failed, the scraper was served at 160 a second (9,600 in 60 s) and the peak load was 509.
Neither fail open nor fail closed is right on its own.
A local fallback is the usual answer for a protective limiter, because the point of the limit is to protect the backend. For a limiter that enforces a paid quota, failing open for a short time is often acceptable. For a security limiter, such as one on a login endpoint, failing closed may be right. Say which you chose and why, set a short timeout on the store call so that a slow store does not slow the API, and alert when the limiter switches to its fallback.
9. Limiting by Cost
Counting requests treats a request for a marks lookup the same as a request for a marksheet PDF, but the PDF may need twenty times the work. A cost-based limiter charges each request a number of units (tokens) according to its expected cost and limits the units.
The fifth program has a backend that can do 1,000 units of work a second. A cheap request costs 1 unit and an expensive one, the marksheet PDF, costs 20. Thirty normal clients send 0 to 9 requests a second, and 1 in 10 of them is expensive. Five heavy clients send 20 expensive requests a second each. It runs for 60 s with two rules.
Output
30 normal clients and 5 heavy clients for 60 s. Backend capacity 1000 units a second.
limit per client average peak seconds over normal reqs heavy reqs
load load capacity refused served
25 requests a second 2382 2595 60 0 6000
100 units a second 882 1095 5 0 1500
25 requests a second per client: every heavy request was served (6,000) and the average load was 2,382 units a second. The peak was 2,595 and the backend was over capacity for all 60 seconds.
100 units a second per client: each heavy client was held to 5 expensive requests a second (1,500 served in total) and the average load was 882. The peak was 1,095, with 5 seconds over capacity, when many normal clients happened to burst together.
No normal request was refused under either rule.
Charge for the work, not for the request.
The cost of a request must be known before it runs. Use a fixed cost per route, or a cost class from the request (a page size, a file size). A limit on cost also gives you a natural way to price plans.
10. Layered Limits
A single limit has one window, and a window that suits one kind of abuse misses another. A limit of 600 a minute lets a client send all 600 in the first few seconds. Rate limiters therefore combine a per-minute limit for the sustained rate with a per-second limit that caps how fast a burst can arrive. The per-second limit has to be set above the largest burst a real user makes.
The sixth program has 35 normal clients and 5 scrapers for 120 s against a backend that can serve 350 requests a second. A normal client sends 3 requests a second, and in 1 second out of 100 a page load makes a burst of 40 a second for 2 seconds. Each scraper sends 600 requests in a 5 s burst (120 a second) once a minute. Every rule keeps 600 a minute per client and adds a per-second limit.
Output
35 normal clients and 5 scrapers for 120 s. Backend capacity 350 requests a second.
limits per client peak load seconds over normal requests scraper requests
(a second) capacity refused accepted
600 a minute only 385 6 0 6000
+ 40 a second 305 0 0 3650
+ 20 a second 205 0 1980 2650
+ 10 a second 155 0 2970 2150
600 a minute only: the scrapers' bursts overlapped, the peak load was 385 and the backend was over capacity for 6 seconds. The scrapers got their full 600 a minute each (6,000 requests in total).
Add 40 a second: the peak fell to 305, no seconds were over capacity and no normal request was refused.
Add 20 a second: the peak fell to 205, but 1,980 normal requests were refused, because the page-load bursts of 40 were cut.
Add 10 a second: the peak fell to 155 and 2,970 normal requests were refused.
Set the short window just above the largest normal burst.
Choose the per-second limit from measured traffic: look at the 99.9th percentile of requests per second for real users and add some room. If real bursts are important, give the short window a token bucket with a capacity that matches the burst and a refill rate that matches the sustained rate.
11. Telling the Client
A rate limiter that only refuses is half a limiter. Return 429 Too Many Requests, and a Retry-After header with the number of seconds to wait, so that clients do not guess. Add rate-limit headers to normal replies, so that clients can see how much budget is left and slow down before they are refused. Document that clients should retry with exponential backoff and jitter, as in the lock-waiting example in Design a Distributed Locking Service, so that all the refused clients do not return at the same moment.
A clear refusal is the cheapest way to reduce the next wave of requests.
12. Choosing the Design
Start from what you are protecting.
| Concern | Choice | Watch for |
|---|---|---|
| Algorithm | Token bucket, or a sliding window when strict | Boundary bursts with fixed windows |
| Shared count | Atomic update in a shared store | Read-then-write races |
| Key | Account first, loose IP limit as backstop | Shared and rotating IPs |
| Store failure | Local fallback, short timeout, alert | Fail open under attack |
| Cost | Charge units per request | Unknown cost before the call |
| Bursts | Per-second and per-minute limits | A short limit below real bursts |
13. Trade-offs to Mention
A sliding log is exact and stores every timestamp; a counter or a bucket stores a few numbers and is approximate or burst-friendly.
A shared atomic counter is correct and adds a network call. Local counters are fast and overspend.
An IP key works before login and punishes shared addresses. An account key is precise and needs identity.
Failing open keeps users in and exposes the backend. Failing closed protects the backend and takes the API down.
Cost-based limits protect the backend better and need a cost for each route.
Tight per-second limits stop bursts and refuse real users.
14. Common Mistakes
Reading a counter and writing it back in separate steps.
Limiting only by IP address.
No plan for a failure of the counter store, or a store call with no timeout.
Counting requests when their costs differ a lot.
Setting a per-second limit below the bursts of normal users.
Refusing without a
Retry-Afterheader, so clients retry at once.Keeping limits in code, so that a change needs a deployment.
15. Interview Questions
Which algorithm would you use, and why? A token bucket for most APIs, because it allows short bursts and limits the long-run rate with two numbers per client. A sliding window when the limit must be strict inside every window.
How do you count across many servers? One atomic update in a shared store, such as an increment with an expiry or a Lua script. Local counters with sync trade accuracy for speed.
What do you limit on? The strongest identity available, and a loose IP limit as a backstop. Beware of shared and rotating IPs.
What happens if Redis goes down? Decide beforehand: a local fallback for a protective limiter, fail open or closed by the cost of each mistake, a short timeout and an alert.
How do you handle expensive requests? Charge units by cost and limit units.
How do you let normal bursts through but stop floods? Combine a per-minute limit with a per-second limit set just above the largest normal burst.
What does the client see? A 429, a Retry-After header and rate-limit headers.
16. Practice Problems
A token bucket has a capacity of 10 and refills 2 tokens a second. A client sends 25 requests at second 0. How many are allowed, and what
Retry-Afterdoes the 11th get? Answer: 10 are allowed. The 11th needs 1 token, which takes 0.5 s, so it getsRetry-After: 1(rounded up).A fixed window allows 100 requests a minute. A client sends 100 at 0:59 and 100 at 1:00. How many get through in 2 seconds? Answer: 200, twice the limit, because the two bursts fall in different windows.
The counter store answers in 2 ms at the median and 40 ms at the 99.9th percentile, and the gateway may spend 5 ms on the check. What do you do? Answer: set a timeout of about 3 ms and fall back to the local counter when it passes, count how often that happens and alert if it becomes common.
Limit a login endpoint. Answer: key on the account being attacked (a few attempts a minute, then a delay) and also on the IP with a looser limit, fail closed if the store is down because the cost of a wrong allow is high, and log every refusal.
Summary
Choose the algorithm from whether bursts are allowed and how much state you can keep.
Check and update the count in one atomic step in a shared store.
Limit on an account, with a loose IP limit as a backstop, and limit account creation.
Plan for the store failing, with a local fallback.
Charge by cost when requests differ.
Layer a per-second limit over a per-minute limit, and tell clients when to retry.
Conclusion
A rate limiter is a counter with consequences. The algorithm decides how bursts are treated, the shared store and its atomic update decide whether the count is right, the key decides who is hurt by mistake, and the failure rule decides whether the limiter protects the API or takes it down. In an interview, say what you are protecting, pick the key and the algorithm for it, and back each choice with a number.
Previous topic: Design a URL Shortener. Next topic: Design Pastebin.
References and further reading
RFC 6585 (the 429 Too Many Requests status code) and RFC 9110 (the Retry-After header). The IETF draft on RateLimit header fields for HTTP.
Stripe engineering blog, Scaling your API with rate limiters (2017), on request, concurrency and load-shedding limiters. Cloudflare blog posts on how rate limiting is built at scale.
The Redis documentation on
INCR, key expiry and Lua scripts, and the documentation of Nginxlimit_req, Envoy rate limiting and Kong, for token-bucket and window implementations.Design a Distributed Locking Service and Design Message Queue on this site, for retry, backoff and failure-handling ideas used here.