Python Async Redis Sliding Window Rate Limiter
Atomic sliding window rate limiter implementation in Python utilizing Redis ZSET and microsecond timestamps.
1234567891011121314151617import time import redis.asyncio as redis async def check_rate_limit(r: redis.Redis, user_id: str, limit: int, window_sec: int) -> bool: now = time.time() key = f"rate:{user_id}" window_start = now - window_sec async with r.pipeline(transaction=True) as pipe: pipe.zremrangebyscore(key, 0, window_start) pipe.zadd(key, {str(now): now}) pipe.zcard(key) pipe.expire(key, window_sec) results = await pipe.execute() current_requests = results[2] return current_requests <= limit
Usage & Production Best Practices
This implementation is specifically optimized for high-throughput production environments. When integrating this pattern into your codebase:
- Ensure all asynchronous handles or listeners are cleaned up within the parent lifecycle.
- Avoid unbounded memory allocation by pinning cache buffers and queue capacities.
- Pair with automated unit tests to guarantee zero regressions under edge-case concurrency.
FastAPI Dependency Injection with Scoped Session Pool
Production-ready recipe for fastapi dependency injection with scoped session pool. Engineered for resilience, zero memory leaks, and sub-millisecond execution.
Python Async Batch Processor with Throttled Chunking
Production-ready recipe for python async batch processor with throttled chunking. Engineered for resilience, zero memory leaks, and sub-millisecond execution.
Python Sentence Embeddings with ONNX Runtime and Fast Tokenizer
Production-ready recipe for python sentence embeddings with onnx runtime and fast tokenizer. Engineered for resilience, zero memory leaks, and sub-millisecond execution.
Python Pydantic v2 Custom Serializer with Alias Generator
Production-ready recipe for python pydantic v2 custom serializer with alias generator. Engineered for resilience, zero memory leaks, and sub-millisecond execution.