🌐 Detecting your location…
📢 Advertisement — Configure AdSense in Appearance → Customize → AdSense Settings

Redis Tutorial 2026: Caching, Pub/Sub, Streams and Production Patterns

⏱️3 min read  ·  504 words
Redis Tutorial 2026: Caching, Pub/Sub, Streams and Production Patterns

Redis is the most widely used in-memory data store in 2026. Sub-millisecond reads, pub/sub messaging, and atomic operations make it essential for caching, session storage, rate limiting, and real-time leaderboards. This tutorial covers Redis from install to production patterns.

Install Redis

# Ubuntu
sudo apt install redis-server
sudo systemctl enable redis-server

# macOS
brew install redis
brew services start redis

# Docker (simplest)
docker run -d --name redis -p 6379:6379 redis:7-alpine

# Connect
redis-cli ping  # PONG

Basic Data Types

# String
SET user:1:name 'Alice'
GET user:1:name         # Alice
SETEX session:abc 3600 'user_id=1'  # TTL 1 hour

# Hash (object)
HSET user:1 name Alice email alice@example.com age 30
HGET user:1 name        # Alice
HGETALL user:1          # all fields

# List
LPUSH queue:jobs 'job1' 'job2' 'job3'
RPOP queue:jobs         # job1 (queue behavior)
LRANGE queue:jobs 0 -1  # all items

# Set
SADD tags:post:1 python redis backend
SMEMBERS tags:post:1
SISMEMBER tags:post:1 python  # 1 = true

# Sorted Set (leaderboard)
ZADD leaderboard 1500 'Alice' 2200 'Bob' 1800 'Carol'
ZREVRANGE leaderboard 0 2 WITHSCORES  # top 3

Redis with Python

pip install redis

import redis

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

# Cache pattern
def get_user(user_id: int) -> dict:
    key = f'user:{user_id}'
    cached = r.hgetall(key)
    if cached:
        return cached
    # Cache miss — fetch from DB
    user = db.get_user(user_id)  # your DB query
    r.hset(key, mapping=user)
    r.expire(key, 3600)  # 1 hour TTL
    return user

# Rate limiting
def rate_limit(ip: str, limit: int = 100) -> bool:
    key = f'rate:{ip}'
    count = r.incr(key)
    if count == 1:
        r.expire(key, 60)  # 60-second window
    return count <= limit

Pub/Sub Messaging

import redis, threading

r = redis.Redis(decode_responses=True)

# Publisher
def publish_event(channel: str, data: str):
    r.publish(channel, data)

# Subscriber
def subscribe_events():
    pubsub = r.pubsub()
    pubsub.subscribe('events')
    for message in pubsub.listen():
        if message['type'] == 'message':
            print(f'Received: {message["data"]}')

# Run subscriber in background thread
t = threading.Thread(target=subscribe_events, daemon=True)
t.start()

publish_event('events', 'user_logged_in:123')

Redis Streams (Modern Queue)

# Produce
XADD events:orders * user_id 123 amount 49.99 item laptop

# Consume (consumer group)
XGROUP CREATE events:orders workers $ MKSTREAM
XREADGROUP GROUP workers consumer1 COUNT 10 STREAMS events:orders >

# Acknowledge
XACK events:orders workers <message-id>

Production Tips

  • Set maxmemory and maxmemory-policy allkeys-lru to prevent OOM
  • Enable persistence with appendonly yes (AOF) for crash recovery
  • Use connection pooling (redis.ConnectionPool) in Python
  • Prefix all keys by service: auth:session:..., cache:user:...
  • Monitor with redis-cli info stats and redis-cli monitor

Conclusion

Redis is not just a cache — it is a data structure server. Add Redis to any backend for instant caching, rate limiting, session storage, and real-time features. Sub-millisecond operations at millions of requests per second make it irreplaceable in modern architectures.

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇬🇧 English🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी🇧🇩 বাংলা