Redis is more than just a cache - it's a powerful data structure server. Here are 5 patterns that will level up your Redis game.
1. Rate Limiting with Sliding Window
Perfect for API rate limiting:
def is_rate_limited(user_id: str, limit: int = 100, window: int = 60) -> bool:
key = f"rate:{user_id}"
now = time.time()
pipe = redis.pipeline()
pipe.zremrangebyscore(key, 0, now - window)
pipe.zadd(key, {str(now): now})
pipe.zcard(key)
pipe.expire(key, window)
_, _, count, _ = pipe.execute()
return count > limit
2. Distributed Locks
Prevent race conditions across services:
def acquire_lock(name: str, timeout: int = 10) -> bool:
return redis.set(f"lock:{name}", "1", nx=True, ex=timeout)
def release_lock(name: str):
redis.delete(f"lock:{name}")
3. Pub/Sub for Real-time Events
Great for notifications and live updates:
# Publisher
redis.publish("events", json.dumps({"type": "new_message", "data": {...}}))
# Subscriber
pubsub = redis.pubsub()
pubsub.subscribe("events")
for message in pubsub.listen():
handle_event(message)
4. Leaderboards with Sorted Sets
Perfect for gaming and ranking:
# Add score
redis.zadd("leaderboard", {"player1": 1500, "player2": 1200})
# Get top 10
redis.zrevrange("leaderboard", 0, 9, withscores=True)
5. Session Storage
Fast session management:
def save_session(session_id: str, data: dict, ttl: int = 3600):
redis.setex(f"session:{session_id}", ttl, json.dumps(data))
Which pattern will you try first? Let me know in the comments!
Top comments (0)