Back to Digest
SnippetsPython Async Redis Sliding Window Rate Limiter
pythonEssentialCopied 301 times

Python Async Redis Sliding Window Rate Limiter

Atomic sliding window rate limiter implementation in Python utilizing Redis ZSET and microsecond timestamps.

python•
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import 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
17 lines • 541 charactersUsed by 301 developers

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.
Featured Resourcein Python / Backend
Curated Tool