AlgoViz

Design a rate limiter

medium 75 min

A 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

0:00 / 4:49

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

handlercallerlimiterRateLimiterkeysashalockheldruleTokenBucketlimit1 in 2 sburst3try_acquire('asha')

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

old ruleTokenBucketburst10ashaTokenMetertokens5full10

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

    critical

    Two threads see the same last token.

    Wrong
    if bucket.tokens >= 1:    bucket.tokens -= 1
    Right
    with lock:    if bucket.wait(now, 1) == 0:        bucket.spend(now, 1)
  • A thread that refills every bucket

    major

    A million keys, a million updates a second, most for nobody.

    Wrong
    while True:    for b in buckets: b.tokens += 1    sleep(1)
    Right
    passed = now - self._atself._credit += passed * self._rule.limit
  • The wall clock

    major

    It jumps when it is corrected. Limits freeze or open.

    Wrong
    now = time.time()
    Right
    now = time.monotonic_ns()
  • One charge for each rule, one after another

    major

    A call refused by the second rule has already paid the first.

    Wrong
    return all(r.try_take() for r in rules)
    Right
    wait = max(m.wait(now, 1) for m in meters)if wait == 0:    for m in meters: m.spend(now, 1)
  • Keys that never leave

    critical

    Whoever can choose keys can fill the memory.

    Wrong
    self._buckets = {}   # only grows
    Right
    if 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.