Skip to main content

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_limit parameter
  • High performance: Low-overhead design optimized for async workloads
  • asyncio integration: Works seamlessly with asyncio.gather() and TaskGroup

⚙️ 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.limit decorator
  • async with limiter context manager
  • await 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/rate seconds 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!

Report BugRequest FeatureDocumentation

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

throttlekit-0.1.0.tar.gz (4.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

throttlekit-0.1.0-py3-none-any.whl (5.8 kB view details)

Uploaded Python 3

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

Hashes for throttlekit-0.1.0.tar.gz
Algorithm Hash digest
SHA256 4bc8b8eb4f0d68d4234f9037ddb565685172e7eb4c78a2d0ae10a495b13c947b
MD5 e94e046515ebd7924bf260570f813b72
BLAKE2b-256 fd18300bf3560d552b24c6f31bb2429bc9c7e897d33dce00a660329c722cd172

See more details on using hashes here.

Provenance

The following attestation bundles were made for throttlekit-0.1.0.tar.gz:

Publisher: release.yaml on rowds/throttlekit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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

Hashes for throttlekit-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e261c7634d7b097f72b41f8640ebbe902fc225466dae143f6799d2d9bb19292e
MD5 76efcfd6c74c478c3f65c56b5da75377
BLAKE2b-256 a328799703f377ec835423733fab6c4d6e84b81156f2668851c415d0313e8b47

See more details on using hashes here.

Provenance

The following attestation bundles were made for throttlekit-0.1.0-py3-none-any.whl:

Publisher: release.yaml on rowds/throttlekit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page