AI Hints
Home›System Design Tutorial›Rate Limiting
System Design · Lesson 35 of 120

Rate Limiter Algorithms

Token bucket and friends.

⏱ 2 min read▶ Video at 40:25🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

How does a limiter count? The most popular algorithm is the token bucket. It allows short bursts, but keeps the average rate under control.

Rate Limiter Algorithms
From the video: Rate Limiter Algorithms
  • How do we count?
  • The token bucket
  • Bursts, but a steady average

A token bucket

Each client has a bucket of tokens. Every request takes one token. Tokens drip back in at a fixed rate, up to the bucket's size. If the bucket is empty, the request is refused. Here the bucket holds three tokens, and refills one per second. Run it. A burst of five requests at once gets three through. A second later, one more is allowed.

bucket.pypython
class TokenBucket:
    def __init__(self, size, per_sec):
        self.size, self.rate = size, per_sec
        self.tokens, self.last = size, 0.0

    def allow(self, now):
        self.tokens = min(self.size, self.tokens + (now - self.last) * self.rate)
        self.last = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False

b = TokenBucket(size=3, per_sec=1)
for t in [0, 0, 0, 0, 0, 1.0, 1.0]:
    print(f"t={t}s  ->", "allowed" if b.allow(t) else "429")
Output
t=0s  -> allowed
t=0s  -> allowed
t=0s  -> allowed
t=0s  -> 429
t=0s  -> 429
t=1.0s  -> allowed
t=1.0s  -> 429

Other algorithms

There are other options. A fixed window counts requests per clock minute, which is simple, but allows double bursts at the edge of two windows. A sliding window fixes that, with a bit more work. And a leaky bucket processes requests at a perfectly steady rate, like water dripping from a hole.

AlgorithmBehaviour
Token bucketbursts allowed, steady average
Fixed windowsimple, edge bursts
Sliding windowsmooth, more memory
Leaky bucketperfectly steady output

Summary

The token bucket allows short bursts while keeping a steady average. It's the most popular rate limiting algorithm. Next, a quiz on scaling the web tier.

Key takeaways
  • Tokens drip in
  • Each request takes one
  • Empty means 429
Next up: Scaling Quiz — test yourself