Redis logoRedisv8INTERMEDIATE

Redis

Redis cheat sheet covering data structures, caching strategies, pub/sub, transactions, persistence, and cluster management examples.

8 min read
rediscachenosqlkey-valuepub-subdatabasein-memorydata-structures

Sign in to mark items as known and track your progress.

Sign in

Installation & Basics

Getting started with Redis

Installation & Setup

Installing Redis on different platforms

bash
# Ubuntu/Debian
sudo apt update
sudo apt install redis-server

# macOS with Homebrew
brew install redis

# Docker
docker run -d -p 6379:6379 redis

# Start Redis server
redis-server

# Connect with CLI
redis-cli
⚡ In-memory data store for high performance
📦 Available in most package managers
🔧 Default port 6379
💾 Optional persistence with AOF/RDB

Basic Commands

Essential Redis commands and operations

bash
# Connect to Redis
redis-cli

# Test connection
PING

# Set and get values
SET key "value"
GET key

# Set with expiration
SETEX key 60 "value"  # Expires in 60 seconds
TTL key              # Check time to live

# Delete key
DEL key
🔑 All operations on keys are atomic
⚡ O(1) complexity for most operations
🔍 Use SCAN instead of KEYS in production
💾 Transactions with MULTI/EXEC

Data Structures

Redis data types and their operations

Lists

Ordered collections of strings

bash
# Push elements
LPUSH mylist "first"      # Push to left (head)
RPUSH mylist "last"       # Push to right (tail)

# Pop elements
LPOP mylist              # Pop from left
RPOP mylist              # Pop from right

# Get elements
LRANGE mylist 0 -1       # Get all elements
LINDEX mylist 0          # Get element at index
LLEN mylist             # Get list length
📝 Doubly-linked lists for fast push/pop
🔄 O(1) for head/tail operations
📊 Great for queues and stacks
⏰ Blocking operations for queue patterns

Sets

Unordered collections of unique strings

bash
# Add members
SADD myset "member1"
SADD myset "member2"

# Check membership
SISMEMBER myset "member1"

# Get all members
SMEMBERS myset

# Set operations
SUNION set1 set2       # Union
SINTER set1 set2       # Intersection
SDIFF set1 set2        # Difference
🎯 Guarantees unique members
⚡ O(1) add, remove, and check
🔄 Powerful set operations (union, intersection)
🎲 Random member selection support

Sorted Sets

Ordered sets with scores

bash
# Add members with scores
ZADD leaderboard 100 "player1"
ZADD leaderboard 200 "player2"

# Get by rank
ZRANGE leaderboard 0 -1              # All members
ZREVRANGE leaderboard 0 9            # Top 10

# Get by score
ZRANGEBYSCORE leaderboard 100 200
📊 Members ordered by score
🏆 Perfect for leaderboards and rankings
⚡ O(log(N)) for most operations
🔢 Floating point scores for precision

Hashes

Field-value pairs (like objects)

bash
# Set fields
HSET user:1 name "John"
HSET user:1 age 30

# Get fields
HGET user:1 name
HGETALL user:1

# Multiple fields
HMSET user:2 name "Jane" age 25 city "NYC"
🗂️ Perfect for storing objects/records
⚡ O(1) for single field operations
💾 More memory efficient than JSON strings
🔍 Can fetch specific fields without entire object

Pub/Sub & Streams

Messaging patterns and stream processing

Pub/Sub Messaging

Publish/Subscribe messaging pattern

bash
# Subscribe to channel
SUBSCRIBE channel1

# Publish message
PUBLISH channel1 "Hello subscribers"

# Pattern subscription
PSUBSCRIBE news:*

# Unsubscribe
UNSUBSCRIBE channel1
📡 Real-time messaging between clients
🔥 Fire-and-forget delivery (no persistence)
🎯 Pattern matching for flexible subscriptions
⚠️ Messages lost if no active subscribers

Streams

Persistent message streams with consumer groups

bash
# Add to stream
XADD mystream * field1 value1 field2 value2

# Read from stream
XREAD COUNT 2 STREAMS mystream 0

# Consumer groups
XGROUP CREATE mystream mygroup 0
XREADGROUP GROUP mygroup consumer1 STREAMS mystream >
💾 Persistent message history
👥 Consumer groups for distributed processing
✅ Message acknowledgment support
📊 Better than pub/sub for reliable messaging

Persistence & Backup

Data persistence and backup strategies

Persistence Options

RDB snapshots and AOF logging

bash
# RDB (snapshots)
SAVE                    # Synchronous save
BGSAVE                  # Background save
LASTSAVE               # Last save timestamp

# AOF (Append Only File)
CONFIG SET appendonly yes
BGREWRITEAOF           # Rewrite AOF file

# Configure in redis.conf
save 900 1             # Save after 900s if 1 key changed
appendonly yes         # Enable AOF
💾 RDB for periodic snapshots
📝 AOF for write durability
🔄 Hybrid mode combines both benefits
⚡ Choose based on durability vs performance needs

Performance & Optimization

Optimizing Redis for better performance

Memory Optimization

Memory management and optimization techniques

bash
# Memory commands
INFO memory             # Memory statistics
MEMORY USAGE key       # Memory used by key
MEMORY STATS          # Detailed memory stats
MEMORY DOCTOR         # Memory issues report

# Eviction policies
CONFIG SET maxmemory 2gb
CONFIG SET maxmemory-policy allkeys-lru
💾 Choose correct eviction policy
📊 Use appropriate data structures
🗜️ Enable compression for large values
⏱️ Set TTL to auto-clean old data

Performance Tuning

Optimizing Redis performance

bash
# Slow log
CONFIG SET slowlog-log-slower-than 10000  # Log queries > 10ms
SLOWLOG GET 10                            # Get last 10 slow queries

# Pipeline commands for bulk operations
# Use client library pipelining

# Disable persistence if not needed
CONFIG SET save ""
CONFIG SET appendonly no
🚀 Pipeline commands to reduce latency
📊 Monitor slow queries regularly
⚙️ Tune OS settings for production
📈 Use redis-benchmark for testing

Clustering & Replication

Scaling Redis with replication and clustering

Replication & Clustering

Master-slave replication and Redis Cluster

bash
# Replication setup
REPLICAOF master-host 6379    # Make this instance a replica
REPLICAOF NO ONE              # Promote to master

# Cluster commands
CLUSTER NODES                 # List cluster nodes
CLUSTER INFO                  # Cluster information
CLUSTER SLOTS                 # Slot assignments
📋 Replication for read scaling and backup
🔰 Sentinel for automatic failover
🎯 Cluster for horizontal scaling
⚠️ Use hash tags for multi-key operations in cluster