Asyncio rate limiter
Project description
arate-limit
A flexible and robust rate limiting library for Python applications, offering multiple implementation strategies including leaky bucket, token bucket, and Redis-based sliding window rate limiters.
Features
- Multiple rate limiting strategies:
- Leaky bucket rate limiter
- Token bucket rate limiter
- Redis-based sliding window rate limiter
- Redis-based sliding window API rate limiter
- Async/await support using
asyncio
- Configurable time windows and burst allowances
- Safe for concurrent access within asyncio applications
- Redis integration for distributed rate limiting
Installation
pip install arate-limit
Usage
Leaky Bucket Rate Limiter
A rate limiter that implements the leaky bucket algorithm, which smooths out bursts of requests and processes them at a steady rate:
import asyncio
from rate_limiter import LeakyBucketRateLimiter
async def example():
# Allow 100 requests per minute with some slack
limiter = LeakyBucketRateLimiter(event_count=100, time_window=60, slack=10)
async def limited_task():
await limiter.wait()
# Your rate-limited code here
print("Task executed")
# Execute multiple tasks
tasks = [limited_task() for _ in range(10)]
await asyncio.gather(*tasks)
Token Bucket Rate Limiter
More sophisticated rate limiting with burst support:
from datetime import timedelta
from rate_limiter import TokenBucketRateLimiter
async def example():
# Allow 1000 requests per hour with burst of 100
limiter = TokenBucketRateLimiter(
event_count=1000,
time_window=timedelta(hours=1),
burst=100
)
await limiter.wait() # Wait for rate limit
Redis Sliding Window Rate Limiter
Distributed rate limiting using Redis:
from rate_limiter import RedisSlidingWindowRateLimiter
import redis.asyncio as redis
async def example():
redis_client = redis.Redis(host='localhost', port=6379)
# Allow 1000 requests per minute with slack of 10
limiter = RedisSlidingWindowRateLimiter(
redis=redis_client,
event_count=1000,
time_window=60,
slack=10
)
await limiter.wait() # Wait for rate limit
Redis Sliding Window API Rate Limiter
Distributed API rate limiting using Redis:
from rate_limiter import RedisSlidingWindowApiRateLimiter
import redis.asyncio as redis
async def example():
redis_client = redis.Redis(host='localhost', port=6379)
# Allow 1000 requests per minute per user
limiter = RedisSlidingWindowApiRateLimiter(
redis=redis_client,
event_count=1000,
time_window=60,
)
result, time_remaining = await limiter.check("user-1")
if not result:
raise HTTPException(
status_code=429,
detail=f"Rate limit exceeded. Try again in {time_remaining} seconds"
)
Configuration Options
All rate limiters accept these common parameters:
event_count
: Maximum number of events allowed in the time windowtime_window
: Time period for the rate limit (accepts int/float seconds or timedelta)
Additional options per implementation:
LeakyBucketRateLimiter
slack
: Additional allowance for brief bursts (default: 10)
TokenBucketRateLimiter
burst
: Maximum burst size (default: 100)
RedisSlidingWindowRateLimiter
redis
: Redis compatible client/interfaceslack
: Additional allowance for brief bursts (default: 10)key_prefix
: Prefix for Redis keys (default: "rate_limiter:")
RedisSlidingWindowApiRateLimiter
redis
: Redis compatible client/interfacekey_prefix
: Prefix for Redis keys (default: "rate_limiter:")
Error Handling
The rate limiters raise appropriate exceptions for invalid configurations:
TypeError
: When parameters are of incorrect typeValueError
: When parameters have invalid values
Performance Considerations
LeakyBucketRateLimiter
: Best for scenarios requiring steady, predictable request ratesTokenBucketRateLimiter
: Efficient for bursty workloadsRedisSlidingWindowRateLimiter
: Suitable for distributed systems, but requires Redis or Redis compatible cache serviceRedisSlidingWindowApiRateLimiter
: Suitable for distributed systems, but requires Redis or Redis compatible cache service
License
This project is licensed under the MIT License - see the LICENSE file 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
File details
Details for the file arate_limit-1.1.6.tar.gz
.
File metadata
- Download URL: arate_limit-1.1.6.tar.gz
- Upload date:
- Size: 22.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 |
03cc9afd4906bf8400ae3db8014dc9e3dfa67f52a5e8f72db625e9e20c4b4570
|
|
MD5 |
1ac0922af036529211e82ab9e1c3040d
|
|
BLAKE2b-256 |
ac4c0eaf9c321e33575f770d532feae1a8cc70b4fcc98ee3cbed556892bfca30
|
Provenance
The following attestation bundles were made for arate_limit-1.1.6.tar.gz
:
Publisher:
release.yml
on jammymalina/arate-limit
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1
-
Predicate type:
https://docs.pypi.org/attestations/publish/v1
-
Subject name:
arate_limit-1.1.6.tar.gz
-
Subject digest:
03cc9afd4906bf8400ae3db8014dc9e3dfa67f52a5e8f72db625e9e20c4b4570
- Sigstore transparency entry: 227650735
- Sigstore integration time:
-
Permalink:
jammymalina/arate-limit@7488369dfdb1d62e1f2e65f206788da505804a74
-
Branch / Tag:
refs/tags/v1.1.6
- Owner: https://github.com/jammymalina
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com
-
Runner Environment:
github-hosted
-
Publication workflow:
release.yml@7488369dfdb1d62e1f2e65f206788da505804a74
-
Trigger Event:
release
-
Statement type:
File details
Details for the file arate_limit-1.1.6-py3-none-any.whl
.
File metadata
- Download URL: arate_limit-1.1.6-py3-none-any.whl
- Upload date:
- Size: 7.2 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 |
0416995e41b2d5dd5f6c3252225c3c8f3acd71cb6903563ce940d5ca5138e9f6
|
|
MD5 |
0e8853290d1fda8fe0df55a500e1e1d2
|
|
BLAKE2b-256 |
3c5311e39240ccb7c1709e973b5c8e12aae3bd89a4f3ea5fd5e663458cc7631c
|
Provenance
The following attestation bundles were made for arate_limit-1.1.6-py3-none-any.whl
:
Publisher:
release.yml
on jammymalina/arate-limit
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1
-
Predicate type:
https://docs.pypi.org/attestations/publish/v1
-
Subject name:
arate_limit-1.1.6-py3-none-any.whl
-
Subject digest:
0416995e41b2d5dd5f6c3252225c3c8f3acd71cb6903563ce940d5ca5138e9f6
- Sigstore transparency entry: 227650745
- Sigstore integration time:
-
Permalink:
jammymalina/arate-limit@7488369dfdb1d62e1f2e65f206788da505804a74
-
Branch / Tag:
refs/tags/v1.1.6
- Owner: https://github.com/jammymalina
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com
-
Runner Environment:
github-hosted
-
Publication workflow:
release.yml@7488369dfdb1d62e1f2e65f206788da505804a74
-
Trigger Event:
release
-
Statement type: