Redis – In-Memory Data Structure Store and Cache

4.8 Stars
Version 7.2
3 MB
Redis – In-Memory Data Structure Store and Cache

Complete Guide to Redis: High-Performance Data Storage

Redis (Remote Dictionary Server) has become the go-to solution for applications requiring high-speed data access, serving as an in-memory data structure store, cache, message broker, and streaming engine. Its sub-millisecond response times and support for complex data structures make it ideal for use cases ranging from session management to real-time analytics. Major platforms including Twitter, GitHub, and Stack Overflow rely on Redis for performance-critical operations.

Unlike traditional databases that persist data to disk, Redis keeps data in memory for exceptional speed while offering configurable persistence options. Its rich set of data structures—strings, hashes, lists, sets, sorted sets, and more—enables solving complex problems with simple, efficient commands.

Installation

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

# Start service
sudo systemctl start redis-server
sudo systemctl enable redis-server

# Fedora
sudo dnf install redis
sudo systemctl start redis

# Arch Linux
sudo pacman -S redis
sudo systemctl start redis

# macOS
brew install redis
brew services start redis

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

# With persistence
docker run -d --name redis \
  -p 6379:6379 \
  -v redis_data:/data \
  redis:latest \
  redis-server --appendonly yes

# Verify
redis-cli ping
# Returns: PONG

Basic Commands

# Connect to Redis
redis-cli
redis-cli -h hostname -p 6379 -a password

# String operations
SET key "value"
GET key
APPEND key " more"
STRLEN key
INCR counter
INCRBY counter 10
DECR counter

# Key management
KEYS *
KEYS user:*
EXISTS key
DEL key
EXPIRE key 3600    # Seconds
TTL key            # Time to live
PERSIST key        # Remove expiration
TYPE key
RENAME key newkey

# Multiple keys
MSET key1 "val1" key2 "val2"
MGET key1 key2

# Conditional set
SETNX key "value"  # Set if not exists
SETEX key 3600 "value"  # Set with expiration

# Database operations
SELECT 1           # Switch database (0-15)
DBSIZE             # Number of keys
FLUSHDB            # Clear current database
FLUSHALL           # Clear all databases

Data Structures

# Hashes (field-value pairs)
HSET user:1 name "John"
HSET user:1 email "john@example.com"
HGET user:1 name
HGETALL user:1
HMSET user:1 name "John" email "john@example.com"
HINCRBY user:1 visits 1
HDEL user:1 email
HEXISTS user:1 name

# Lists (ordered)
LPUSH mylist "first"      # Push left
RPUSH mylist "last"       # Push right
LPOP mylist               # Pop left
RPOP mylist               # Pop right
LRANGE mylist 0 -1        # Get all
LLEN mylist               # Length
LINDEX mylist 0           # Get by index
LSET mylist 0 "new"       # Set by index

# Sets (unique values)
SADD myset "member1"
SADD myset "member2"
SMEMBERS myset
SISMEMBER myset "member1"
SCARD myset               # Count
SREM myset "member1"
SUNION set1 set2          # Union
SINTER set1 set2          # Intersection
SDIFF set1 set2           # Difference

# Sorted Sets (with scores)
ZADD leaderboard 100 "player1"
ZADD leaderboard 200 "player2"
ZRANGE leaderboard 0 -1             # By index
ZRANGE leaderboard 0 -1 WITHSCORES
ZRANGEBYSCORE leaderboard 100 200   # By score
ZRANK leaderboard "player1"          # Rank
ZSCORE leaderboard "player1"         # Score
ZINCRBY leaderboard 10 "player1"     # Increment

Pub/Sub Messaging

# Subscribe to channel
SUBSCRIBE channel1
SUBSCRIBE channel1 channel2
PSUBSCRIBE pattern*

# Publish message
PUBLISH channel1 "Hello subscribers"

# Pattern matching
PSUBSCRIBE news.*
PUBLISH news.sports "Sports update"

# Unsubscribe
UNSUBSCRIBE channel1
PUNSUBSCRIBE pattern*

# List channels
PUBSUB CHANNELS
PUBSUB NUMSUB channel1

Streams

# Add to stream
XADD mystream * field1 value1 field2 value2
XADD mystream * sensor_id 1234 temperature 23.5

# Read from stream
XREAD STREAMS mystream 0
XREAD COUNT 10 STREAMS mystream 0
XREAD BLOCK 5000 STREAMS mystream $  # Block for new

# Range queries
XRANGE mystream - +
XRANGE mystream - + COUNT 10

# Consumer groups
XGROUP CREATE mystream mygroup $ MKSTREAM
XREADGROUP GROUP mygroup consumer1 STREAMS mystream >
XACK mystream mygroup message-id

