DEV Community

Wu Xie
Wu Xie

Posted on

5 Redis Patterns Every Developer Should Know

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
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

Which pattern will you try first? Let me know in the comments!

Top comments (0)