A small, thread-safe token-bucket rate limiter in Python, with per-key buckets and a CLI demo that shows it throttling simulated API traffic.
Any public API needs to stop one client from hogging everything. The classic answer is the token bucket: each client gets tokens at a fixed rate and spends one per request. Bursts are allowed up to the bucket capacity, sustained traffic is capped at the refill rate. I wanted a dependency-free implementation I actually understand, instead of pulling in a framework.
- Lazy refill on a monotonic clock — tokens are topped up from
time.monotonic()on every operation, so idle buckets cost nothing. No background threads, no timers to clean up. - One lock per bucket, never held while waiting —
acquire()takes the lock only to check-and-decrement. Blocking waits sleep outside the lock in short slices, so a timeout is honoured promptly and other threads are never stalled by a waiter. - Per-key manager with lazy bucket creation —
RateLimiterkeeps one bucket per key (client id, IP, …) and creates them on first use, so you only pay for keys that actually show up. - Oversized requests fail fast — asking for more tokens than the capacity can never succeed, so
acquire()returnsFalseimmediately instead of waiting forever.
from rate_limiter import RateLimiter
limiter = RateLimiter(capacity=100, refill_rate=10) # 10 req/s, burst of 100
if limiter.acquire("client-42"):
handle_request()
else:
return_429()Blocking until a token is available (with a timeout):
limiter.acquire("client-42", blocking=True, timeout=2.0)python demo.py --rate 3 --capacity 6 --clients 3 --requests 20pip install -r requirements.txt
pytest -v- Python 3.10+ (standard library only:
threading,time) - pytest for the test suite
MIT