A decorator-based rate limiter using the token bucket algorithm
Project description
Rate Limiter
A Python decorator-based rate limiter using the token bucket algorithm.
Made by Dan Foster
Features
- Simple decorator-based API rate limiting
- Token bucket algorithm for smooth rate limiting (both short bursts and constant usage are supported)
- Per-key rate limiting support (e.g., per user ID)
- Thread-safe implementation
- Zero external dependencies (Python standard library only)
Installation
pip install -e .
Basic Rate Limiting
from rate_limiter_df import RateLimiter, RateLimitExceeded
@RateLimiter(calls=10, period=60) # 10 calls per 60 seconds
def my_api_call():
# Your function code goes here
return "Success"
try:
result = my_api_call()
except RateLimitExceeded as e:
print(f"Rate limit exceeded: {e}")
Per-Key Rate Limiting
Rate limit different keys (e.g., user IDs) independently:
def get_user_id(user_id, **kwargs):
return user_id
@RateLimiter(calls=5, period=60, per_key=get_user_id)
def process_user_request(user_id, data):
# Each user gets their own rate limit
return f"Processed request for user {user_id}"
# User 1 can make 5 calls
process_user_request(user_id=1, data="...")
process_user_request(user_id=1, data="...")
# User 2 has their own separate rate limit
process_user_request(user_id=2, data="...")
Advanced Example
from rate_limiter_df import RateLimiter, RateLimitExceeded
import time
@RateLimiter(calls=3, period=5.0)
def expensive_operation():
print("Performing expensive operation...")
return "Done"
# Make multiple calls
for i in range(5):
try:
result = expensive_operation()
print(f"Call {i+1}: {result}")
except RateLimitExceeded as e:
print(f"Call {i+1}: {e}")
time.sleep(1) # Wait before retrying
How It Works
The rate limiter uses the token bucket algorithm:
- Each function (or key) has a bucket that holds tokens
- Tokens are consumed when the function is called
- Tokens refill over time at a constant rate
- If no tokens are available, a
RateLimitExceededexception is raised
API Reference
RateLimiter(calls, period, per_key=None)
Creates a rate limiter decorator.
Parameters:
calls(int): Maximum number of calls allowedperiod(float): Time period in secondsper_key(callable, optional): Function to extract a key from function arguments for per-key rate limiting
Returns:
- A decorator that can be applied to functions
RateLimitExceeded
Exception raised when the rate limit is exceeded. The exception message includes information about when to retry.
License
MIT License - see LICENSE.txt for details.
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 rate_limiter_df-0.1.0.tar.gz.
File metadata
- Download URL: rate_limiter_df-0.1.0.tar.gz
- Upload date:
- Size: 4.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f4f81fe07d431c65dadd0088a706d041353653d5341af931afb98c823ef2f7d8
|
|
| MD5 |
892bf4ed8c0d57bb64ee2b3c5bb0039e
|
|
| BLAKE2b-256 |
27c78fd94f29252b52dd8675b77dab7196462bb7a0a825a5bc2e9c1f4bdbb3b9
|
File details
Details for the file rate_limiter_df-0.1.0-py3-none-any.whl.
File metadata
- Download URL: rate_limiter_df-0.1.0-py3-none-any.whl
- Upload date:
- Size: 6.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2478b47f1107bc0826061cc493cbc4d7b4147fedc4e2aa8d8739c8b2dfdb3eb1
|
|
| MD5 |
8021b20514774b876884083df8db50e6
|
|
| BLAKE2b-256 |
40c7754417a38c55392d34b99d0a31745188a901757fd1210b1a180320cb52a3
|