5 Redis Patterns Every Developer Should Know

Published: (February 11, 2026 at 03:21 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

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

Distributed Lock (Prevent Race Conditions)

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}")

Pub/Sub 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)

Leaderboard (Gaming and Ranking)

# Add score
redis.zadd("leaderboard", {"player1": 1500, "player2": 1200})

# Get top 10
redis.zrevrange("leaderboard", 0, 9, withscores=True)

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!

0 views
Back to Blog

Related posts

Read more »

Idempotent APIs in Node.js with Redis

!Cover image for Idempotent APIs in Node.js with Redishttps://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2...