Skip to content

About

Thread-safe token-bucket rate limiter in Python with per-key buckets and a throttling demo CLI

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

Token-Bucket Rate Limiter

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.

The problem

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.

Design decisions

  • 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 — RateLimiter keeps 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() returns False immediately instead of waiting forever.

Quick start

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)

Run the demo

python demo.py --rate 3 --capacity 6 --clients 3 --requests 20

Run the tests

pip install -r requirements.txt
pytest -v

Tech stack

  • Python 3.10+ (standard library only: threading, time)
  • pytest for the test suite

License

MIT

About

Thread-safe token-bucket rate limiter in Python with per-key buckets and a throttling demo CLI

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages