Cap the rate at which a user / IP / API key can hit a service.
bucket holds N tokens
refills at rate R tokens/sec
request -> if bucket >= 1: consume, allow
else: reject (HTTP 429)
class TokenBucket:
def __init__(self, rate, capacity):
self.rate = rate
self.cap = capacity
self.tokens = capacity
self.last = time.monotonic()
def allow(self):
now = time.monotonic()
self.tokens = min(self.cap, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
A turnstile at a stadium: refills with tokens, lets one person per token. Bursts allowed up to capacity.
Interview tip: Specify rate, capacity, and what HTTP header you send back on rejection.