← Back to all cheatsheets
Database
redisdatabasecachenosqlin-memorykey-value

Redis Cheat Sheet

Table of Contents


Connection and Basic Commands

Connect with redis-cli

# Connect to local Redis
redis-cli

# Connect to remote Redis
redis-cli -h hostname -p 6379

# Connect with password
redis-cli -h hostname -p 6379 -a password

# Connect with password (more secure - prompts for password)
redis-cli -h hostname -p 6379 --askpass

# Connect to specific database (0-15 by default)
redis-cli -n 2

# Connect with TLS/SSL
redis-cli --tls -h hostname -p 6379

# Execute single command
redis-cli PING
redis-cli GET mykey

# Execute command on remote server
redis-cli -h hostname -p 6379 -a password GET mykey

Basic Commands

# Test connection
PING                        # Returns PONG

# Select database (0-15)
SELECT 2

# Get server info
INFO
INFO memory
INFO replication
INFO server

# Get all configuration
CONFIG GET *
CONFIG GET maxmemory

# Set configuration
CONFIG SET maxmemory 100mb

# Clear current database
FLUSHDB

# Clear all databases
FLUSHALL

# Get database size (number of keys)
DBSIZE

# Get last save time
LASTSAVE

# Save database to disk
SAVE                        # Synchronous (blocks)
BGSAVE                      # Asynchronous (background)

# Shutdown server
SHUTDOWN
SHUTDOWN SAVE               # Save before shutdown
SHUTDOWN NOSAVE             # Don't save

String Operations

Basic String Commands

# Set a key
SET key "value"
SET key "value" EX 60       # Expires in 60 seconds
SET key "value" PX 60000    # Expires in 60000 milliseconds
SET key "value" NX          # Only set if key doesn't exist
SET key "value" XX          # Only set if key exists

# Get a key
GET key

# Get multiple keys
MGET key1 key2 key3

# Set multiple keys
MSET key1 "value1" key2 "value2"

# Set if not exists
SETNX key "value"

# Set with expiration (seconds)
SETEX key 60 "value"

# Set with expiration (milliseconds)
PSETEX key 60000 "value"

# Get and set
GETSET key "newvalue"       # Returns old value

# Get substring
GETRANGE key 0 5            # Get characters 0-5

# Set substring
SETRANGE key 6 "world"      # Overwrite starting at position 6

# Append to string
APPEND key " more text"

# Get string length
STRLEN key

Numeric Operations

# Increment
INCR counter                # Increment by 1
INCRBY counter 5            # Increment by 5
INCRBYFLOAT counter 1.5     # Increment by float

# Decrement
DECR counter                # Decrement by 1
DECRBY counter 5            # Decrement by 5

Key Management

Key Commands

# Check if key exists
EXISTS key
EXISTS key1 key2 key3       # Returns count of existing keys

# Delete keys
DEL key
DEL key1 key2 key3          # Delete multiple
UNLINK key                  # Async delete (non-blocking)

# Rename key
RENAME key newkey
RENAMENX key newkey         # Only if newkey doesn't exist

# Get key type
TYPE key

# Find keys by pattern
KEYS *                      # All keys (avoid in production!)
KEYS user:*                 # Keys starting with "user:"
KEYS *name*                 # Keys containing "name"

# Scan keys (safe for production)
SCAN 0                      # Start scanning
SCAN 0 MATCH user:* COUNT 100

# Get random key
RANDOMKEY

# Dump key (serialize)
DUMP key

# Restore key (deserialize)
RESTORE key 0 "\x00\x03..."

Expiration Commands

# Set expiration (seconds)
EXPIRE key 60

# Set expiration (milliseconds)
PEXPIRE key 60000

# Set expiration at Unix timestamp
EXPIREAT key 1735689600

# Set expiration at Unix timestamp (milliseconds)
PEXPIREAT key 1735689600000

# Get time to live (seconds)
TTL key                     # -1 = no expiry, -2 = key doesn't exist

# Get time to live (milliseconds)
PTTL key

# Remove expiration
PERSIST key

List Operations

# Push to list
LPUSH mylist "value"        # Push to left (head)
RPUSH mylist "value"        # Push to right (tail)
LPUSH mylist "a" "b" "c"    # Push multiple
LPUSHX mylist "value"       # Push only if list exists
RPUSHX mylist "value"

