Skip to main content

Rate limiting utilities with Redis and Memory providers for Smart Platform

Project description

Smart Rate Limit

Rate limiting utilities with Redis and Memory providers for Smart Platform.

Features

  • Multiple Providers: Redis and in-memory rate limiting
  • Sliding Window: Accurate rate limiting algorithm
  • FastAPI Integration: Middleware and decorators
  • Multiple Strategies: IP-based, user-based, endpoint-based
  • Async/Await: Full async support

Installation

pip install smart-rate-limit

Usage

Memory Rate Limiter

from mehdashti_rate_limit import MemoryRateLimiter

# Initialize limiter
limiter = MemoryRateLimiter(cleanup_interval=300)
await limiter.start_cleanup()

# Check rate limit
try:
    info = await limiter.check(
        key="user:123",
        limit=100,
        window=60,  # 100 requests per minute
    )
    print(f"Remaining: {info.remaining}")
except RateLimitExceeded as e:
    print(f"Rate limit exceeded. Retry after {e.retry_after} seconds")

Redis Rate Limiter

from mehdashti_rate_limit import RedisRateLimiter

# Initialize limiter
limiter = RedisRateLimiter(redis_url="redis://localhost:6379/0")

# Check rate limit
try:
    info = await limiter.check(
        key="user:123",
        limit=1000,
        window=3600,  # 1000 requests per hour
    )
    print(f"Remaining: {info.remaining}")
except RateLimitExceeded as e:
    print(f"Rate limit exceeded. Retry after {e.retry_after} seconds")

FastAPI Middleware

from fastapi import FastAPI
from mehdashti_rate_limit import MemoryRateLimiter, RateLimitMiddleware

app = FastAPI()
limiter = MemoryRateLimiter()

# Add middleware
app.add_middleware(
    RateLimitMiddleware,
    limiter=limiter,
    limit=100,
    window=60,  # 100 requests per minute
    exclude_paths=["/health", "/metrics"],
)

@app.get("/api/users")
async def get_users():
    return {"users": []}

Decorators

Basic Rate Limiting

from fastapi import FastAPI, Request
from mehdashti_rate_limit import MemoryRateLimiter, rate_limit

app = FastAPI()
limiter = MemoryRateLimiter()

@app.get("/api/search")
@rate_limit(limiter, limit=10, window=60)
async def search(request: Request, query: str):
    return {"results": []}

User-Based Rate Limiting

from mehdashti_rate_limit import user_rate_limit

@app.get("/api/profile")
@user_rate_limit(limiter, limit=20, window=60)
async def get_profile(request: Request):
    # Rate limited by user ID (from request.state.user)
    return {"profile": {}}

Endpoint-Based Rate Limiting

from mehdashti_rate_limit import endpoint_rate_limit

@app.post("/api/expensive-operation")
@endpoint_rate_limit(limiter, limit=5, window=300)
async def expensive_operation(request: Request):
    # Rate limited per endpoint per IP
    return {"status": "processing"}

Custom Key Function

from fastapi import Request
from mehdashti_rate_limit import rate_limit

def custom_key(request: Request) -> str:
    # Rate limit by API key
    api_key = request.headers.get("X-API-Key", "unknown")
    return f"api_key:{api_key}"

@app.get("/api/data")
@rate_limit(limiter, limit=1000, window=3600, key_func=custom_key)
async def get_data(request: Request):
    return {"data": []}

API

RateLimiter

Base interface for all rate limiter providers.

  • check(key, limit, window): Check and increment rate limit
  • reset(key): Reset rate limit for a key
  • get_info(key, limit, window): Get rate limit info without incrementing

RateLimitInfo

Rate limit information returned by check() and get_info().

  • limit: Maximum requests allowed
  • remaining: Remaining requests in current window
  • reset_at: Unix timestamp when limit resets
  • retry_after: Seconds until reset (only when limit exceeded)

RateLimitExceeded

Exception raised when rate limit is exceeded.

  • message: Error message
  • retry_after: Seconds until rate limit resets

Response Headers

Rate limit responses include these headers:

  • X-RateLimit-Limit: Maximum requests allowed
  • X-RateLimit-Remaining: Remaining requests
  • X-RateLimit-Reset: Unix timestamp when limit resets
  • Retry-After: Seconds until reset (only in 429 responses)

License

MIT

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

mehdashti_rate_limit-0.1.1.tar.gz (8.3 kB view details)

Uploaded Source

Built Distribution

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

mehdashti_rate_limit-0.1.1-py3-none-any.whl (11.2 kB view details)

Uploaded Python 3

File details

Details for the file mehdashti_rate_limit-0.1.1.tar.gz.

File metadata

  • Download URL: mehdashti_rate_limit-0.1.1.tar.gz
  • Upload date:
  • Size: 8.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.11 {"installer":{"name":"uv","version":"0.9.11"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for mehdashti_rate_limit-0.1.1.tar.gz
Algorithm Hash digest
SHA256 adfe85dc57b6b5a6d3177657b75c326daf2ab8bfe21be688354e29d9a31cfa25
MD5 0082362e460aeb16f40fd577fac70e75
BLAKE2b-256 757827d276fbaf80ed3e56decae11c7b03b02d2add501d36393f74ad429eedbd

See more details on using hashes here.

File details

Details for the file mehdashti_rate_limit-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: mehdashti_rate_limit-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 11.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.11 {"installer":{"name":"uv","version":"0.9.11"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for mehdashti_rate_limit-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4ce0caa10fe1fe15ba6dc5c3e0fb55d71b91d61eb9ea7e01e74a63958abaa834
MD5 998140f630c4132905eccdbdfe684cc3
BLAKE2b-256 ca2108064df238ab335b641eb3025291a680ba366c9d1c4133a1c762d0704c33

See more details on using hashes here.

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