Requirements of a rate limiter
easy 24 minBefore choosing an algorithm, agree on the rules: who is counted, what counts, how strict the limit is, where it is checked, what a refused caller gets, how fast the check must be, and what happens when the limiter itself fails.
See it run
Each question in a picture: why, whom, where, how strict, and what if the limiter breaks.
Operations
Why: a spike
The same traffic with and without a limit of 100 a second.
Step 1 of 6
Normal
- Passed
- 10
- Refused
- 0
10 requests a second. All pass.
Step 1: Normal
rule = Rule(name="api", subject="account", limit=100, window="1 s")if count(rule, caller) >= rule.limit: return 429, retry_after(rule)return next(request)- Question
- Why?
- Decide by
- Goal
Name the goal before the number.
In the real world
The same requirements of a rate limiter doing real jobs. Pick one and step through it.
Who would be refused, before anybody is.
Step 1 of 3
Plan
| Accounts | |
|---|---|
| Under 60 | 9,940 |
| 60 to 200 | 55 |
| Over 200 | 5 |
Example numbers
Limit 60 a minute. Count for a week, refuse nobody.
Step 1: Plan
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Open for everything
criticalWith the store down, password guessing has no limit.
Wrongexcept Timeout: return allowRightexcept Timeout: return local_limit(rule) if rule.fail_open else refuseTrusting a forwarded header
criticalA client can write a new address into it for each call.
Wrongip = headers["X-Forwarded-For"].split(",")[0]Rightip = last_entry_added_by_our_proxy(request)No waiting time
majorClients guess, and try again at once.
Wrongreturn 429Rightreturn 429, {"Retry-After": seconds}Limits in the code
majorRaising one customer's limit needs a release.
WrongLIMIT = 100Rightlimit = rules.for_request(route, plan).limit
Interview tips
Explain it in one line
- Why, whom, how much, where, what answer, what on failure.
LIMIT
- Low time, Identify, Multiple rules.
- Inform, Track.
Good targets
- 2 ms extra, 5 ms timeout.
- 1% error.
- Rules live in 60 s.
Expect these questions
- Open or closed?
- By address or by user?
- How exact must it be?