Deep Dive into Redis VII: Commands
ð Document Overviewâ
Organized by usage frequency and modern patterns
ð Top 10 Most Used Redis Commandsâ
1. SET - Store Key-Value Pairâ
Purpose: Store string value with optional expiration
Syntax:
SET key value [EX seconds|PX milliseconds] [NX|XX]
Real-life Scenarios:
- User session storage
- Cache with TTL (Time-To-Live)
- Feature flag storage
- Temporary data storage
Best Practices:
# Cache with 60-second expiration
SET user:123:profile "{name: 'John', email: 'john@email.com'}" EX 60
# Set only if key doesn't exist (for locks)
SET lock:order:456 "processing" EX 30 NX
# Set only if key exists (for updates)
SET user:123:status "active" XX
Diagram:
âââââââââââââââââââââââââââââââââââââââââââââââ
â SET Command Flow â
âââââââââââââââââââââââââââââââââââââââââââââââ€
â Client Redis Server â
â â â â
â â SET key value EX 30 â â
â âââââââââââââââââââââââââââ>â â
â â â â
â â "OK" â â
â â<âââââââââââââââââââââââââââ â
â â â â
â â (30 seconds later) â â
â â GET key â â
â âââââââââââââââââââââââââââ>â â
â â (nil) â â
â â<âââââââââââââââââââââââââââ â
âââââââââââââââââââââââââââââââââââââââââââââââ
2. GET - Retrieve Key Valueâ
Purpose: Get value of a key
Syntax: GET key
Real-life Scenarios:
- Retrieve cached data
- Read configuration
- Check feature flags
Examples:
# Basic get
GET user:456:profile
# Use with EXISTS check first
EXISTS user:456:profile
GET user:456:profile
# Pattern for cache miss handling
GET product:789
# If nil, fetch from database and SET with EX
3. DEL - Delete Keysâ
Purpose: Remove one or more keys
Syntax: DEL key [key ...]
Best Practices:
# Delete single key
DEL user:123:session
# Delete multiple keys
DEL user:123:profile user:123:preferences user:123:cart
# Safer deletion with EXISTS check
EXISTS important:config
DEL important:config
# Use UNLINK for large keys in production (non-blocking)
UNLINK large:dataset:456
4. INCR/DECR - Atomic Countersâ
Purpose: Increment/decrement integer values atomically
Real-life Scenarios:
- Page view counters
- Rate limiting
- Inventory management
- Unique ID generation
Examples:
# Basic counter
SET page:views 0
INCR page:views # Returns 1
INCR page:views # Returns 2
# Rate limiting pattern
INCR rate:limit:192.168.1.1
EXPIRE rate:limit:192.168.1.1 60
# Decrement inventory
SET product:789:stock 100
DECR product:789:stock # Returns 99
# Increment by specific amount
INCRBY user:123:score 50
DECRBY user:123:score 20
Rate Limiting Diagram:
âââââââââââââââââââââââââââââââââââââââââââââââââââ
â Rate Limiting Pattern â
âââââââââââââââââââââââââââââââââââââââââââââââââââ€
â Minute 1 â Minute 2 â Minute 3 â
â âââââââââââ â âââââââââââ â âââââââââââ â
â âRequest 1â â âRequest 1â â âRequest 1â â
â âINCR key â â âINCR key â â âINCR key â â
â âEXPIRE â â âEXPIRE â â âEXPIRE â â
â âââââââââââ â âââââââââââ â âââââââââââ â
â âRequest 2â â âRequest 2â â â
â âINCRâ2 â â âINCRâ2 â â â
â âââââââââââ â âââââââââââ â â
â âRequest 3â â âRequest 3â â â
â âINCRâ3 â â âINCRâ3 â â â
â âââââââââââ â âââââââââââ â â
â âRequest 4â â âRequest 4â â â
â âINCRâ4 â â âGETâ4 â â â
â âIF >3 â â âIF >3 â â â
â âReject â â âReject â â â
â âââââââââââ â âââââââââââ â â
âââââââââââââââââââââââââââââââââââââââââââââââââââ
5. EXPIRE - Set Key Expirationâ
Purpose: Set timeout on key
Syntax: EXPIRE key seconds
Modern Alternatives:
# Set with expiration in one command (preferred)
SET session:abc123 "user_data" EX 3600
# Update existing key's TTL
EXPIRE cache:key 300
EXPIREAT cache:key 1672531200 # Unix timestamp
# Check remaining TTL
TTL session:abc123
# Returns: -2 (key doesn't exist)
# Returns: -1 (key exists, no expire)
# Returns: >0 (seconds remaining)
# Remove expiration
PERSIST important:config
6. HSET/HGET - Hash Operationsâ
Purpose: Store field-value pairs within a key
Real-life Scenarios:
- User profiles
- Product information
- Object storage
- Partial updates
Examples:
# Store user profile
HSET user:123 name "John Doe" email "john@email.com" age 30
# Get specific fields
HGET user:123 name # "John Doe"
HGET user:123 age # "30"
# Get all fields
HGETALL user:123
# Update single field
HSET user:123 age 31
# Check if field exists
HEXISTS user:123 email
# Increment numeric field
HINCRBY user:123 visits 1
# Get multiple fields
HMGET user:123 name email phone
Hash vs String Storage:
âââââââââââââââââââ âââââââââââââââââââ
â String Storage â â Hash Storage â
ââââââââââââââââââ†âââââââââââââââââââ€
â â â â
â user:123 â â user:123 â
â ââââââââââââ â â ââââââââââââ â
â { â â name: "John" â
â "name": â â email: "john@" â
â "John", â â age: "30" â
â "email": â â â
â "john@...", â â â
â "age": 30 â â â
â } â â â
â â â â
â Memory: 100B â â Memory: 80B â
â â â (more efficientâ
â â â for many flds)â
âââââââââââââââââââ âââââââââââââââââââ
7. LPUSH/RPUSH - List Operationsâ
Purpose: Add elements to lists
Real-life Scenarios:
- Message queues
- Activity feeds
- Recent items
- Job queues
Examples:
# Message queue pattern
LPUSH messages:queue "{job: 'process', data: {...}}"
LPUSH messages:queue "{job: 'email', data: {...}}"
# Worker processing
RPOP messages:queue # Gets oldest item
# Recent activities
LPUSH user:123:activity "Logged in"
LPUSH user:123:activity "Viewed product:789"
LPUSH user:123:activity "Purchased item"
# Get range (last 10 activities)
LRANGE user:123:activity 0 9
# Fixed-length list (news feed)
LPUSH feed:global "News item 1"
LTRIM feed:global 0 99 # Keep only 100 items
Message Queue Pattern:
âââââââââââââââ LPUSH âââââââââââââââ RPOP/BLPOP âââââââââââââââ
â Producer ââââââââââââ>â Redis â<ââââââââââââââââ Consumer â
â â â List â â â
â â â âââââââââ â â â
â â â â Msg 3 â â â â
â â â â Msg 2 â â â â
â â â â Msg 1 â â â â
â â â âââââââââ â â â
âââââââââââââââ âââââââââââââââ âââââââââââââââ
â â â
â â â
â (FIFO Queue) â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
8. SADD/SMEMBERS - Set Operationsâ
Purpose: Store unique unordered elements
Real-life Scenarios:
- Tags/categories
- Unique visitors
- Friends/followers
- Vote tracking
Examples:
# Store tags
SADD article:456:tags "redis" "database" "nosql" "cache"
# Check membership
SISMEMBER article:456:tags "redis" # Returns 1 (true)
# Get all members
SMEMBERS article:456:tags
# Set operations (powerful!)
SADD users:online "user1" "user2" "user3"
SADD users:active "user2" "user3" "user4"
# Intersection (users both online AND active)
SINTER users:online users:active # ["user2", "user3"]
# Union (all unique users)
SUNION users:online users:active # ["user1","user2","user3","user4"]
# Difference (online but not active)
SDIFF users:online users:active # ["user1"]
# Random element (lottery, sampling)
SRANDMEMBER users:online
SPOP users:online # Removes and returns random
9. ZADD/ZRANGE - Sorted Set Operationsâ
Purpose: Store sorted unique elements with scores
Real-life Scenarios:
- Leaderboards
- Time-series data
- Priority queues
- Range queries
Examples:
# Leaderboard
ZADD leaderboard 1000 "player1"
ZADD leaderboard 850 "player2"
ZADD leaderboard 920 "player3"
# Get top 3 players
ZREVRANGE leaderboard 0 2 WITHSCORES
# Get player rank (0-indexed from top)
ZREVRANK leaderboard "player2"
# Increment score
ZINCRBY leaderboard 50 "player1"
# Range queries (scores 800-900)
ZRANGEBYSCORE leaderboard 800 900
# Time-series pattern
ZADD temperature:nyc 1672444800 "38.5" # timestamp, value
ZADD temperature:nyc 1672448400 "39.2"
ZRANGEBYSCORE temperature:nyc 1672444800 1672448400
Leaderboard Architecture:
âââââââââââââââââââââââââââââââââââââââââââââââââââ
â Redis Sorted Set Leaderboard â
âââââââââââââââââââââââââââââââââââââââââââââââââââ€
â Score â Member â Operations â
ââââââââââââŒââââââââââââââââââŒââââââââââââââââââââ€
â 1050 â player1 â ZADD score â
â 920 â player3 â ZINCRBY +50 â
â 850 â player2 â ZREVRANGE 0 2 â
â 720 â player4 â ZREVRANK player2 â
â 650 â player5 â ZRANGEBYSCORE â
â â â 800 1000 â
ââââââââââââŽââââââââââââââââââŽââââââââââââââââââââ
â²
â
ââââ Scores automatically sorted,
O(log N) operations
10. SCAN - Safe Key Iterationâ
Purpose: Incrementally iterate keys without blocking
Why not KEYS?
KEYS *blocks Redis (use in production with extreme caution)SCANis non-blocking, production-safe
Examples:
# Iterate through all keys matching pattern
SCAN 0 MATCH user:* COUNT 100
# Iterate specific type
SCAN 0 MATCH product:* COUNT 50 TYPE string
# Hash scan
HSCAN user:123 0 MATCH *name* COUNT 10
# Set scan
SSCAN tags:article:456 0 COUNT 20
# Sorted set scan
ZSCAN leaderboard 0 COUNT 15
SCAN Iteration Pattern:
âââââââââââââââââââââââââââââââââââââââââââââââ
â SCAN Iteration Process â
âââââââââââââââââââââââââââââââââââââââââââââââ€
â Initial: SCAN 0 MATCH user:* COUNT 5 â
â Returns: â
â 1) "5" (next cursor) â
â 2) ["user:1", "user:2", "user:3"] â
â â
â Next: SCAN 5 MATCH user:* COUNT 5 â
â Returns: â
â 1) "12" (next cursor) â
â 2) ["user:4", "user:5"] â
â â
â Next: SCAN 12 MATCH user:* COUNT 5 â
â Returns: â
â 1) "0" (iteration complete) â
â 2) ["user:6"] â
â â
â Cursor 0 = Done â
âââââââââââââââââââââââââââââââââââââââââââââââ
ðïž Data Structure Selection Guideâ
âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â Choosing the Right Data Structure â
ââââââââââââââââ¬âââââââââââââââââ¬ââââââââââââââ¬ââââââââââââââââ€
â Use Case â Structure â Best For â Example â
ââââââââââââââââŒâââââââââââââââââŒââââââââââââââŒââââââââââââââââ€
â Simple Cache â String â Single vals â SET/GET â
â â â With TTL â user:session â
ââââââââââââââââŒâââââââââââââââââŒââââââââââââââŒââââââââââââââââ€
â Object Store â Hash â Multiple â HSET/HGETALL â
â â â fields â user:profile â
ââââââââââââââââŒâââââââââââââââââŒââââââââââââââŒââââââââââââââââ€
â Queue â List â FIFO/LIFO â LPUSH/RPOP â
â â â â jobs:queue â
ââââââââââââââââŒâââââââââââââââââŒââââââââââââââŒââââââââââââââââ€
â Unique Items â Set â Membership â SADD/SISMEMBERâ
â â â Operations â article:tags â
ââââââââââââââââŒâââââââââââââââââŒââââââââââââââŒââââââââââââââââ€
â Rankings â Sorted Set â Scores â ZADD/ZRANGE â
â â â Ranges â leaderboard â
ââââââââââââââââŒâââââââââââââââââŒââââââââââââââŒââââââââââââââââ€
â Time Series â Sorted Set â Timestamps â ZADD ts:data â
â â or Stream â Sequences â XADD log:streamâ
ââââââââââââââââŽâââââââââââââââââŽââââââââââââââŽââââââââââââââââ
â¡ Advanced & Modern Patternsâ
11. Pipeline - Batch Operationsâ
Purpose: Reduce round-trip time
# Without pipeline (3 round trips)
SET user:1:name "John"
SET user:1:email "john@email.com"
SET user:1:age 30
# With pipeline (1 round trip)
MULTI
SET user:1:name "John"
SET user:1:email "john@email.com"
SET user:1:age 30
EXEC
12. Transactions - Atomic Operationsâ
MULTI
GET account:123:balance
DECRBY account:123:balance 100
INCRBY account:456:balance 100
EXEC
13. Lua Scripting - Complex Atomic Operationsâ
EVAL "local current = redis.call('GET', KEYS[1])
if tonumber(current) < tonumber(ARGV[1]) then
return redis.call('INCR', KEYS[1])
else
return nil
end" 1 rate:limit:ip 10
14. Streams - Modern Message Queueâ
# Producer
XADD mystream * sensor-id 1234 temperature 19.8
# Consumer group
XGROUP CREATE mystream mygroup 0
# Consumer
XREADGROUP GROUP mygroup consumer1 COUNT 1 BLOCK 5000 STREAMS mystream >
ð Security & Production Commandsâ
15. AUTH - Authenticationâ
AUTH your_strong_password_here
# Better: Use Redis 6+ ACL
ACL SETUSER alice on >password ~cache:* +get +set
16. CONFIG - Configuration Managementâ
# Get configuration
CONFIG GET maxmemory
CONFIG GET requirepass
# Set configuration (prefer redis.conf for persistence)
CONFIG SET maxmemory 2gb
CONFIG SET save "900 1 300 10 60 10000"
# Never expose these in production:
CONFIG SET requirepass "" # DON'T!
CONFIG SET protected-mode no # DON'T!
17. INFO - Monitoringâ
# Get all info (verbose)
INFO
# Get specific sections
INFO memory
INFO stats
INFO clients
INFO replication
# Critical metrics to monitor:
INFO memory # used_memory, maxmemory, evictions
INFO stats # instantaneous_ops_per_sec, keyspace_hits/misses
INFO persistence # rdb_last_save_time, aof_rewrite_in_progress
ð¯ Memory Optimization Commandsâ
18. MEMORY USAGEâ
MEMORY USAGE large:key
MEMORY STATS
MEMORY PURGE # Attempts to defragment (Redis 4+)
19. Efficient Data Encodingâ
# Use appropriate data types
# Strings under 44 bytes use EMBSTR encoding
SET small:key "short" # More efficient
# Hashes with <= 512 fields use ziplist
HSET config:app field1 "val1" ... field500 "val500"
# Lists with small elements use ziplist
LPUSH recent:items "item1" "item2" # Check list-max-ziplist* configs
ð Performance Optimization Patternsâ
Connection Pooling Diagram:â
âââââââââââââââ âââââââââââââââââââ âââââââââââââââ
â App â â Connection â â Redis â
â Server âââââââ¶â Pool âââââââ¶â Server â
â â â â â â
â Request 1 â â âââââââââââââ â â â
â âââââââââ â â â ConnectionââââŒââââââ¶â Process â
â GET key â â â 1 â â â Request â
â â â âââââââââââââ â â â
â Request 2 â â âââââââââââââ â â â
â âââââââââ â â â ConnectionââââŒââââââ¶â Process â
â SET key âââââ¬ââ¶â â 2 â â â Request â
â â â â âââââââââââââ â â â
â Request 3 â â â âââââââââââââ â â â
â âââââââââ â âââ¶â â ConnectionââââŒââââââ¶â Process â
â INCR key â â â 3 â â â Request â
â â â âââââââââââââ â â â
âââââââââââââââ âââââââââââââââââââ âââââââââââââââ
20. Monitor Slow Logsâ
# Configure slow log
CONFIG SET slowlog-log-slower-than 10000 # 10ms
CONFIG SET slowlog-max-len 128
# View slow logs
SLOWLOG GET 10
SLOWLOG LEN
SLOWLOG RESET
ð« Anti-Patterns to Avoidâ
Bad Patterns:â
# 1. KEYS * in production (use SCAN instead)
KEYS * # BLOCKS SERVER!
# 2. Large values in single key
SET huge:key "[...10MB of data...]" # Blocks during serialization
# 3. Not using TTL for cache
SET cache:key "data" # Might fill memory
# 4. Using Redis as primary database
# Redis is in-memory - data can be lost
# 5. Not monitoring memory usage
# Leads to OOM (Out Of Memory) errors
Good Patterns:â
# 1. Use pipelining for bulk operations
MULTI
SET key1 "val1"
SET key2 "val2"
EXEC
# 2. Use appropriate data structures
# For object with many fields: Hash, not multiple String keys
# 3. Always set TTL for cache
SET session:abc "data" EX 3600
# 4. Use Lua scripts for complex atomic operations
# 5. Monitor with INFO and SLOWLOG
ð Replication & High Availability Commandsâ
21. Replication Managementâ
# On replica
REPLICAOF master-ip 6379
REPLICAOF NO ONE # Promote to master
# Check replication status
INFO replication
# Monitor replication lag
redis-cli --latency
22. Sentinel & Cluster Commandsâ
# Sentinel
SENTINEL MASTERS
SENTINEL GET-MASTER-ADDR-BY-NAME mymaster
# Cluster
CLUSTER NODES
CLUSTER INFO
CLUSTER SLOTS
ð§¹ Maintenance Commandsâ
23. Backup & Persistenceâ
# Manual save (blocks)
SAVE # Synchronous, blocks
BGSAVE # Asynchronous, forks
# Check persistence status
INFO persistence
LASTSAVE # Unix timestamp of last save
# AOF operations
BGREWRITEAOF
24. Cleanup & Debuggingâ
# Flush data (CAUTION!)
FLUSHDB # Current database
FLUSHALL # All databases
# Debug object
DEBUG OBJECT keyname
# Monitor commands in real-time
MONITOR # Use sparingly, verbose
# Client management
CLIENT LIST
CLIENT KILL addr ip:port
CLIENT PAUSE timeout_ms # Pause clients
ð Monitoring Dashboard Metricsâ
âââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â Redis Health Dashboard â
âââââââââââââââââââ¬ââââââââââââââââââ¬ââââââââââââââââââ€
â Memory Usage â Command Stats â Connections â
âââââââââââââââââââŒââââââââââââââââââŒââââââââââââââââââ€
â Used: 1.2GB/2GBâ Ops/sec: 5,000 â Connected: 45 â
â 60% â Hits: 98% â Max: 10,000 â
â Peak: 1.8GB â Misses: 2% â Rejected: 0 â
â Evictions: 0 â Cmd/sec: 8,000 â Timeout: 0 â
âââââââââââââââââââŒââââââââââââââââââŒââââââââââââââââââ€
â Replication â Persistence â Keyspace â
âââââââââââââââââââŒââââââââââââââââââŒââââââââââââââââââ€
â Role: Master â RDB: Enabled â DB0 Keys: 45K â
â Slaves: 2 â Last Save: 2m â Expires: 12K â
â Lag: 0.5s â AOF: Enabled â Avg TTL: 300s â
â Status: OK â Size: 500MB â Hit Rate: 99% â
âââââââââââââââââââŽââââââââââââââââââŽââââââââââââââââââ
ð Quick Reference Cheat Sheetâ
Caching Patterns:â
# Cache-aside pattern
1. GET cache:key
2. If nil, fetch from DB
3. SET cache:key value EX 300
# Write-through pattern
1. Update DB
2. SET cache:key new_value EX 300
# Write-behind pattern
1. SET cache:key new_value EX 300
2. Async update to DB
Key Design Best Practices:â
Good: Bad:
user:123:profile user_profile_123
session:abc123 abc123_session
product:789:views product_views_789
geo:nyc:users newyork_users_list
Pattern: object_type:id:field
TTL Strategies:â
# Cache: 5 minutes - 1 hour
SET cache:key value EX 300
# Session: 30 minutes - 24 hours
SET session:key data EX 1800
# Rate limit: 1 second - 1 minute
SET rate:limit:ip 1 EX 60 NX
# Leaderboard: 1 day - 7 days
EXPIRE leaderboard:daily 86400
ð Troubleshooting Commandsâ
25. Diagnose Issuesâ
# Check if Redis is alive
PING # Should return PONG
# Check latency between commands
redis-cli --latency
# Monitor commands in real-time (debug)
MONITOR
# Check memory fragmentation
INFO memory | grep fragmentation
# List connected clients
CLIENT LIST
# Check slow queries
SLOWLOG GET 5
26. Performance Testingâ
# Benchmark tool (outside redis-cli)
redis-benchmark -t set,get -n 100000 -q
# Pipeline benchmark
redis-benchmark -t set,get -n 100000 -q -P 16
ðš Visualization: Data Structure Memory Layoutâ
String:
ââââââââââ¬âââââââââ¬âââââââââ
â Header â Data â Null â
â Type â "value"â term â
ââââââââââŽâââââââââŽâââââââââ
Hash (ziplist encoding):
ââââââ¬âââââ¬âââââ¬âââââ¬âââââ¬âââââ
â ZL â F1 â V1 â F2 â V2 â ZL â
âbytesâ"name"â"John"â"age"â"30"âend â
ââââââŽâââââŽâââââŽâââââŽâââââŽâââââ
List (quicklist):
âââââââââââ¬ââââââââââ¬ââââââââââ
â Node â Node â Node â
â [ziplistâ [ziplistâ [ziplistâ
â "item1" â "item4" â "item7" â
â "item2" â "item5" â â
â "item3" â "item6" â â
âââââââââââŽââââââââââŽââââââââââ
ð Further Learning Pathâ
Next Steps:â
- Redis Streams - Modern message queues
- Redis Modules - RediSearch, RedisJSON, RedisGraph
- Redis Cluster - Horizontal scaling
- Redis Sentinel - High availability
- Redis Enterprise - Commercial features
Production Checklist:â
- Set
maxmemoryand eviction policy - Enable persistence (RDB/AOF)
- Configure backups
- Set up monitoring
- Implement connection pooling
- Use key expiration
- Regular maintenance
- Disaster recovery plan
Remember: Redis is single-threaded for commands. One slow command blocks all others. Always test commands in staging before production, and monitor performance metrics regularly.