# Pop from list
LPOP mylist                 # Pop from left
RPOP mylist                 # Pop from right
LPOP mylist 3               # Pop 3 elements from left
BLPOP mylist 30             # Blocking pop (wait 30 seconds)
BRPOP mylist 30             # Blocking pop from right
BRPOPLPUSH source dest 30   # Pop from source, push to dest

# Get list elements
LRANGE mylist 0 -1          # Get all elements
LRANGE mylist 0 9           # Get first 10 elements
LINDEX mylist 0             # Get element at index

# Get list length
LLEN mylist

# Set element at index
LSET mylist 0 "newvalue"

# Insert element
LINSERT mylist BEFORE "pivot" "value"
LINSERT mylist AFTER "pivot" "value"

# Remove elements
LREM mylist 0 "value"       # Remove all occurrences
LREM mylist 2 "value"       # Remove first 2 occurrences
LREM mylist -2 "value"      # Remove last 2 occurrences

# Trim list
LTRIM mylist 0 99           # Keep only first 100 elements

# Move element between lists
LMOVE source dest LEFT RIGHT

Set Operations

# Add to set
SADD myset "member"
SADD myset "a" "b" "c"      # Add multiple

# Remove from set
SREM myset "member"
SPOP myset                  # Remove and return random member
SPOP myset 3                # Remove and return 3 random members

# Check membership
SISMEMBER myset "member"    # Returns 1 or 0
SMISMEMBER myset "a" "b"    # Check multiple members

# Get set members
SMEMBERS myset              # Get all members
SRANDMEMBER myset           # Get random member
SRANDMEMBER myset 3         # Get 3 random members

# Get set size
SCARD myset

# Set operations
SUNION set1 set2            # Union
SINTER set1 set2            # Intersection
SDIFF set1 set2             # Difference (in set1 but not set2)

# Store set operation results
SUNIONSTORE destset set1 set2
SINTERSTORE destset set1 set2
SDIFFSTORE destset set1 set2

# Move member between sets
SMOVE source dest "member"

# Scan set members
SSCAN myset 0 MATCH pattern COUNT 100

Sorted Set Operations

# Add to sorted set
ZADD myzset 1 "one"
ZADD myzset 2 "two" 3 "three"       # Add multiple
ZADD myzset NX 1 "one"              # Only if not exists
ZADD myzset XX 1 "one"              # Only if exists
ZADD myzset GT 5 "one"              # Only if new score > current
ZADD myzset LT 5 "one"              # Only if new score < current

# Get score
ZSCORE myzset "member"

# Increment score
ZINCRBY myzset 2 "member"

# Get rank
ZRANK myzset "member"               # Rank (low to high)
ZREVRANK myzset "member"            # Reverse rank (high to low)

# Get members by rank
ZRANGE myzset 0 -1                  # All members (low to high)
ZRANGE myzset 0 -1 WITHSCORES       # With scores
ZREVRANGE myzset 0 9                # Top 10 (high to low)
ZREVRANGE myzset 0 9 WITHSCORES

