AlgoViz

Rate limiter algorithms

medium 30 min

Token bucket, leaky bucket, fixed window, sliding log and sliding counter: how each one counts, what it lets through, what it stores, and which to choose.

See it run

Follow tokens, queues and windows call by call, with every number worked out.

Operations

Token bucket

Capacity 10, refill 2 a second.

Step 1 of 8

Full

Our systemClientt = 0 sAPI gateway2 tokens a secondService
Tokens of 10
10

calls

The bucket starts with 10 tokens.

Step 1: Full

def allow(n, now):    tokens = min(10, tokens + (now - last) * 2)    last = now    if tokens >= n:        tokens -= n        return True    return False
Stored
2 numbers
Bursts
Up to 10

Refill first, then decide.

In the real world

The same rate limiter algorithms doing real jobs. Pick one and step through it.

100 calls at 00:59 and 100 at 01:01, limit 100 a minute.

Step 1 of 4

Fixed window

00:5901:01
Fixed window100100

All 200 pass.

Step 1: Fixed window

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Check, then count

    critical

    Two calls read the same number and both pass.

    Wrong
    n = get(key)if n < limit: set(key, n + 1)
    Right
    one atomic step in the store
  • Losing the fraction

    major

    Under steady load a bucket that rounds down never leaks or refills.

    Wrong
    leaks = int(elapsed * rate)last = now
    Right
    leaks = int(elapsed * rate)last += leaks / rate
  • Counting refused calls

    major

    A caller who keeps trying stays blocked for ever.

    Wrong
    log.append(now)return len(log) <= limit
    Right
    if len(log) >= limit: return Falselog.append(now)
  • Forgetting the idle gap

    minor

    After an hour of silence the count of an hour ago is treated as the previous minute.

    Wrong
    previous = current
    Right
    previous = current if window == last + 1 else 0

Interview tips

  • Explain it in one line

    • Buckets model a supply, windows count in a stretch of time.
  • BLAST

    • Buckets, Leaky is smooth.
    • Allow bursts with tokens, Sliding, Token as default.
  • Good numbers

    • At most C + r × t.
    • Edge of a fixed window: 2 × limit.
    • Counter: prev × (1 - part) + cur.
  • Expect these questions

    • Why not a fixed window?
    • How much memory for ten million?
    • How long must the caller wait?