Redis is not just a key-value store. Cache, sessions, rate limiting, pub/sub, leaderboards — a versatile in-memory database.
Cache pattern¶
import redis r = redis.Redis() def get_user(user_id):
Redis Patterns — Cache, Session, Queue¶
cached = r.get(f”user:{user_id}”) if cached: return json.loads(cached)
Cache miss — fetch from DB¶
user = db.users.find_one(user_id) r.setex(f”user:{user_id}”, 3600, json.dumps(user)) # TTL 1h return user
Rate limiter¶
def rate_limit(key, limit=100, window=60): pipe = r.pipeline() now = time.time() 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
Pub/Sub¶
Publisher¶
r.publish(‘notifications’, json.dumps({‘user’: 123, ‘msg’: ‘Hello’}))
Subscriber¶
pubsub = r.pubsub() pubsub.subscribe(‘notifications’) for message in pubsub.listen(): if message[‘type’] == ‘message’: handle(json.loads(message[‘data’]))
Key Takeaway¶
Cache with TTL, sorted set for rate limiting, pub/sub for real-time. Redis = Swiss Army knife.