aiolimiter: Asyncio Rate Limiter
aiolimiter is an asyncio-compatible rate limiter library for Python, implementing a leaky bucket algorithm. It allows controlling the rate at which concurrent operations can acquire permits, preventing resource exhaustion or API overuse. The current version is 1.2.1, and it maintains a steady release cadence for bug fixes and minor enhancements.
Warnings
- gotcha When using `limiter.acquire(count)` outside of an `async with` block, it must be `await`ed, as it is a coroutine. Forgetting `await` will result in a runtime warning about an unawaited coroutine, or the acquisition not taking effect as intended.
- gotcha The `rate` and `period` parameters of `AsyncLimiter(rate, period)` can be confused. `rate` is the number of permits, and `period` is the duration in seconds over which those permits are available. E.g., `AsyncLimiter(10, 1)` means 10 permits per 1 second, not 1 permit per 10 seconds.
- gotcha By default, `acquire()` blocks until permits are available. If you want a non-blocking attempt, pass `block=False`. In this case, if permits are not immediately available, `acquire()` will raise a `LimitReached` exception instead of waiting.
Install
-
pip install aiolimiter
Imports
- AsyncLimiter
from aiolimiter import AsyncLimiter
Quickstart
import asyncio
from aiolimiter import AsyncLimiter
async def main():
# Initialize a limiter for 5 permits per second
limiter = AsyncLimiter(5, 1)
print("Attempting to acquire 3 permits...")
async with limiter:
await limiter.acquire(2) # Acquire 2 permits within the context manager
print("Acquired 3 permits (1 from 'async with', 2 from 'acquire')!")
print("Attempting to acquire 1 permit without context manager...")
await limiter.acquire(1)
print("Acquired 1 permit!")
# Demonstrate waiting if limit is reached
print("Acquiring 5 permits, might wait...")
for _ in range(5):
await limiter.acquire(1)
print(f"Permit {_+1} acquired.")
asyncio.run(main())