← Back to Python, page 5

python-0095 · Hard senior

Design a token-bucket rate limiter for an API, in process first and then shared across servers.

A token bucket holds up to capacity tokens and refills at a fixed rate; each request takes a token or is rejected with HTTP 429 and a Retry-After header. It allows short bursts while enforcing an average rate. With several servers, keep the bucket state in a shared store such as Redis and update it atomically with a Lua script.

Full answer
python
class TokenBucket:
    def __init__(self, rate, capacity, clock):
        self.rate, self.capacity, self.clock = rate, capacity, clock
        self.tokens, self.updated = capacity, clock()
    def allow(self):
        now = self.clock()
        self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
        self.updated = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False
    def retry_after(self):
        return max(0.0, (1 - self.tokens) / self.rate)

t = [0.0]
bucket = TokenBucket(rate=2, capacity=3, clock=lambda: t[0])
print([bucket.allow() for _ in range(4)], bucket.retry_after())
t[0] = 1.0
print([bucket.allow() for _ in range(3)])

Output:

text
[True, True, True, False] 0.5
[True, True, False]

With a capacity of 3, the first three requests at time 0 pass as a burst and the fourth is rejected; the limiter reports that one token arrives in 0.5 seconds at 2 tokens per second. After one second, two tokens have been added, so two more requests pass and the third fails. The injected clock makes the behaviour testable.

Across servers, design points are: key buckets per user or API key; store tokens and timestamp in Redis and update them in one atomic Lua script to avoid races; set expiry on idle keys; return 429 with Retry-After and rate-limit headers; decide whether to fail open or closed if Redis is down; and consider a sliding-window counter when exact per-minute limits matter more than burst handling.

python
class TokenBucket:
    def __init__(self, rate, capacity, clock):
        self.rate, self.capacity, self.clock = rate, capacity, clock
        self.tokens, self.updated = capacity, clock()
    def allow(self):
        now = self.clock()
        self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
        self.updated = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False
    def retry_after(self):
        return max(0.0, (1 - self.tokens) / self.rate)

t = [0.0]
bucket = TokenBucket(rate=2, capacity=3, clock=lambda: t[0])
print([bucket.allow() for _ in range(4)], bucket.retry_after())
t[0] = 1.0
print([bucket.allow() for _ in range(3)])

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Token buckets allow bursts within an average rate
  • Refill lazily from elapsed time
  • Return 429 with Retry-After
  • Atomic updates in a shared store across servers
  • Decide fail-open versus fail-closed

Common mistakes

  • Per-process limits behind a load balancer
  • Read-modify-write races in Redis

Follow-ups

  • How does a sliding-window log differ?
  • How would you rate limit per tenant and globally?

Tips

  • Use an injected clock