This cheatsheet provides a comprehensive reference for Redis, covering essential commands, data structures, common usage patterns, and best practices for developers. All information is current as of December 30, 2025, reflecting features and recommendations for Redis 7.4.
Quick Reference: Most Used Commands
| Command | Description | Example |
|---|---|---|
SET key value [EX seconds] | Sets string value of a key, with optional expiration. | SET mykey "hello" EX 3600 |
GET key | Gets the string value of a key. | GET mykey |
DEL key [key ...] | Deletes one or more keys. | DEL mykey anotherkey |
EXPIRE key seconds | Sets a timeout on key. | EXPIRE session:123 1800 |
HSET key field value [field value ...] | Sets field-value pairs in a hash. | HSET user:1 name "Alice" age 30 |
HGETALL key | Gets all fields and values in a hash. | HGETALL user:1 |
LPUSH key value [value ...] | Prepends one or more values to a list. | LPUSH mylist "item1" "item2" |
RPOP key | Removes and returns the last element of a list. | RPOP mylist |
SADD key member [member ...] | Adds one or more members to a set. | SADD tags "tech" "dev" |
SMEMBERS key | Returns all members of a set. | SMEMBERS tags |
ZADD key score member [score member ...] | Adds one or more members to a sorted set, or updates their scores. | ZADD leaderboard 100 "playerA" 150 "playerB" |
ZRANGE key start stop [WITHSCORES] | Returns a range of members in a sorted set, by index. | ZRANGE leaderboard 0 -1 WITHSCORES |
INFO [section] | Returns information and statistics about the server. | INFO memory |
PING | Returns PONG if the server is alive. | PING |
I. Basic Data Types & Operations
Redis is a data structure server, supporting various data types.
1. Strings
Binary-safe strings, up to 512MB.
| Command | Description | Example |
|---|---|---|
SET key value [EX seconds] | Sets a key’s string value, with optional expiration. | SET user:1:email "alice@example.com" EX 86400 |
GET key | Retrieves a key’s string value. | GET user:1:email |
SETNX key value | Sets key only if it does not already exist. | SETNX lock:resource "locked" EX 10 |
MSET key value [key value ...] | Sets multiple keys to multiple values. | MSET user:1:name "Alice" user:1:age "30" |
MGET key [key ...] | Retrieves multiple keys’ values. | MGET user:1:name user:1:age |
INCR key | Increments the integer value of a key by one. | INCR page_views:home |
DECR key | Decrements the integer value of a key by one. | DECR available_stock:item:123 |
INCRBY key increment | Increments the integer value of a key by the given amount. | INCRBY user:1:score 10 |
DECRBY key decrement | Decrements the integer value of a key by the given amount. | DECRBY user:1:balance 5 |
APPEND key value | Appends a value to a key. | APPEND log:20251230 "Event A" |
GETRANGE key start end | Gets a substring of the string value stored at a key. | GETRANGE mykey 0 4 (returns “hello” from “hello world”) |
2. Hashes
Maps string fields to string values, ideal for representing objects.
| Command | Description | Example |
|---|---|---|
HSET key field value [field value ...] | Sets multiple field-value pairs in a hash. | HSET user:2 name "Bob" email "bob@example.com" age 25 |
HGET key field | Retrieves the value associated with a field in a hash. | HGET user:2 name |
HGETALL key | Retrieves all fields and values in a hash. | HGETALL user:2 |
HMGET key field [field ...] | Retrieves the values associated with multiple fields. | HMGET user:2 name email |
HDEL key field [field ...] | Deletes one or more hash fields. | HDEL user:2 age |
HKEYS key | Returns all field names in a hash. | HKEYS user:2 |
HVALS key | Returns all values in a hash. | HVALS user:2 |
HEXISTS key field | Determines if a hash field exists. | HEXISTS user:2 email |
HINCRBY key field increment | Increments the integer value of a hash field by the given number. | HINCRBY product:1:stats views 1 |
3. Lists
Ordered collections of strings, implemented as linked lists. Good for queues, recent items.
| Command | Description | Example |
|---|---|---|
LPUSH key value [value ...] | Prepends one or more values to the head of a list. | LPUSH notifications "New message" "New follower" |
RPUSH key value [value ...] | Appends one or more values to the tail of a list. | RPUSH tasks "Task A" "Task B" |
LPOP key | Removes and returns the first element of a list. | LPOP notifications |
RPOP key | Removes and returns the last element of a list. | RPOP tasks |
BLPOP key [key ...] timeout | Blocking LPOP. Waits for elements if list is empty. | BLPOP queue:high queue:low 0 (0 for infinite wait) |
BRPOP key [key ...] timeout | Blocking RPOP. Waits for elements if list is empty. | BRPOP queue:process 5 |
LRANGE key start stop | Returns a range of elements from a list. | LRANGE notifications 0 -1 (all elements) |
LLEN key | Returns the length of a list. | LLEN notifications |
LINDEX key index | Returns the element at index in a list. | LINDEX notifications 0 |
LTRIM key start stop | Trims a list to the specified range. | LTRIM notifications 0 99 (keep only last 100) |
4. Sets
Unordered collections of unique strings. Good for tags, unique visitors.
| Command | Description | Example |
|---|---|---|
SADD key member [member ...] | Adds one or more members to a set. | SADD user:1:friends "Alice" "Bob" |
SMEMBERS key | Returns all members of the set. | SMEMBERS user:1:friends |
SISMEMBER key member | Checks if a member is part of a set. | SISMEMBER user:1:friends "Alice" |
SREM key member [member ...] | Removes one or more members from a set. | SREM user:1:friends "Bob" |
SCARD key | Returns the number of members in a set. | SCARD user:1:friends |
SUNION key [key ...] | Returns the union of multiple sets. | SUNION user:1:friends user:2:friends |
SINTER key [key ...] | Returns the intersection of multiple sets. | SINTER user:1:friends user:2:friends |
SDIFF key [key ...] | Returns the difference between multiple sets. | SDIFF user:1:friends user:2:friends |
SRANDMEMBER key [count] | Returns a random member from a set. | SRANDMEMBER user:1:friends 2 |
5. Sorted Sets
Collections of unique strings where each member is associated with a score. Members are ordered by score. Good for leaderboards, timed events.
| Command | Description | Example |
|---|---|---|
ZADD key score member [score member ...] | Adds or updates members with scores in a sorted set. | ZADD leaderboard 100 "playerA" 150 "playerB" |
ZRANGE key start stop [WITHSCORES] | Returns a range of members by index (ascending score). | ZRANGE leaderboard 0 -1 WITHSCORES |
ZREVRANGE key start stop [WITHSCORES] | Returns a range of members by index (descending score). | ZREVRANGE leaderboard 0 9 WITHSCORES (top 10) |
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] | Returns a range of members by score. | ZRANGEBYSCORE leaderboard 100 200 WITHSCORES |
ZSCORE key member | Returns the score of a member in a sorted set. | ZSCORE leaderboard "playerA" |
ZINCRBY key increment member | Increments the score of a member in a sorted set. | ZINCRBY leaderboard 5 "playerA" |
ZREM key member [member ...] | Removes one or more members from a sorted set. | ZREM leaderboard "playerC" |
ZCARD key | Returns the number of members in a sorted set. | ZCARD leaderboard |
ZCOUNT key min max | Counts members within a given score range. | ZCOUNT leaderboard 0 100 |
II. Key Management & Expiration
Managing keys and their lifecycles is crucial for efficient Redis usage.
1. Key Commands
| Command | Description | Example |
|---|---|---|
KEYS pattern | WARNING: Do not use in production on large datasets. Finds all keys matching a pattern. | KEYS user:* |
SCAN cursor [MATCH pattern] [COUNT count] | Iterates through keys in the database. Production-safe alternative to KEYS. | SCAN 0 MATCH user:* COUNT 100 |
EXISTS key [key ...] | Determines if one or more keys exist. | EXISTS mykey |
DEL key [key ...] | Deletes one or more keys. | DEL user:1:session user:2:session |
TYPE key | Returns the data type of the value stored at key. | TYPE mykey |
RENAME oldkey newkey | Renames a key. | RENAME oldname newname |
RENAMENX oldkey newkey | Renames a key only if the new key does not exist. | RENAMENX temp_data permanent_data |
EXPIRE key seconds | Sets a key’s time to live in seconds. | EXPIRE cache:item:123 300 |
PEXPIRE key milliseconds | Sets a key’s time to live in milliseconds. | PEXPIRE temp_lock 5000 |
TTL key | Returns the remaining time to live of a key in seconds. | TTL cache:item:123 |
PTTL key | Returns the remaining time to live of a key in milliseconds. | PTTL temp_lock |
PERSIST key | Removes the expiration from a key. | PERSIST important_data |
MOVE key db | Moves a key to another database. | MOVE mykey 1 |
2. Pattern Matching with SCAN
// Syntax for SCAN
SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]
Explanation: SCAN is an iterator that allows you to incrementally iterate over the keyspace. It returns a new cursor to use in the next call, along with a subset of keys matching the MATCH pattern (if provided) and optionally filtered by TYPE.
Use Case: Safely iterate over large numbers of keys in production without blocking the server, unlike KEYS.
# Initial call
SCAN 0 MATCH user:* COUNT 100
# Example output:
# 1) "128" (the new cursor)
# 2) 1) "user:101"
# 2) "user:205"
# ... (up to 100 keys)
# Next call using the cursor from the previous result
SCAN 128 MATCH user:* COUNT 100
III. Transactions & Scripting
Ensure atomicity and complex operations.
1. Transactions (MULTI/EXEC)
Redis transactions allow a group of commands to be executed as a single, atomic operation.
// Syntax for Transactions
MULTI
COMMAND1
COMMAND2
...
EXEC
Explanation:
MULTI: Starts a transaction. All subsequent commands are queued.EXEC: Executes all queued commands atomically.DISCARD: Flushes all queued commands and exits the transaction.WATCH key [key ...]: Monitors keys for changes. If any watched key is modified beforeEXEC, the transaction is aborted. Use Case: Transferring funds, updating multiple related counters atomically.
# Example: Atomic decrement and check
WATCH user:1:balance
GET user:1:balance
# In your application, check if balance is sufficient
# If yes:
MULTI
DECRBY user:1:balance 100
RPUSH transaction:log "User 1 paid 100"
EXEC
# If no, or WATCH detected a change, EXEC will return nil,
# and you can retry or inform the user.
2. Lua Scripting (EVAL)
Execute custom server-side scripts for complex, atomic operations.
// Syntax for EVAL
EVAL script numkeys key [key ...] arg [arg ...]
Explanation: EVAL executes a Lua script. numkeys specifies how many of the subsequent arguments are key names (accessed via KEYS table in Lua), and the rest are arguments (accessed via ARGV table).
Use Case: Implementing custom atomic commands, complex rate limiters, or fetching multiple related items with conditional logic.
-- Lua script for an atomic rate limiter
-- KEYS[1]: rate limit key (e.g., "rate_limit:user:123")
-- ARGV[1]: max requests allowed
-- ARGV[2]: time window in seconds
-- ARGV[3]: current timestamp
local key = KEYS[1]
local max_requests = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local current_time = tonumber(ARGV[3])
redis.call('ZREMRANGEBYSCORE', key, '-inf', current_time - window)
local current_requests = redis.call('ZCARD', key)
if current_requests < max_requests then
redis.call('ZADD', key, current_time, current_time .. math.random()) -- Add with unique member
redis.call('EXPIRE', key, window + 1) -- Set expiration slightly longer than window
return 1 -- Request allowed
else
return 0 -- Request denied
end
# Example usage of the rate limiter script (assuming script is loaded or passed directly)
# KEYS[1] = "rate_limit:user:123"
# ARGV[1] = 10 (max requests)
# ARGV[2] = 60 (window in seconds)
# ARGV[3] = <current_unix_timestamp>
EVAL "local key = KEYS[1] ... return 0 end" 1 rate_limit:user:123 10 60 1735689600
EVALSHA: For production, load scripts once with SCRIPT LOAD to get an SHA1 digest, then execute with EVALSHA to save bandwidth.
IV. Pub/Sub & Streams
Real-time messaging and event streaming.
1. Publish/Subscribe (Pub/Sub)
Simple messaging system where senders (publishers) send messages to channels, and receivers (subscribers) listen to channels.
| Command | Description | Example |
|---|---|---|
PUBLISH channel message | Publishes a message to a channel. | PUBLISH chat:room:general "Hello everyone!" |
SUBSCRIBE channel [channel ...] | Subscribes to one or more channels. | SUBSCRIBE chat:room:general news:updates |
PSUBSCRIBE pattern [pattern ...] | Subscribes to channels matching a pattern. | PSUBSCRIBE chat:* |
UNSUBSCRIBE [channel ...] | Unsubscribes from specified channels. | UNSUBSCRIBE chat:room:general |
PUNSUBSCRIBE [pattern ...] | Unsubscribes from specified patterns. | PUNSUBSCRIBE chat:* |
2. Streams (Redis 5.0+)
A more robust and persistent message queue, log, and event store.
| Command | Description | Example |
|---|---|---|
XADD key ID field value [field value ...] | Appends a new entry to a stream. ID can be * for auto-generation. | XADD sensor_data * temperature 25 humidity 60 |
XRANGE key start end [COUNT count] | Returns a range of entries from a stream. start/end can be 0-0 or - / +. | XRANGE sensor_data - + COUNT 10 |
XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...] | Reads entries from one or multiple streams. BLOCK makes it a blocking read. | XREAD COUNT 10 BLOCK 0 STREAMS sensor_data $ (read new entries) |
XGROUP CREATE key groupname ID | Creates a consumer group for a stream. ID is the last ID processed. $ for new entries. | XGROUP CREATE sensor_data mygroup $ |
XREADGROUP GROUP group consumer [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...] | Reads entries from a stream as part of a consumer group. ID is usually > for new entries. | XREADGROUP GROUP mygroup consumer1 STREAMS sensor_data > |
XACK key group ID [ID ...] | Acknowledges processing of stream entries by a consumer group. | XACK sensor_data mygroup 1735689600000-0 |
XDEL key ID [ID ...] | Deletes entries from a stream. | XDEL sensor_data 1735689600000-0 |
XTRIM key MAXLEN [~] count | Trims the stream to a maximum number of entries. | XTRIM sensor_data MAXLEN ~ 1000 |
V. Server Management & Persistence
Monitoring, configuration, and data durability.
1. Server Information & Configuration
| Command | Description | Example |
|---|---|---|
INFO [section] | Provides information about the Redis server (e.g., memory, clients, replication). | INFO memory |
CLIENT LIST | Returns information about all connected clients. | CLIENT LIST |
CONFIG GET parameter | Gets the value of a configuration parameter. | CONFIG GET maxmemory |
CONFIG SET parameter value | Sets a configuration parameter to a new value. | CONFIG SET maxmemory 2gb |
DBSIZE | Returns the number of keys in the current database. | DBSIZE |
MONITOR | Debugging command that streams every command processed by the Redis server. | MONITOR |
| `SHUTDOWN [NOSAVE | SAVE]` | Saves the dataset and then quits. |
2. Persistence
Redis offers two main persistence options: RDB (snapshotting) and AOF (append-only file).
- RDB (Redis Database Backup): Point-in-time snapshots of your dataset.
SAVE: Synchronously saves the dataset to disk. Blocks the server.BGSAVE: Asynchronously saves the dataset to disk in the background. Non-blocking.
- AOF (Append-Only File): Logs every write operation received by the server.
BGREWRITEAOF: Rewrites the AOF file in the background to minimize its size.
# Manually trigger a background save
BGSAVE
# Manually trigger AOF rewrite
BGREWRITEAOF
3. Security (ACL)
Redis 6.0+ introduced Access Control Lists (ACLs) for fine-grained permissions.
// Syntax for ACL
ACL SETUSER username [password] [rules ...]
Explanation: ACLs allow you to define users with specific permissions for commands, keys, and Pub/Sub channels. Use Case: Restricting certain applications or microservices to only access specific keys or commands.
# Create a user 'app_cache' with password 'cache_pass'
# Can only use GET/SET/DEL commands
# Can only access keys starting with 'cache:'
ACL SETUSER app_cache on >cache_pass +@read +@write ~cache:*
VI. Common Patterns
Practical use cases and best practices.
1. Caching
// Basic Caching
SET user:profile:123 '{"name":"Alice", "email":"alice@example.com"}' EX 3600
GET user:profile:123
// Cache Invalidation (explicit)
DEL user:profile:123
// Cache Invalidation (on update)
// When user profile is updated in DB, also update/delete in Redis
SET user:profile:123 '{"name":"Alice Updated", "email":"alice_new@example.com"}' EX 3600
Best Practice: Use EX or PX for expiration. Implement a cache-aside pattern.
2. Rate Limiting
-- Lua script for a sliding window rate limiter (as shown above)
-- KEYS[1]: rate limit key
-- ARGV[1]: max requests
-- ARGV[2]: time window (seconds)
-- ARGV[3]: current timestamp (milliseconds for better precision)
local key = KEYS[1]
local max_requests = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local current_time = tonumber(ARGV[3])
-- Remove old requests
redis.call('ZREMRANGEBYSCORE', key, '-inf', current_time - (window * 1000))
-- Count current requests
local current_requests = redis.call('ZCARD', key)
if current_requests < max_requests then
-- Add current request
redis.call('ZADD', key, current_time, current_time .. '-' .. math.random(0, 100000))
-- Set expiration for the key to ensure it's cleaned up
redis.call('PEXPIRE', key, window * 1000 + 1000) -- +1 second buffer
return 1 -- Allowed
else
return 0 -- Denied
end
# Example: Allow 10 requests per 60 seconds for user:123
# Assuming current_ms is current Unix timestamp in milliseconds
EVALSHA <sha1_of_script> 1 rate_limit:user:123 10 60 <current_ms>
Best Practice: Use Lua scripts for atomic rate limiting logic.
3. Distributed Locks
// Acquire Lock
SET resource:lock:<id> <owner_id> NX PX <milliseconds>
// Returns OK if acquired, nil if not.
// Release Lock (requires checking owner_id for safety, ideally with Lua)
// Lua script for safe release:
-- KEYS[1]: lock key
-- ARGV[1]: expected owner_id
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
Best Practice: Use SET key value NX PX milliseconds for acquiring. Releasing should be done atomically (e.g., with Lua) to prevent one client from releasing another’s lock. Implement retry logic with exponential backoff.
4. Message Queues (Simple)
// Producer
LPUSH tasks "task_id_1" "task_id_2"
// Consumer (blocking)
BRPOP tasks 0 // Blocks indefinitely until a task is available
Best Practice: For simple task queues, LPUSH/BRPOP works well. For more robust, persistent, and consumer-group-aware queues, use Redis Streams.
5. Leaderboards/Ranking
// Add/Update player scores
ZADD game:leaderboard 1000 "player:Alice" 1200 "player:Bob" 950 "player:Charlie"
// Get top 10 players
ZREVRANGE game:leaderboard 0 9 WITHSCORES
// Get player's rank (0-indexed, ascending)
ZRANK game:leaderboard "player:Alice"
// Get player's score
ZSCORE game:leaderboard "player:Alice"
Best Practice: Sorted Sets are purpose-built for leaderboards.
6. Session Management
// Store user session data
HSET session:user:123 id 123 username "Alice" login_time <timestamp>
EXPIRE session:user:123 1800 // Session expires in 30 minutes
// Retrieve session data
HGETALL session:user:123
// Check if session exists
EXISTS session:user:123
Best Practice: Use Hashes for structured session data and EXPIRE for automatic cleanup.
VII. Tips & Tricks
1. KEYS vs SCAN
KEYS: Use only in development or on very small, non-production datasets. It’s a blocking command and can severely impact performance on large databases.SCAN: Always useSCANin production for iterating over keys. It’s non-blocking and provides a cursor for incremental iteration.
2. Memory Usage
- Use
INFO memoryto get an overview of memory consumption. - Use
MEMORY USAGE keyto estimate the memory used by a specific key. - Consider using Redis data structures efficiently (e.g., small hashes/lists can be optimized for memory).
- Set
maxmemoryand amaxmemory-policyinredis.confto prevent Redis from running out of memory.
3. Atomic Operations
- Redis commands are atomic by default.
- For multi-command atomicity, use
MULTI/EXECtransactions or Lua scripting. Lua scripts are generally preferred for complex logic as they are executed entirely on the server.
4. Connection Pooling
- Always use connection pooling in your application to manage connections efficiently and avoid overhead of establishing new connections for every command.
5. Pipelining
- Send multiple commands to Redis in a single round trip to reduce network latency, especially for bulk operations. Most Redis client libraries support pipelining.
6. Data Modeling
- Think about your access patterns. Redis is very flexible, but modeling data to fit its strengths (e.g., using hashes for objects, sorted sets for rankings) leads to better performance.
- Use appropriate key naming conventions (e.g.,
object_type:id:field).
7. Troubleshooting
NOAUTH Authentication required: This error means your Redis server is configured with a password, but your client isn’t providing it. Checkredis.confforrequirepass. Use theAUTH passwordcommand.- Connection issues: Check Redis server status (
redis-cli PING), firewall rules, and ensure the client is connecting to the correct host and port. - High CPU/Memory usage: Use
INFOcommands to diagnose.INFO CPUshows CPU usage,INFO memoryshows memory.MONITORcan reveal high-frequency commands.redis-cli --latencycan help detect performance issues. - Data loss: Ensure persistence (RDB/AOF) is configured correctly for your durability requirements.
VIII. Version Information
This cheatsheet is based on Redis 7.4, which is anticipated to be the latest stable major version by December 30, 2025, building upon the features of Redis 7.2 (released mid-2023).
- Key Features (Redis 7.x series):
- ACLv2: Enhanced Access Control Lists for more granular permissions.
- Functions: Server-side functions written in Lua, offering a more structured way to extend Redis logic than raw
EVALscripts. - Sharded Pub/Sub: Improves scalability for Pub/Sub by allowing messages to be sharded across multiple nodes in a cluster.
- Client-side Caching (Tracking): Optimizations for client-side caching to reduce network round-trips.
- Command improvements: Various new arguments and options for existing commands, and new commands for specific use cases.
- Performance enhancements: Continuous improvements in core performance and memory efficiency.
Redis maintains strong backward compatibility, so commands from older versions (e.g., 6.x) generally work as expected, but leveraging newer features like ACLs and Functions requires compatible server and client versions.
IX. References
Transparency Note
This cheatsheet was generated by an AI expert based on a comprehensive understanding of Redis, its official documentation, common usage patterns, and best practices. Information is current as of December 30, 2025, with reasonable projections for Redis versioning and feature sets. While every effort has been made to ensure accuracy and practicality, always refer to the official Redis documentation for the most definitive and up-to-date information.