Rate limits and quotas in APIs
easy 22 minA limit is part of an API's contract.
See it run
See a limit from both sides: what the server counts and answers, and what a good client does next.
Operations
A bucket, seen from outside
Capacity 100, refill 10 a second, 15 tokens for each request.
Step 1 of 7
Full bucket
- Tokens of 100
- 100
requests
The client starts with a burst of 100 tokens.
Step 1: Full bucket
def take(bucket, n, now): bucket.tokens = min(100, bucket.tokens + (now - bucket.last) * 10) bucket.last = now if bucket.tokens >= n: bucket.tokens -= n return 200 wait = (n - bucket.tokens) / 10 return 429, {"Retry-After": ceil(wait)}- Refused with
- 429 + Retry-After
- Client does
- Waits
- How it is built and shared
- see the rate limiter topic
Two numbers: burst size and refill rate.
In the real world
The same rate limits and quotas in apis doing real jobs. Pick one and step through it.
600 calls with a limit of 60 a minute.
Step 1 of 3
As fast as possible
| Passed | Refused | |
|---|---|---|
| At once | 60 | 540 |
| Paced | - | - |
The script sends 600 at once. 60 pass and 540 are refused.
Step 1: As fast as possible
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Retrying at once
criticalThe retries are extra load on a service that has none to spare.
Wrongwhile send().status == 429: passRightr = send()if r.status == 429: sleep(r.retry_after * (1 + random() * 0.1))Taking before all limits are checked
majorA refused request still uses a call, and the caller cannot understand the numbers.
Wrongcalls += 1if tokens_used + n > tpm: return 429Rightif calls + 1 > rpm or tokens_used + n > tpm: return 429take_from_all()Check, then spend
criticalTen parallel calls all see room and all pass.
Wrongif spent(account) < budget: call_provider()Rightif reserve(account, estimate): # atomic call_provider() settle(account, real)Trusting a caller's own header
criticalA client can send a new user ID with every call and never be limited.
Wrongwho = request.headers["X-User-ID"]Rightwho = verify(request.token).account
Interview tips
Explain it in one line
- A limit is a promise to all callers and a rule for each.
- Say no with a reason and a waiting time.
BUCKET
- Burst, Usage, Cost.
- Quota, Enforce, Track.
Good numbers
- Gap = time to reset / remaining.
- Wait = (needed - have) / refill.
- Warn at 50, 75, 90 and 100%.
Expect these questions
- Which key do you count by?
- What does the client do on 429?
- How do you add limits to a live API?