Building a Robust Async Rate Limiter SDK in Python
Rate limiting is an essential pattern in modern microservices and API gateways to prevent abuse, manage traffic spikes, and ensure fair resource allocation.
In this post, we explore how to build a lightweight, thread-safe, and async-ready Token Bucket Rate Limiter SDK in Python without heavy external dependencies.
Architecture & Implementation
The core algorithm relies on the Token Bucket strategy:
- A bucket has a maximum capacity.
- Tokens are replenished at a constant refill rate over time.
- Each incoming request consumes one or more tokens. If insufficient tokens remain, the request is rejected or throttled.
Code Sample (limiter.py)
import time
import asyncio
from typing import Dict, Tuple
class TokenBucketRateLimiter:
"""Memory-based Token Bucket Rate Limiter supporting async operations."""
def __init__(self, capacity: int, refill_rate: float):
self.capacity = capacity
self.refill_rate = refill_rate # tokens per second
self.buckets: Dict[str, Tuple[float, float]] = {}
def _get_tokens(self, key: str, now: float) -> float:
if key not in self.buckets:
return float(self.capacity)
tokens, last_refill = self.buckets[key]
delta = now - last_refill
tokens = min(float(self.capacity), tokens + delta * self.refill_rate)
return tokens
def acquire(self, key: str, tokens: int = 1) -> bool:
now = time.time()
current_tokens = self._get_tokens(key, now)
if current_tokens >= tokens:
self.buckets[key] = (current_tokens - tokens, now)
return True
return False
async def acquire_async(self, key: str, tokens: int = 1) -> bool:
await asyncio.sleep(0)
return self.acquire(key, tokens)
Running Unit Tests
We ensure reliability with thorough unittest coverage:
python3 -m unittest test_limiter.py
Result: Ran 2 tests in 0.001s — OK!
Conclusion
This SDK is extremely lightweight, easy to integrate into FastAPI or asyncio-based services, and fully tested. Happy coding!
Top comments (0)