Python implementations of five Redis rate limiting algorithms using
redis-py and Lua scripts executed
via EVAL.
This is the Python companion to the Build 5 Rate Limiters with Redis tutorial on redis.io, which covers the same algorithms in TypeScript.
| Algorithm | Redis type | Memory per client | Burst behavior |
|---|---|---|---|
| Fixed window | STRING | 1 key | Allows 2x burst at boundaries |
| Sliding window log | SORTED SET | O(n) entries | No bursts |
| Sliding window counter | STRING x2 | 2 keys | Smoothed boundaries |
| Token bucket | HASH | 1 key (2 fields) | Allows controlled bursts |
| Leaky bucket (policing) | HASH | 1 key (2 fields) | No bursts, immediate deny |
All five limiters use Lua scripts executed atomically on the Redis server. Rate limiting algorithms share the same pattern: read state, make a decision, write updated state. Without atomicity, two concurrent requests can both read the same state, both pass the check, and both write — bypassing the limit.
MULTI/EXEC cannot branch on intermediate values. WATCH + MULTI/EXEC works
but causes retry loops under the exact high-concurrency conditions where rate
limiting is critical. A Lua script completes the read-decide-write cycle in a
single round trip with no retries.
All scripts that need a current timestamp derive now from
redis.call('TIME') inside the Lua script rather than time.time() in the
caller. When the limiter runs across multiple application servers, each
caller's clock drifts independently — requests get scored and pruned with
inconsistent timestamps and the limit drifts even though the Lua body is
atomic. Deriving time from Redis eliminates this entirely.
# Start Redis
docker run -p 6379:6379 redis:latest
# Install dependencies
pip install redis
# Run the demo
python demo.pyimport redis
from limiters import sliding_window_log
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
result = sliding_window_log.is_allowed(
client=r,
key="rate:user_123",
limit=10,
window_seconds=60,
)
if not result["allowed"]:
print(f"Rate limited. Retry in {result['retry_after_ms']}ms.")- Most APIs: sliding window counter — near-exact accuracy, low memory, no boundary bursts
- Need exact timestamps or audit trail: sliding window log
- Allow short bursts: token bucket
- Strict no-burst, immediate deny: leaky bucket (policing)
- Simplest possible: fixed window