To set a rate limit on asyncio calls in Python, you need to control how many times per second your asynchronous functions are executed. This is commonly done using a token bucket, leaky bucket, or by using semaphores with time-based release mechanisms.
A simple and effective way is to use an asyncio-friendly semaphore with time-based acquisition, or use a third-party library like async-throttle or implement your own throttler.
✅ Option 1: Using a Custom Rate Limiter
Here’s a simple implementation of a rate limiter using asyncio.Semaphore and tracking the last call time:
import asyncio
import time
class RateLimiter:
def __init__(self, calls_per_second):
self.calls_per_second = calls_per_second
self.semaphore = asyncio.Semaphore(calls_per_second)
self._last_refill = time.monotonic()
self._tokens = calls_per_second
# Refill tokens every 1/calls_per_second seconds
self._interval = 1.0 / calls_per_second if calls_per_second > 0 else 0
async def acquire(self):
now = time.monotonic()
elapsed = now - self._last_refill
self._last_refill = now
# Add new tokens based on elapsed time
new_tokens = int(elapsed // self._interval)
if new_tokens > 0:
self._tokens = min(self._tokens + new_tokens, self.calls_per_second)
while self._tokens < 1:
await asyncio.sleep(self._interval)
now = time.monotonic()
elapsed = now - self._last_refill
self._last_refill = now
new_tokens = int(elapsed // self._interval)
self._tokens = min(self._tokens + new_tokens, self.calls_per_second)
self._tokens -= 1
# Note: no need to use semaphore in this token-bucket approach
# Alternative: Use semaphore directly (simpler but less precise)
# async def acquire(self):
# await self.semaphore.acquire()
# asyncio.create_task(self._release_after_delay())
# async def _release_after_delay(self):
# await asyncio.sleep(1 / self.calls_per_second)
# self.semaphore.release()
# Example usage:
async def limited_call(id, limiter):
await limiter.acquire()
print(f"[{id}] Call started at {time.time()}")
await asyncio.sleep(0.1) # Simulate work
print(f"[{id}] Call finished at {time.time()}")
async def main():
limiter = RateLimiter(5) # 5 calls per second
tasks = [limited_call(i, limiter) for i in range(20)]
await asyncio.gather(*tasks)
asyncio.run(main())
⚠️ Note: The above token bucket code is illustrative — it has some flaws (e.g., not sleeping precisely). Let's simplify with a more practical approach:
✅ Option 2: Simpler Rate Limiting Using asyncio.Semaphore (Fixed Interval)
If you want to allow exactly N calls per second (evenly spaced), you can schedule them with asyncio.create_task and sleep between acquisitions:
import asyncio
class FixedRateLimiter:
def __init__(self, calls_per_second):
self.interval = 1.0 / calls_per_second
self._semaphore = asyncio.Semaphore(calls_per_second)
async def acquire(self):
await self._semaphore.acquire()
asyncio.create_task(self._delayed_release())
async def _delayed_release(self):
await asyncio.sleep(self.interval)
self._semaphore.release()
# Example usage:
async def make_request(id, limiter):
await limiter.acquire()
print(f"[{id}] Request made at {time.time()}")
await asyncio.sleep(0.1) # Simulate IO
async def main():
import time
limiter = FixedRateLimiter(3) # 3 requests per second
tasks = [make_request(i, limiter) for i in range(10)]
await asyncio.gather(*tasks)
asyncio.run(main())
This version schedules one call every 1 / calls_per_second seconds, regardless of how long the call takes.
✅ Option 3: Use async-throttle Library
Install via pip:
pip install async-throttle
Usage:
import asyncio
from async_throttle import Throttler
throttler = Throttler(rate_limit=5, period=1) # 5 calls per second
async def task(i):
async with throttler:
print(f"[{i}] Doing work at {time.time()}")
await asyncio.sleep(0.1)
async def main():
tasks = [task(i) for i in range(20)]
await asyncio.gather(*tasks)
asyncio.run(main())
✅ This is the cleanest and most reliable method.
Summary
| Method | Pros | Cons |
|---|
| Custom Token Bucket | Flexible, customizable | More complex to implement |
| Semaphore + Delayed Release | Simple, effective | Less accurate spacing |
async-throttle library | Very easy, robust | External dependency |
Choose the one that fits your needs best!