Overview
Redis is an in-memory data store used for caching, session management, message queues, and real-time leaderboards. This tutorial covers the commands you will reach for most often, organized by use case.
Connecting to Redis
# Connect to local Redis
redis-cli
# Connect to a remote host with authentication
redis-cli -h redis.example.com -p 6379 -a yourpassword
Install Redis from the Redis official download page.
String Commands
| Command | Purpose |
|---|---|
SET key value | Set a string value |
GET key | Retrieve a value |
SET key value EX 60 | Set with a 60-second expiry |
INCR counter | Increment an integer |
MSET k1 v1 k2 v2 | Set multiple keys at once |
MGET k1 k2 | Retrieve multiple keys |
SET session:user1 "active" EX 3600
GET session:user1
INCR page:views
Key Management
# Check if a key exists
EXISTS mykey
# Set a timeout on an existing key
EXPIRE mykey 300
# Check remaining time to live
TTL mykey
# Delete a key
DEL mykey
# Scan keys safely (never use KEYS in production)
SCAN 0 MATCH user:* COUNT 100
KEYS * blocks the Redis event loop on large datasets. Use SCAN instead, which returns results incrementally.
Hash Commands
Hashes store field-value pairs, ideal for objects.
HSET user:1 name "Alice" email "alice@example.com"
HGET user:1 name
HGETALL user:1
HDEL user:1 email
List Commands
# Push to the left (head)
LPUSH queue "task1"
LPUSH queue "task2"
# Pop from the right (tail)
RPOP queue # returns "task1"
# Get a range
LRANGE queue 0 -1
Set Commands
SADD tags "redis" "database" "cache"
SMEMBERS tags
SISMEMBER tags "redis"
SREM tags "cache"
Sorted Set Commands
Sorted sets are ideal for leaderboards and rate limiting.
ZADD leaderboard 100 "player1" 200 "player2" 150 "player3"
ZRANGE leaderboard 0 -1 WITHSCORES
ZREVRANGE leaderboard 0 2 WITHSCORES # top 3
ZINCRBY leaderboard 50 "player1"
Connection and Server Commands
| Command | Purpose |
|---|---|
PING | Check server connectivity |
INFO | Show server statistics |
DBSIZE | Number of keys in the current database |
FLUSHDB | Delete all keys in the current database |
CONFIG GET maxmemory | View a configuration value |
Quick Reference by Use Case
| Use case | Recommended type |
|---|---|
| Caching HTML fragments | String with EX |
| User sessions | Hash with expiry |
| Job queue | List with LPUSH / BRPOP |
| Leaderboard | Sorted set |
| Unique visitors | Set |
| Rate limiting | Sorted set or INCR with expiry |
