0

Redis beyond caching: 5 use cases you should know

Most developers know Redis as a cache. But it's capable of much more. Here are 5 patterns I use in production.

1. Rate Limiting

import redis

r = redis.Redis()

def is_rate_limited(user_id, limit=100, window=60):
    key = f"rate:{user_id}"
        current = r.incr(key)
            if current == 1:
                    r.expire(key, window)
                        return current > limit
                        ```
                        
                        Simple, atomic, and fast. No database queries needed.
                        
                        ## 2. Distributed Locks
                        
                        When multiple workers might process the same job:
                        
                        ```python
                        import redis
                        
                        r = redis.Redis()
                        
                        def acquire_lock(name, timeout=10):
                            return r.set(f"lock:{name}", "1", nx=True, ex=timeout)
                            
                            def release_lock(name):
                                r.delete(f"lock:{name}")
                                
                                # Usage
                                if acquire_lock("process-order-123"):
                                    try:
                                            process_order(123)
                                                finally:
                                                        release_lock("process-order-123")
                                                        ```
                                                        
                                                        `nx=True` means "set only if not exists" — atomic mutex.
                                                        
                                                        ## 3. Real-time Leaderboard
                                                        
                                                        ```python
                                                        # Add scores
                                                        r.zadd("leaderboard", {"player_a": 1500, "player_b": 2100, "player_c": 1800})
                                                        
                                                        # Top 10 players
                                                        top_10 = r.zrevrange("leaderboard", 0, 9, withscores=True)
                                                        
                                                        # Player rank
                                                        rank = r.zrevrank("leaderboard", "player_a")  # 0-indexed
                                                        
                                                        # Update score atomically
                                                        r.zincrby("leaderboard", 50, "player_a")
                                                        ```
                                                        
                                                        Sorted sets handle millions of entries with O(log N) operations.
                                                        
                                                        ## 4. Pub/Sub for Real-time Events
                                                        
                                                        ```python
                                                        # Publisher
                                                        r.publish("notifications", json.dumps({
                                                            "user_id": 123,
                                                                "message": "New order received"
                                                                }))
                                                                
                                                                # Subscriber
                                                                pubsub = r.pubsub()
                                                                pubsub.subscribe("notifications")
                                                                
                                                                for message in pubsub.listen():
                                                                    if message["type"] == "message":
                                                                            data = json.loads(message["data"])
                                                                                    send_push_notification(data)
                                                                                    ```
                                                                                    
                                                                                    Lightweight alternative to Kafka/RabbitMQ for simple event streaming.
                                                                                    
                                                                                    ## 5. Session Storage
                                                                                    
                                                                                    ```python
                                                                                    from flask import Flask, session
                                                                                    from flask_session import Session
                                                                                    
                                                                                    app = Flask(__name__)
                                                                                    app.config["SESSION_TYPE"] = "redis"
                                                                                    app.config["SESSION_REDIS"] = redis.Redis(host="localhost")
                                                                                    Session(app)
                                                                                    
                                                                                    @app.route("/login")
                                                                                    def login():
                                                                                        session["user_id"] = 123  # Stored in Redis, not cookies
                                                                                        ```
                                                                                        
                                                                                        Advantages over cookie-based sessions:
                                                                                        - Server-side: can't be tampered with
                                                                                        - Shared across instances (horizontal scaling)
                                                                                        - Easy to invalidate: just delete the key
                                                                                        
                                                                                        ## When NOT to use Redis
                                                                                        
                                                                                        - **Primary database**: Redis is in-memory, data loss risk on crash (even with AOF)
                                                                                        - **Large objects**: Keep values under 1MB
                                                                                        - **Complex queries**: No SQL, limited filtering
                                                                                        
                                                                                        ---
                                                                                        
                                                                                        What's your favorite Redis use case? I'm curious what patterns work for others.

All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.