PyrateLimiter is a Python library implementing the Leaky-Bucket Algorithm for rate limiting. It supports both synchronous and asynchronous workflows and offers various backends like in-memory, SQLite, Redis, and PostgreSQL for persistent limit tracking. Currently at version 4.1.0, it maintains an active development and release cadence, with several minor and patch releases in the last year.
pip install pyrate-limiterVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up a basic in-memory rate limiter with a single rate. It shows both blocking and non-blocking acquisition attempts.
Update `Limiter` initialization: `limiter = Limiter(Rate(X, Duration.Y))` for single rates or use `limiter = Limiter(BucketFactory(...))` for complex scenarios. Replace `RequestRate` with `Rate`.
Review the documentation for the specific bucket type or `Limiter` methods to configure delay behavior in v4.x, as `max_delay` is no longer a direct constructor argument.
Install with the appropriate extra: `pip install pyrate-limiter[redis]` for Redis, or `pip install pyrate-limiter[postgres]` for PostgreSQL.
Ensure `Rate` objects passed to a bucket or factory are sorted according to the specified rules.
Switch to a persistent backend (`SQLiteBucket`, `RedisBucket`, `PostgresBucket`) and configure it appropriately for your distributed setup.
pip install pyrate-limiter
from pyrate_limiter import RateLimiter, Rate, Limiter, MemoryBackend
import redis from pyrate_limiter import RedisBackend redis_client = redis.Redis(host='localhost', port=6379) backend = RedisBackend(redis_client)
async def my_async_function():
# ... (setup limiter)
if await limiter.try_acquire("user1", Rate(10, 60)):
print("Request allowed")
else:
print("Too many requests")