Design a rate limiter
medium 45 minProtect services against overload, abuse and surprise bills.
See it run
Many gateways, one count: follow a request, a race, a failure, a hot caller and a second region.
Operations
One request
From the client to the answer.
Step 1 of 7
A request arrives
The client sends a request with its key.
Step 1: A request arrives
def handle(request): caller = verify(request.token) rule = rules.find(request.path, request.method, caller.plan) ok, left, wait = redis.script(key(caller, rule), rule) if not ok: return 429, {"Retry-After": wait} return forward(request, remaining=left)- Extra time
- about 1 ms
- Error
- None
Rules in memory, counts in Redis.
In the real world
The same design a rate limiter doing real jobs. Pick one and step through it.
A ticket sale begins and scripts try to buy everything.
Step 1 of 3
Before
| Tries | Passed | |
|---|---|---|
| People | - | - |
| Scripts | - | - |
5 booking tries a minute per account, 300 a minute per address.
Step 1: Before
Common mistakes
The bugs interviewers watch for, with the fix beside each.
GET, then SET
criticalParallel requests read the same number and all pass.
Wrongn = redis.get(key)if n < limit: redis.set(key, n + 1)Rightok = redis.script(BUCKET, key, limit)Expiry in a second call
majorIf the process stops in between, the key stays and the caller is blocked for ever.
Wrongn = redis.incr(key)if n == 1: redis.expire(key, 60)RightINCR and EXPIRE in one scriptWaiting for Redis
criticalA slow helper makes every request slow.
Wrongredis = Redis() # default timeoutRightredis = Redis(timeout="5 ms")fallback = local_limitA missing plan matches
majorCallers without a plan slip under a rule made for others.
Wrongif rule.tiers and tier and tier not in rule.tiers: skipRightif rule.tiers and tier not in rule.tiers: skip
Interview tips
Explain it in one line
- Many gateways share one count with one atomic step, and have a plan for its failure.
REDIS
- Redis for a shared count, Expire keys.
- Distribute, Include headers, Script.
Good numbers
- 350,000 checks a second, 12 shards.
- 3 GB of buckets.
- 5 ms timeout.
Expect these questions
- What if Redis is down?
- What about one huge caller?
- One limit for two regions?