A decorator-based rate limiter using the token bucket algorithm
Project description
Rate Limiter
A Python decorator-based rate limiter using the sliding window algorithm.
Made by Dan Foster
Features
- Simple decorator-based API rate limiting
- Sliding window algorithm for strict rate limiting (exactly N calls allowed per time period)
- Per-key rate limiting support (e.g., per user ID)
- Auto-retry with configurable max retries
- Thread-safe implementation
- Zero external dependencies (Python standard library only)
Installation
pip install rate-limiter-df
For development:
pip install -e ".[dev]"
Usage
Basic Rate Limiting
from rate_limiter_df import RateLimiter, RateLimitExceeded
@RateLimiter(calls=10, period=60) # 10 calls per 60 seconds
def my_api_call():
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="...")
Auto-Retry
Automatically wait and retry when rate limited:
@RateLimiter(calls=2, period=1.0, auto_retry=True, max_retries=3)
def resilient_call():
return "Success"
# If rate limited, the decorator will sleep and retry up to 3 times
# before raising RateLimitExceeded
result = resilient_call()
How It Works
The rate limiter uses the sliding window algorithm:
- Each function (or key) tracks timestamps of recent calls
- When a call is made, timestamps older than the window period are discarded
- If the number of calls within the window is under the limit, the call proceeds
- If the limit has been reached, a
RateLimitExceededexception is raised with a retry time - With
auto_retryenabled, the decorator sleeps for the wait time and retries automatically
API Reference
RateLimiter(calls, period, per_key=None, auto_retry=False, max_retries=3)
Creates a rate limiter decorator.
Parameters:
calls(int): Maximum number of calls allowed per period. Default:1period(float): Time period in seconds. Default:60.0per_key(callable, optional): Function to extract a key from function arguments for per-key rate limitingauto_retry(bool): IfTrue, automatically wait and retry when rate limited. Default:Falsemax_retries(int): Maximum number of retry attempts whenauto_retryis enabled. Default:3
Returns:
- A decorator that can be applied to functions
RateLimitExceeded
Exception raised when the rate limit is exceeded. The exception message includes the wait time before a retry will succeed.
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.2.0.tar.gz.
File metadata
- Download URL: rate_limiter_df-0.2.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 |
5509c1e6a55174b6edadaaf99a10514c21e9ae1f0d403f1fd5f5cc55a4a7de9d
|
|
| MD5 |
7b4fb62792e3ef6e23f0052ed26765f7
|
|
| BLAKE2b-256 |
35ffb939266b7339db05558b8c8c99844bd7ca4bb852c01d96a4186afebf37a2
|
File details
Details for the file rate_limiter_df-0.2.0-py3-none-any.whl.
File metadata
- Download URL: rate_limiter_df-0.2.0-py3-none-any.whl
- Upload date:
- Size: 5.6 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 |
b4f9064c76490e22cb36563fe6a745fd4c97724f5d30a476d15a548f3258dd43
|
|
| MD5 |
a80a46d4a24d1529043be109e7cb54d2
|
|
| BLAKE2b-256 |
b0be8dbee874d802cdf35511af2ac2be021be94272637fc8bef7ace9312bf99e
|