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

CommandPurpose
SET key valueSet a string value
GET keyRetrieve a value
SET key value EX 60Set with a 60-second expiry
INCR counterIncrement an integer
MSET k1 v1 k2 v2Set multiple keys at once
MGET k1 k2Retrieve 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

CommandPurpose
PINGCheck server connectivity
INFOShow server statistics
DBSIZENumber of keys in the current database
FLUSHDBDelete all keys in the current database
CONFIG GET maxmemoryView a configuration value

Quick Reference by Use Case

Use caseRecommended type
Caching HTML fragmentsString with EX
User sessionsHash with expiry
Job queueList with LPUSH / BRPOP
LeaderboardSorted set
Unique visitorsSet
Rate limitingSorted set or INCR with expiry