# Stream info
XLEN mystream
XINFO STREAM mystream
XINFO GROUPS mystream

Transactions

# Basic transaction
MULTI
SET key1 "value1"
SET key2 "value2"
INCR counter
EXEC

# Discard transaction
MULTI
SET key "value"
DISCARD

# Watch for optimistic locking
WATCH key
MULTI
SET key "newvalue"
EXEC
# Returns nil if key changed

# Lua scripting
EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey myvalue

# Script with logic
EVAL "
local current = redis.call('GET', KEYS[1])
if current then
    return redis.call('INCR', KEYS[1])
else
    return redis.call('SET', KEYS[1], 1)
end
" 1 counter

Persistence

# RDB (snapshot)
# In redis.conf:
save 900 1      # Save if 1 key changed in 900s
save 300 10     # Save if 10 keys changed in 300s
save 60 10000   # Save if 10000 keys changed in 60s

# Manual snapshot
BGSAVE          # Background save
SAVE            # Blocking save

# AOF (append-only file)
# In redis.conf:
appendonly yes
appendfsync everysec  # Options: always, everysec, no

# Rewrite AOF
BGREWRITEAOF

# Check AOF
redis-check-aof --fix appendonly.aof

# Check RDB
redis-check-rdb dump.rdb

# Disable persistence (cache only)
save ""
appendonly no

Caching Patterns

# Cache-aside pattern
# Pseudocode:
data = redis.get(key)
if data is None:
    data = database.query()
    redis.setex(key, 3600, data)
return data

# Write-through
# Pseudocode:
database.write(data)
redis.set(key, data)

# Cache invalidation
DEL cache:user:123
# Or set short TTL
SETEX cache:user:123 300 data

# LRU eviction
# In redis.conf:
maxmemory 100mb
maxmemory-policy allkeys-lru

# Eviction policies:
# noeviction - Error on memory limit
# allkeys-lru - LRU on all keys
# volatile-lru - LRU on keys with TTL
# allkeys-random - Random all keys
# volatile-random - Random with TTL
# volatile-ttl - Remove soonest expiring

Replication and Clustering

# Replication setup
# On replica:
REPLICAOF master-host 6379
# Or in config:
replicaof master-host 6379

# Check replication
INFO replication

# Promote replica
REPLICAOF NO ONE

# Redis Sentinel (high availability)
# sentinel.conf:
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 30000
sentinel failover-timeout mymaster 180000

# Start sentinel
redis-sentinel sentinel.conf

# Redis Cluster
# Create cluster (6 nodes minimum)
redis-cli --cluster create \
  node1:6379 node2:6379 node3:6379 \
  node4:6379 node5:6379 node6:6379 \
  --cluster-replicas 1

# Cluster commands
CLUSTER INFO
CLUSTER NODES
CLUSTER SLOTS

Security

# Set password
# In redis.conf:
requirepass your_strong_password

# Or at runtime
CONFIG SET requirepass "password"

# Authenticate
AUTH password

# ACL (Access Control List)
ACL SETUSER myuser on >password ~keys:* +@read
ACL LIST
ACL WHOAMI

# Disable dangerous commands
rename-command FLUSHALL ""
rename-command CONFIG ""
rename-command DEBUG ""

# Bind to specific interface
bind 127.0.0.1
# Or for production:
bind 10.0.0.1

# TLS encryption
# In redis.conf:
tls-port 6380
tls-cert-file /path/to/redis.crt
tls-key-file /path/to/redis.key

Monitoring

# Server info
INFO
INFO memory
INFO replication
INFO stats

# Real-time monitoring
MONITOR       # Shows all commands

# Slow log
SLOWLOG GET 10
CONFIG SET slowlog-log-slower-than 10000

# Memory analysis
MEMORY USAGE key
MEMORY DOCTOR
MEMORY STATS

# Client list
CLIENT LIST
CLIENT KILL ID client-id

# Latency
redis-cli --latency
redis-cli --latency-history

# Benchmark
redis-benchmark -q -n 100000

Conclusion

Redis delivers exceptional performance for applications requiring fast data access, caching, and real-time features. Its versatile data structures, pub/sub capabilities, and streaming support make it far more than a simple cache. Whether building session stores, leaderboards, real-time analytics, or message queues, Redis provides the speed and flexibility needed for demanding applications while remaining straightforward to operate and scale.

Developer: Redis Ltd

Download Options

Download Redis – In-Memory Data Structure Store and Cache

Version 7.2

File Size: 3 MB

Download Now
Safe & Secure

Verified and scanned for viruses

Regular Updates

Always get the latest version

24/7 Support

Help available when you need it