Complete Redis command reference covering all data types, pub/sub, transactions, Lua scripting, persistence, clustering, and common patterns like caching and rate limiting.
# Atomic compare-and-set: only update if current value matches
EVAL "
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('SET', KEYS[1], ARGV[2])
else
return nil
end
" 1 mykey "old_value" "new_value"
Persistence (RDB/AOF)
Command
Description
BGSAVE
Trigger a background RDB snapshot
SAVE
Trigger a synchronous RDB snapshot (blocks server)
LASTSAVE
Get the Unix timestamp of the last successful save
BGREWRITEAOF
Trigger a background AOF rewrite
CONFIG SET save "60 1000"
Auto-save RDB if 1000 keys changed in 60 seconds
CONFIG SET appendonly yes
Enable AOF persistence at runtime
CONFIG SET appendfsync everysec
Set AOF fsync policy (always, everysec, no)
CONFIG SET aof-use-rdb-preamble yes
Use RDB+AOF hybrid format for faster loads
DEBUG SLEEP 0
Check if a BGSAVE is in progress
Persistence Options Comparison
Feature
RDB (Snapshots)
AOF (Append Only File)
How it works
Point-in-time binary snapshots
Logs every write operation
File size
Compact
Larger (can be compacted via rewrite)
Data loss risk
Minutes of data between snapshots
At most 1 second with everysec fsync
Restart speed
Fast (load binary dump)
Slower (replay all operations)
Best for
Backups, disaster recovery
Minimal data loss requirements
Cluster Commands
Command
Description
CLUSTER INFO
Get cluster state and statistics
CLUSTER NODES
List all nodes in the cluster
CLUSTER MYID
Get the node ID of the current node
CLUSTER MEET <ip> <port>
Add a node to the cluster
CLUSTER FORGET <node-id>
Remove a node from the cluster
CLUSTER REPLICATE <node-id>
Make current node a replica of the given master
CLUSTER SLOTS
Get the mapping of hash slots to nodes
CLUSTER KEYSLOT <key>
Get the hash slot for a given key
CLUSTER COUNTKEYSINSLOT <slot>
Count keys in a specific hash slot
CLUSTER ADDSLOTS <slot> [slot ...]
Assign hash slots to the current node
CLUSTER DELSLOTS <slot> [slot ...]
Remove hash slot assignments from the current node
CLUSTER FAILOVER
Force a replica to perform a manual failover
CLUSTER RESET SOFT
Soft reset: clear slot assignments and known nodes
Check cache first. On miss, load from database and store in cache with a TTL to prevent stale data.
# Pseudocode for cache-aside pattern
value = GET "cache:user:123"
if value is nil:
value = db.query("SELECT * FROM users WHERE id=123")
SET "cache:user:123" value EX 300 # Cache for 5 minutes
return value
# Invalidate on update
DEL "cache:user:123"
Rate Limiting (Sliding Window)
Limit API calls per user using a sorted set with timestamps. Clean up expired entries on each check.
# Allow 100 requests per 60 seconds per user
MULTI
ZREMRANGEBYSCORE "ratelimit:user:42" 0 (NOW - 60)
ZADD "ratelimit:user:42" NOW NOW
ZCARD "ratelimit:user:42"
EXPIRE "ratelimit:user:42" 60
EXEC
# If ZCARD result > 100, reject the request
Rate Limiting (Fixed Window Counter)
Simple counter-based rate limiting. Lighter than the sliding window but less precise at boundaries.
# Allow 100 requests per minute
key = "ratelimit:user:42:" + current_minute
count = INCR key
if count == 1:
EXPIRE key 60
if count > 100:
reject request
Session Management
Store user sessions as Redis hashes with automatic expiry. Fast reads/writes for session data.
Use SET NX with an expiry to implement a simple distributed lock. Always include a unique token for safe release.
# Acquire lock (only if not held)
SET "lock:resource" "unique-token-abc" NX EX 30
# Release lock (only if we hold it) — use Lua 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-token-abc"
Leaderboard
Use sorted sets for real-time leaderboards with O(log N) inserts and O(log N + M) range queries.
# Add or update a player's score
ZADD "leaderboard:game1" 1500 "player:42"
# Get top 10 players
ZREVRANGE "leaderboard:game1" 0 9 WITHSCORES
# Get a player's rank (0-indexed, highest first)
ZREVRANK "leaderboard:game1" "player:42"
# Increment a player's score
ZINCRBY "leaderboard:game1" 50 "player:42"
Frequently Asked Questions
What is Redis and what is it used for?
Redis (Remote Dictionary Server) is an open-source, in-memory data structure store used as a database, cache, message broker, and streaming engine. It supports data structures such as strings, lists, sets, sorted sets, hashes, bitmaps, and streams. Redis is widely used for caching, session management, real-time analytics, rate limiting, leaderboards, and pub/sub messaging due to its sub-millisecond response times.
What is the difference between RDB and AOF persistence in Redis?
RDB (Redis Database) creates point-in-time snapshots of the dataset at specified intervals. It produces compact binary files ideal for backups but may lose data between snapshots. AOF (Append Only File) logs every write operation, providing better durability since you can configure it to fsync every second or on every write. AOF files are larger but can be rewritten to stay compact. Many production deployments use both RDB and AOF together for the best combination of fast restarts (RDB) and minimal data loss (AOF).
How does Redis Cluster handle data sharding?
Redis Cluster automatically partitions data across multiple nodes using hash slots. The key space is divided into 16,384 hash slots, and each node in the cluster is responsible for a subset of these slots. When a key is stored, Redis computes its hash slot using CRC16(key) mod 16384 and routes it to the correct node. Redis Cluster also provides high availability through automatic failover: each master node can have one or more replica nodes that take over if the master fails.