# Get members by score
ZRANGEBYSCORE myzset 0 100
ZRANGEBYSCORE myzset -inf +inf
ZRANGEBYSCORE myzset (1 5           # Exclusive lower bound
ZREVRANGEBYSCORE myzset 100 0

# Count members
ZCARD myzset                        # Total count
ZCOUNT myzset 0 100                 # Count in score range
ZLEXCOUNT myzset [a [z              # Count in lex range

# Remove members
ZREM myzset "member"
ZREMRANGEBYRANK myzset 0 9          # Remove by rank range
ZREMRANGEBYSCORE myzset 0 100       # Remove by score range

# Pop min/max
ZPOPMIN myzset                      # Pop lowest score
ZPOPMAX myzset                      # Pop highest score
BZPOPMIN myzset 30                  # Blocking pop min
BZPOPMAX myzset 30                  # Blocking pop max

# Set operations
ZUNIONSTORE dest 2 zset1 zset2
ZINTERSTORE dest 2 zset1 zset2

Hash Operations

# Set hash fields
HSET myhash field "value"
HSET myhash f1 "v1" f2 "v2"         # Multiple fields
HSETNX myhash field "value"         # Only if field doesn't exist
HMSET myhash f1 "v1" f2 "v2"        # Deprecated, use HSET

# Get hash fields
HGET myhash field
HMGET myhash f1 f2 f3               # Get multiple fields
HGETALL myhash                      # Get all fields and values
HKEYS myhash                        # Get all field names
HVALS myhash                        # Get all values

# Check field existence
HEXISTS myhash field

# Get hash size
HLEN myhash

# Delete fields
HDEL myhash field
HDEL myhash f1 f2 f3

# Increment field value
HINCRBY myhash field 5
HINCRBYFLOAT myhash field 1.5

# Get field string length
HSTRLEN myhash field

# Scan hash fields
HSCAN myhash 0 MATCH pattern COUNT 100

Pub/Sub

# Subscribe to channel
SUBSCRIBE channel
SUBSCRIBE channel1 channel2

# Subscribe to pattern
PSUBSCRIBE news.*
PSUBSCRIBE user:*:notifications

# Unsubscribe
UNSUBSCRIBE channel
PUNSUBSCRIBE pattern

# Publish message
PUBLISH channel "message"

# Get active channels
PUBSUB CHANNELS
PUBSUB CHANNELS news.*

# Get subscriber count
PUBSUB NUMSUB channel1 channel2

# Get pattern subscriber count
PUBSUB NUMPAT

Transactions

# Start transaction
MULTI

# Queue commands
SET key1 "value1"
SET key2 "value2"
INCR counter

# Execute transaction
EXEC

# Discard transaction
DISCARD

# Watch keys for optimistic locking
WATCH key1 key2
MULTI
SET key1 "newvalue"
EXEC                        # Fails if watched keys changed

# Unwatch all keys
UNWATCH

Scripting (Lua)

# Execute Lua script
EVAL "return 'Hello'" 0
EVAL "return redis.call('GET', KEYS[1])" 1 mykey
EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey "value"

# Load script (returns SHA1)
SCRIPT LOAD "return 'Hello'"

# Execute loaded script by SHA1
EVALSHA "sha1hash" 0

# Check if script exists
SCRIPT EXISTS sha1hash

# Kill running script
SCRIPT KILL

# Flush script cache
SCRIPT FLUSH

Persistence

RDB (Snapshotting)

# Manual save (blocking)
SAVE

# Background save (non-blocking)
BGSAVE

# Check background save status
LASTSAVE

# Configure automatic saves (redis.conf)
# save 900 1                  # Save if 1 key changed in 900 seconds
# save 300 10                 # Save if 10 keys changed in 300 seconds
# save 60 10000               # Save if 10000 keys changed in 60 seconds

AOF (Append Only File)

# Rewrite AOF file
BGREWRITEAOF

# Check AOF status
INFO persistence

# Configure AOF (redis.conf)
# appendonly yes
# appendfsync always          # Fsync after every write
# appendfsync everysec        # Fsync every second (default)
# appendfsync no              # Let OS decide

Replication

# Check replication status
INFO replication

# Make instance a replica
REPLICAOF hostname 6379
SLAVEOF hostname 6379       # Deprecated

# Promote replica to master
REPLICAOF NO ONE

# Check replica lag
INFO replication            # Check master_repl_offset vs slave_repl_offset

Cluster Commands

# Cluster info
CLUSTER INFO
CLUSTER NODES
CLUSTER SLOTS

# Add node to cluster
CLUSTER MEET ip port

# Assign slots
CLUSTER ADDSLOTS 0 1 2 3

# Get key slot
CLUSTER KEYSLOT mykey

# Failover
CLUSTER FAILOVER

# Cluster mode in redis-cli
redis-cli -c -h hostname -p 6379

Memory Management

# Get memory usage
INFO memory
MEMORY STATS
MEMORY USAGE key            # Memory used by specific key

# Get memory doctor report
MEMORY DOCTOR

# Purge lazy-free memory
MEMORY PURGE

# Debug object
DEBUG OBJECT key

# Configure max memory
CONFIG SET maxmemory 1gb

# Configure eviction policy
CONFIG SET maxmemory-policy allkeys-lru

# Eviction policies:
# noeviction     - Return error when memory limit reached
# allkeys-lru    - Remove least recently used keys
# allkeys-lfu    - Remove least frequently used keys
# allkeys-random - Remove random keys
# volatile-lru   - Remove LRU keys with expiration set
# volatile-lfu   - Remove LFU keys with expiration set
# volatile-random - Remove random keys with expiration
# volatile-ttl   - Remove keys with shortest TTL

Security

# Authenticate
AUTH password
AUTH username password      # ACL (Redis 6+)

# Set password (redis.conf)
# requirepass yourpassword

# ACL commands (Redis 6+)
ACL LIST                    # List all users
ACL WHOAMI                  # Current user
ACL GETUSER username        # Get user details
ACL SETUSER username on >password ~* +@all
ACL DELUSER username

# ACL categories
ACL CAT                     # List categories
ACL CAT read                # Commands in category

Monitoring and Debugging

# Real-time monitoring (shows all commands)
MONITOR                     # Caution: impacts performance

# Slow log
SLOWLOG GET 10              # Get last 10 slow queries
SLOWLOG LEN                 # Number of slow log entries
SLOWLOG RESET               # Clear slow log

# Configure slow log
CONFIG SET slowlog-log-slower-than 10000   # Microseconds
CONFIG SET slowlog-max-len 128

# Client connections
CLIENT LIST                 # List all clients
CLIENT GETNAME              # Get current client name
CLIENT SETNAME "myapp"      # Set client name
CLIENT KILL ip:port         # Kill client connection
CLIENT PAUSE 5000           # Pause clients for 5 seconds

# Debug
DEBUG SLEEP 5               # Sleep for 5 seconds
DEBUG SEGFAULT              # Crash server (testing only!)

Common Patterns

Caching Pattern

# Check cache, fetch if miss
GET cache:user:123
# If nil, fetch from database and cache
SETEX cache:user:123 3600 "{...json...}"

# Cache with sliding expiration
GET cache:session:abc
EXPIRE cache:session:abc 1800    # Reset TTL on access

Rate Limiting

# Simple rate limiter (fixed window)
INCR ratelimit:user:123:minute
EXPIRE ratelimit:user:123:minute 60

# Check if over limit
GET ratelimit:user:123:minute
# If > 100, reject request

# Sliding window rate limiter
ZADD ratelimit:user:123 <timestamp> <request_id>
ZREMRANGEBYSCORE ratelimit:user:123 0 <timestamp-60>
ZCARD ratelimit:user:123

Distributed Lock

# Acquire lock
SET lock:resource <unique_id> NX EX 30

# Release lock (Lua script for atomicity)
EVAL "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end" 1 lock:resource <unique_id>

Session Storage

# Store session
HSET session:abc123 user_id 456 username "john" role "admin"
EXPIRE session:abc123 3600

# Get session data
HGETALL session:abc123

# Update session
HSET session:abc123 last_access 1735689600
EXPIRE session:abc123 3600

Leaderboard

# Add/update score
ZADD leaderboard 1500 "player:123"
ZINCRBY leaderboard 50 "player:123"

# Get top 10
ZREVRANGE leaderboard 0 9 WITHSCORES

# Get player rank
ZREVRANK leaderboard "player:123"

# Get players around a score
ZREVRANGEBYSCORE leaderboard 1600 1400 WITHSCORES LIMIT 0 10

Message Queue

# Producer: add to queue
LPUSH queue:tasks "{task_data}"

# Consumer: blocking pop
BRPOP queue:tasks 30

# Reliable queue with backup
BRPOPLPUSH queue:tasks queue:processing 30

# After processing, remove from backup
LREM queue:processing 1 "{task_data}"

CLI Tips and Tricks

# Batch operations from file
cat commands.txt | redis-cli

# Output to file
redis-cli --scan --pattern "user:*" > keys.txt

# Pipe mode (mass insertion)
cat data.txt | redis-cli --pipe

# Get all keys matching pattern (production safe)
redis-cli --scan --pattern "session:*"

# Count keys matching pattern
redis-cli --scan --pattern "cache:*" | wc -l

# Delete keys matching pattern
redis-cli --scan --pattern "temp:*" | xargs redis-cli DEL

# Export/import (using DUMP/RESTORE)
redis-cli --rdb dump.rdb

# Latency monitoring
redis-cli --latency
redis-cli --latency-history
redis-cli --latency-dist

# Memory analysis
redis-cli --bigkeys          # Find largest keys
redis-cli --memkeys          # Memory usage per key

# Stat monitoring
redis-cli --stat             # Continuous stats

# Interactive mode with formatting
redis-cli
> SET user:1 '{"name":"John"}'
> GET user:1

Configuration Reference

# Common redis.conf settings

# Network
bind 127.0.0.1              # Bind to localhost only
port 6379                   # Default port
protected-mode yes          # Require auth for external connections
timeout 0                   # Client timeout (0 = disabled)
tcp-keepalive 300          # TCP keepalive

# Memory
maxmemory 1gb              # Maximum memory
maxmemory-policy allkeys-lru

# Persistence
save 900 1                  # RDB snapshots
appendonly yes              # Enable AOF
appendfsync everysec        # AOF sync policy

# Security
requirepass yourpassword    # Password
rename-command FLUSHALL ""  # Disable dangerous commands
rename-command CONFIG ""

# Logging
loglevel notice             # verbose, debug, notice, warning
logfile /var/log/redis/redis.log

# Limits
maxclients 10000           # Max client connections

Troubleshooting

Connection Issues

# Test connectivity
redis-cli PING

# Check if Redis is running
systemctl status redis
ps aux | grep redis

# Check listening port
netstat -tlnp | grep 6379
ss -tlnp | grep 6379

# Test from remote host
redis-cli -h remote_host -p 6379 PING

Performance Issues

# Check slow queries
SLOWLOG GET 25

# Check memory usage
INFO memory
MEMORY DOCTOR

# Find large keys
redis-cli --bigkeys

# Check client connections
CLIENT LIST
INFO clients

# Check replication lag
INFO replication

Memory Issues

# Check memory stats
INFO memory

# Check eviction stats
INFO stats | grep evicted

# Analyze key memory usage
MEMORY USAGE key SAMPLES 5

# Clear unused memory
MEMORY PURGE

Service Management

systemd (Linux)

# Start Redis
sudo systemctl start redis

# Stop Redis
sudo systemctl stop redis

# Restart Redis
sudo systemctl restart redis

# Enable on boot
sudo systemctl enable redis

# Check status
sudo systemctl status redis

# View logs
sudo journalctl -u redis -f

Docker

# Run Redis container
docker run -d --name redis -p 6379:6379 redis

# Run with persistence
docker run -d --name redis -p 6379:6379 -v redis-data:/data redis redis-server --appendonly yes

# Run with password
docker run -d --name redis -p 6379:6379 redis redis-server --requirepass mypassword

# Connect to containerized Redis
docker exec -it redis redis-cli

Generate Secure Secrets for Docker

# Generate Redis password (32 characters, alphanumeric)
openssl rand -base64 32 | tr -dc 'a-zA-Z0-9' | head -c 32

# Generate Redis password (64 characters hex)
openssl rand -hex 32

# Generate Redis encryption key (256-bit for AES-256)
openssl rand -base64 32

# Generate JWT secret (64 characters)
openssl rand -base64 48

# Alternative using /dev/urandom
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 64

# Generate all secrets at once and save to .env file
cat << 'EOF' > .env
REDIS_PASSWORD=$(openssl rand -base64 32 | tr -dc 'a-zA-Z0-9' | head -c 32)
REDIS_ENCRYPTION_KEY=$(openssl rand -base64 32)
JWT_SECRET=$(openssl rand -base64 48)
EOF

# Or generate inline for docker run
docker run -d --name redis \
  -p 6379:6379 \
  -e REDIS_PASSWORD="$(openssl rand -hex 32)" \
  redis redis-server --requirepass "$REDIS_PASSWORD"

Docker Compose with Secrets

# docker-compose.yml
version: '3.8'

services:
  redis:
    image: redis:7-alpine
    container_name: redis
    restart: unless-stopped
    ports:
      - "6379:6379"
    volumes:
      - redis-data:/data
    command: redis-server --requirepass ${REDIS_PASSWORD} --appendonly yes
    environment:
      - REDIS_PASSWORD=${REDIS_PASSWORD}
    healthcheck:
      test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  redis-data:
# Generate .env file for docker-compose
cat << EOF > .env
REDIS_PASSWORD=$(openssl rand -hex 32)
REDIS_ENCRYPTION_KEY=$(openssl rand -base64 32)
JWT_SECRET=$(openssl rand -base64 48)
EOF

# Start with docker-compose
docker-compose up -d

# Verify secrets are loaded
docker-compose exec redis redis-cli -a $REDIS_PASSWORD PING

Docker Secrets (Swarm Mode)

# Create secrets in Docker Swarm
openssl rand -hex 32 | docker secret create redis_password -
openssl rand -base64 32 | docker secret create redis_encryption_key -
openssl rand -base64 48 | docker secret create jwt_secret -

# List secrets
docker secret ls

# Use in docker-compose for swarm
# docker-stack.yml
version: '3.8'

services:
  redis:
    image: redis:7-alpine
    secrets:
      - redis_password
    command: >
      sh -c 'redis-server --requirepass "$$(cat /run/secrets/redis_password)"'

secrets:
  redis_password:
    external: true
  redis_encryption_key:
    external: true
  jwt_secret:
    external: true