Fast asyncio-compatible token bucket rate limiter
Project description
🔄 throttlekit
A lightweight, asyncio-based rate limiting library for Python that provides flexible and efficient rate limiting solutions.
📋 Overview
throttlekit offers two proven rate limiting algorithms:
- ⚡ TokenBucketRateLimiter: Allows controlled bursts of activity
- 💧 LeakyBucketRateLimiter: Enforces a strict, steady rate
Perfect for API throttling, web scrapers, background jobs, and queue management.
🚀 Features
- ✅ Two proven algorithms: Token Bucket (burst-tolerant) and Leaky Bucket (evenly-paced)
- ✅ Multiple usage patterns:
@decorator,async with, and manual.acquire() - ✅ Concurrency control: Optional
concurrency_limitparameter - ✅ High performance: Low-overhead design optimized for async workloads
- ✅ asyncio integration: Works seamlessly with
asyncio.gather()andTaskGroup
⚙️ Installation
Using uv (recommended)
uv add throttlekit
Using pip
pip install throttlekit
✨ Quick Start
import asyncio
from throttlekit import TokenBucketRateLimiter
# Create a rate limiter (5 tokens, refill every second)
limiter = TokenBucketRateLimiter(max_tokens=5, refill_interval=1.0)
@limiter.limit
async def call_api(i):
await asyncio.sleep(0.2)
return f"Request {i} completed"
async def main():
await limiter.start()
# Process 10 requests with rate limiting
results = await asyncio.gather(*(call_api(i) for i in range(10)))
print(results)
# Run the example
asyncio.run(main())
🧠 Which Limiter Should I Use?
| Use Case | Recommended Limiter | Why? |
|---|---|---|
| Allow short bursts (e.g., 5 calls at once) | Token Bucket | Accumulates tokens for burst capacity |
| Require steady pacing (e.g., 1 call/sec max) | Leaky Bucket | Maintains consistent rate |
| Queue smoothing, task draining | Leaky Bucket | FIFO processing at fixed rate |
| Per-user or per-key API quotas | Token Bucket | Flexible burst handling |
Rate Limiters
TokenBucketRateLimiter
Allows bursts up to max_tokens, then refills at a steady rate.
from throttlekit import TokenBucketRateLimiter
limiter = TokenBucketRateLimiter(
max_tokens=10, # Maximum burst size
refill_interval=1.0, # Refill every second
concurrency_limit=5 # Optional: limit concurrent operations
)
Supports:
@limiter.limitdecoratorasync with limitercontext managerawait limiter.acquire()manual usage
💧 LeakyBucketRateLimiter
Processes requests at a fixed rate, queuing excess requests.
from throttlekit import LeakyBucketRateLimiter
limiter = LeakyBucketRateLimiter(
rate=2.0, # 2 requests per second
max_queue_size=100 # Maximum queued requests
)
Behavior:
- Drains 1 request every
1/rateseconds in FIFO order - Queued requests are processed at a fixed rate
- Bursts are automatically queued (up to
max_queue_size)
📘 Usage Examples
1️⃣ Decorator Pattern
@limiter.limit
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()
2️⃣ Context Manager
async with limiter:
result = await expensive_operation()
return result
3️⃣ Manual Control
await limiter.acquire()
try:
result = await do_work()
finally:
limiter.release_token() # For TokenBucket
limiter.release_semaphore() # If using concurrency_limit
🧪 Testing
Install test dependencies:
uv pip install pytest pytest-asyncio
Run tests with coverage:
pytest --cov=src/throttlekit --cov-report=term-missing
📁 Project Structure
throttlekit/
├── src/
│ └── throttlekit/
│ ├── __init__.py
│ ├── limiter.py # TokenBucketRateLimiter
│ └── leaky_limiter.py # LeakyBucketRateLimiter
├── tests/
│ ├── test_token_bucket_limiter.py
│ └── test_leaky_bucket_limiter.py
├── pyproject.toml
├── README.md
└── LICENSE
📜 License
MIT License © Roudrasekhar Majumder
🙋 Contributing
We welcome contributions! Please see CONTRIBUTING.md for detailed setup instructions and guidelines.
⭐ Star this repo if you find it useful!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file throttlekit-0.1.0.tar.gz.
File metadata
- Download URL: throttlekit-0.1.0.tar.gz
- Upload date:
- Size: 4.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4bc8b8eb4f0d68d4234f9037ddb565685172e7eb4c78a2d0ae10a495b13c947b
|
|
| MD5 |
e94e046515ebd7924bf260570f813b72
|
|
| BLAKE2b-256 |
fd18300bf3560d552b24c6f31bb2429bc9c7e897d33dce00a660329c722cd172
|
Provenance
The following attestation bundles were made for throttlekit-0.1.0.tar.gz:
Publisher:
release.yaml on rowds/throttlekit
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
throttlekit-0.1.0.tar.gz -
Subject digest:
4bc8b8eb4f0d68d4234f9037ddb565685172e7eb4c78a2d0ae10a495b13c947b - Sigstore transparency entry: 326820394
- Sigstore integration time:
-
Permalink:
rowds/throttlekit@d161f9ec30df1ed70e03710fab1cd5ef6fccaed3 -
Branch / Tag:
refs/tags/0.1.0 - Owner: https://github.com/rowds
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@d161f9ec30df1ed70e03710fab1cd5ef6fccaed3 -
Trigger Event:
push
-
Statement type:
File details
Details for the file throttlekit-0.1.0-py3-none-any.whl.
File metadata
- Download URL: throttlekit-0.1.0-py3-none-any.whl
- Upload date:
- Size: 5.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e261c7634d7b097f72b41f8640ebbe902fc225466dae143f6799d2d9bb19292e
|
|
| MD5 |
76efcfd6c74c478c3f65c56b5da75377
|
|
| BLAKE2b-256 |
a328799703f377ec835423733fab6c4d6e84b81156f2668851c415d0313e8b47
|
Provenance
The following attestation bundles were made for throttlekit-0.1.0-py3-none-any.whl:
Publisher:
release.yaml on rowds/throttlekit
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
throttlekit-0.1.0-py3-none-any.whl -
Subject digest:
e261c7634d7b097f72b41f8640ebbe902fc225466dae143f6799d2d9bb19292e - Sigstore transparency entry: 326820423
- Sigstore integration time:
-
Permalink:
rowds/throttlekit@d161f9ec30df1ed70e03710fab1cd5ef6fccaed3 -
Branch / Tag:
refs/tags/0.1.0 - Owner: https://github.com/rowds
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@d161f9ec30df1ed70e03710fab1cd5ef6fccaed3 -
Trigger Event:
push
-
Statement type: