Design a rate limiter
medium 75 minA rate limiter inside one process: token bucket behind an interface, exact under threads, several rules at once, and keys that are safely forgotten.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
A bucket for each key, filled by the clock and not by a thread.
Operations
Allowed
The first call of a key: a full bucket, one token less.
Step 1 of 5
One question
May asha go? The handler knows only the limiter.
Step 1: One question
def try_acquire(self, key, cost=1): for rule in self._rules: rule.check_cost(cost) lock, table = self._stripes[hash(key) % len(self._stripes)] with lock: now = self._clock() meters = table.get(key) if meters is None: meters = table[key] = [rule.start(now) for rule in self._rules] wait = max(m.wait(now, cost) for m in meters) if wait == 0: for m in meters: m.spend(now, cost) left = min(m.left(now) for m in meters) return Decision(wait == 0, left, wait)- Cost
- O(rules)
- Guarantee
- One small meter
- A refill thread
- wakes for keys that nobody uses
The rule is shared. Only the meter belongs to a key.
In the real world
The same rate limiter doing real jobs. Pick one and step through it.
burst goes from 10 to 4 while a key has 5 left.
Step 1 of 3
Half full
The key has used 5 of 10.
Step 1: Half full
def set_rule(self, rule, now): self._drip(now) share = Fraction(self._credit, self._full) self._rule = rule self._full = rule.burst * rule.per_ns self._credit = int(share * self._full)Common mistakes
The bugs interviewers watch for, with the fix beside each.
Ask, then spend, without one lock
criticalTwo threads see the same last token.
Wrongif bucket.tokens >= 1: bucket.tokens -= 1Rightwith lock: if bucket.wait(now, 1) == 0: bucket.spend(now, 1)A thread that refills every bucket
majorA million keys, a million updates a second, most for nobody.
Wrongwhile True: for b in buckets: b.tokens += 1 sleep(1)Rightpassed = now - self._atself._credit += passed * self._rule.limitThe wall clock
majorIt jumps when it is corrected. Limits freeze or open.
Wrongnow = time.time()Rightnow = time.monotonic_ns()One charge for each rule, one after another
majorA call refused by the second rule has already paid the first.
Wrongreturn all(r.try_take() for r in rules)Rightwait = max(m.wait(now, 1) for m in meters)if wait == 0: for m in meters: m.spend(now, 1)Keys that never leave
criticalWhoever can choose keys can fill the memory.
Wrongself._buckets = {} # only growsRightif all(m.is_fresh(now) for m in meters): del table[key]
Interview tips
Open with
- Per what? Key.
- How many, in how long, and how many at once?
- Refuse or wait?
Say aloud
- The rule is shared, the meter belongs to a key.
- Time refills the bucket. No thread does.
Before they ask
- The edge of the fixed window.
- Two rules, and who pays when one says no.
- Memory with many keys.
Avoid
- Floats for tokens.
- Sleeping inside the lock.
- Talking about ten servers before one process works.