Redis

Introduction

Redis (Remote Dictionary Server) is an open-source, in-memory data structure store used as a database, cache, message broker, and queue. It supports various data structures and offers high performance.

Key Features:

  • In-memory data storage
  • Multiple data structure support
  • Built-in replication
  • Transactions
  • Pub/Sub messaging
  • Lua scripting

Data Types

Strings

# String operations
SET user:1:name "John Doe"
GET user:1:name
INCR counter
EXPIRE user:1:name 3600

Lists

# List operations
LPUSH tasks "Send email"
RPUSH tasks "Generate report"
LRANGE tasks 0 -1
LPOP tasks

Sets

# Set operations
SADD tags "python" "redis" "nosql"
SMEMBERS tags
SISMEMBER tags "python"
SINTER set1 set2

Hashes

# Hash operations
HSET user:1 name "John" age "30" city "New York"
HGET user:1 name
HGETALL user:1
HINCRBY user:1 age 1

Basic Commands

Key Operations

# Key management
KEYS user:*
EXISTS user:1
DEL user:1
TTL user:1
PERSIST user:1

Transaction Commands

# Transaction handling
MULTI
SET user:2:name "Jane"
INCR user:2:visits
EXEC

WATCH account:balance
MULTI
DECRBY account:balance 100
INCRBY savings:balance 100
EXEC

Persistence

RDB Persistence

# RDB configuration in redis.conf
save 900 1
save 300 10
save 60 10000

# Manual save
SAVE
BGSAVE

AOF Persistence

Configuration Options:

  • appendonly yes
  • appendfsync always/everysec/no
  • auto-aof-rewrite-percentage 100
  • auto-aof-rewrite-min-size 64mb

Replication

Master-Replica Setup

# On replica server
replicaof 192.168.1.1 6379

# Monitor replication
INFO replication

# Make replica writable
replica-read-only no

Replication Features:

  • Asynchronous replication
  • Multiple replicas per master
  • Replica chaining
  • Automatic reconnection

Clustering

Redis Cluster

# Create cluster
redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 \
    127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 \
    127.0.0.1:7005 --cluster-replicas 1

# Check cluster info
CLUSTER INFO
CLUSTER NODES

Cluster Benefits:

  • High availability
  • Automatic partitioning
  • Linear scalability
  • No single point of failure

Use Cases

Common Applications

  • Caching Layer
  • Session Management
  • Real-time Analytics
  • Job Queues
  • Leaderboards
  • Rate Limiting

Implementation Example

# Python Redis caching example
import redis
import json

redis_client = redis.Redis(host='localhost', port=6379, db=0)

def get_user(user_id):
    # Try to get from cache
    cached_user = redis_client.get(f'user:{user_id}')
    if cached_user:
        return json.loads(cached_user)
    
    # Get from database and cache
    user = database.get_user(user_id)
    redis_client.setex(
        f'user:{user_id}',
        3600,  # Cache for 1 hour
        json.dumps(user)
    )
    return user