Redis
Printed from:
Redis Cheatsheet: Mastering In-Memory Data Structures and Caching
Updated for Redis 7.x / 8.x. Redis is a high-performance, in-memory data store widely used for caching, message brokering, real-time analytics, and as a primary database. Note: As of Redis 7.4+, the project is dual-licensed under RSALv2 and SSPLv1; Redis 8 added AGPLv3 as a third option. The Linux Foundation maintains a BSD-licensed fork called Valkey, which remains command-compatible with Redis 7.2.
1. Connection and Basic Commands
Connecting to Redis
123456789101112# Connect to local Redis server
redis-cli
# Connect to remote Redis server
redis-cli -h hostname -p port -a password
# Connect over TLS (recommended for production)
redis-cli -h hostname -p 6379 --tls --cacert ca.crt
# Use a connection URI
redis-cli -u redis://user:password@hostname:6379/0
Basic Server Commands
12345678# Check server status
PING # Returns PONG if Redis is running
INFO # Detailed server information
INFO memory # Section-scoped info (memory, clients, stats, etc.)
DBSIZE # Number of keys in the current database
FLUSHDB ASYNC # Clear current DB without blocking
FLUSHALL ASYNC # Clear all databases without blocking
2. Data Types and Structures
Redis supports multiple data structures, each optimized for specific use cases:
- Strings: Simple key-value storage (binary-safe, up to 512 MB)
- Lists: Ordered collection of strings (linked list / quicklist)
- Sets: Unordered collection of unique strings
- Hashes: Field-value mappings
- Sorted Sets: Sets with associated scores (skiplist + hash)
- Bitmaps: Bit-level operations on strings
- Bitfields: Multi-bit integer arrays
- HyperLogLog: Probabilistic cardinality estimation
- Streams: Append-only log with consumer groups
- Geospatial: Latitude/longitude indexing on sorted sets
Available via Redis Stack / modules:
- JSON (RedisJSON), Search & Query (RediSearch), Time Series, Probabilistic (Bloom/Cuckoo/Top-K/t-digest), and Vector Search for AI workloads.
3. Key Operations
123456789101112131415# Basic Key Management
SET key value # Set a key with a value
GET key # Retrieve a key's value
DEL key # Delete a key (blocking)
UNLINK key # Delete a key asynchronously (non-blocking, preferred for large values)
EXISTS key # Check if key exists
EXPIRE key seconds # Set expiration (supports NX|XX|GT|LT options)
PEXPIRE key ms # Expire in milliseconds
EXPIREAT key timestamp # Expire at Unix time
PERSIST key # Remove TTL
TTL key # Time-to-live in seconds (-1 no TTL, -2 missing)
TYPE key # Inspect key's data type
COPY src dst [DB n] [REPLACE] # Copy a key (Redis 6.2+)
SCAN cursor [MATCH pattern] [COUNT n] [TYPE type] # Iterate keys safely (preferred over KEYS)
⚠️ Avoid
KEYS patternin production — it blocks the server. UseSCANfor any non-trivial key space.
4. String Operations
1234567891011121314151617# String Commands
SET user:1000 "John Doe" # Set a string value
SET key value EX 60 # Set with expiration in seconds
SET key value PX 5000 # Set with expiration in milliseconds
SET key value NX # Set only if key does not exist (replaces SETNX)
SET key value XX # Set only if key already exists
SET key value KEEPTTL # Preserve existing TTL on overwrite
SET key value GET # Set and return previous value (replaces GETSET)
GETEX key EX 60 # Get and update expiration
GETDEL key # Get value and delete key
MSET key1 v1 key2 v2 # Set multiple keys atomically
MGET key1 key2 # Get multiple keys
INCR counter / DECR counter # Increment/decrement integer
INCRBY counter 5 / INCRBYFLOAT key 1.5 # Numeric increments
APPEND key value # Append to string
STRLEN key # String length in bytes
Note:
SETNX,SETEX,PSETEX, andGETSETstill work but are considered legacy — prefer the unifiedSETwith options.
5. List Operations
12345678910111213# List Commands
LPUSH mylist value # Push to head
RPUSH mylist value # Push to tail
LPOP mylist [count] # Pop from head (optional count, 6.2+)
RPOP mylist [count] # Pop from tail
LMOVE src dst LEFT|RIGHT LEFT|RIGHT # Atomic move between lists (replaces RPOPLPUSH)
LRANGE mylist 0 -1 # All elements
LLEN mylist # List length
LINDEX mylist 2 # Element at index
LPOS mylist value # Find index of value (6.0.6+)
LMPOP 2 list1 list2 LEFT COUNT 3 # Pop from first non-empty list (7.0+)
BLPOP / BRPOP / BLMPOP # Blocking variants
6. Set Operations
12345678910111213# Set Commands
SADD myset member1 member2 # Add members
SMEMBERS myset # All members (use SSCAN for large sets)
SINTER set1 set2 # Intersection
SINTERCARD 2 set1 set2 LIMIT 100 # Cardinality of intersection (7.0+)
SDIFF set1 set2 # Difference
SUNION set1 set2 # Union
SISMEMBER myset member # Membership check
SMISMEMBER myset m1 m2 # Multi-member check (6.2+)
SCARD myset # Member count
SRANDMEMBER myset [count] # Random sampling
SPOP myset [count] # Pop random member(s)
7. Hash Operations
123456789101112# Hash Commands
HSET user:1000 name "John" age 30 # Set one or many fields (preferred)
HGET user:1000 name # Get a field
HMGET user:1000 name age # Get multiple fields
HGETALL user:1000 # All fields and values
HINCRBY user:1000 age 1 # Increment integer field
HINCRBYFLOAT user:1000 balance 1.5 # Increment float field
HDEL user:1000 name # Delete field(s)
HEXISTS user:1000 email # Field existence
HRANDFIELD user:1000 2 WITHVALUES # Random field sampling (6.2+)
HEXPIRE user:1000 60 FIELDS 1 name # Per-field TTL (7.4+)
HMSETis deprecated since Redis 4.0 —HSETaccepts multiple field/value pairs.
8. Sorted Set Operations
1234567891011# Sorted Set Commands
ZADD leaderboard 100 user1 200 user2 # Add with score (supports NX|XX|GT|LT|CH|INCR)
ZRANGE leaderboard 0 -1 WITHSCORES # List all with scores
ZRANGE leaderboard 0 9 REV # Top 10 (replaces ZREVRANGE)
ZRANGEBYSCORE / ZRANGEBYLEX # Range by score or lexicographic order
ZRANGESTORE dst src 0 9 # Store range result (6.2+)
ZRANK leaderboard user1 [WITHSCORE] # Rank (7.2+ supports WITHSCORE)
ZSCORE leaderboard user1 # Member score
ZINCRBY leaderboard 10 user1 # Increment score
ZMPOP / BZMPOP # Pop from multiple sorted sets (7.0+)
9. Pub/Sub Messaging
1234567891011# Classic Pub/Sub
SUBSCRIBE channel
PSUBSCRIBE news.* # Pattern subscription
PUBLISH channel message
UNSUBSCRIBE channel
# Sharded Pub/Sub (Redis 7.0+, cluster-aware)
SSUBSCRIBE channel
SPUBLISH channel message
SUNSUBSCRIBE channel
For durable, replayable messaging with consumer groups, prefer Streams (
XADD,XREAD,XREADGROUP,XACK).
10. Transactions and Pipelining
1234567891011121314# Optimistic locking + transaction
WATCH key1
MULTI
SET key1 value1
SET key2 value2
EXEC # Aborts if WATCHed keys changed
DISCARD # Cancel a queued transaction
# Pipelining (client-side example, Python)
pipe = r.pipeline(transaction=False)
pipe.set('key1', 'value1')
pipe.get('key1')
results = pipe.execute()
11. Scripting and Functions
1234567-- EVAL: ad-hoc Lua script
EVAL "redis.call('SET', KEYS[1], ARGV[1]); return redis.call('GET', KEYS[1])" 1 counter 10
-- EVALSHA: run a cached script by SHA1
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
EVALSHA <sha> 1 counter
12345# Functions (Redis 7.0+) — persistent, replicated server-side libraries
FUNCTION LOAD "#!lua name=mylib\nredis.register_function('myfunc', function(keys, args) return redis.call('GET', keys[1]) end)"
FCALL myfunc 1 counter
FUNCTION LIST
Functions are the modern replacement for managing reusable Lua scripts — they are persisted, replicated, and survive restarts.
12. Persistence and Backup
12345678910111213# RDB (point-in-time snapshots)
SAVE # Synchronous snapshot (blocks; avoid in production)
BGSAVE # Background snapshot
LASTSAVE # Unix time of last successful save
# AOF (append-only file)
CONFIG SET appendonly yes
CONFIG SET appendfsync everysec # Recommended balance of speed and durability
BGREWRITEAOF # Compact the AOF file
# Hybrid (recommended): RDB + AOF, with AOF using RDB preamble
CONFIG SET aof-use-rdb-preamble yes
13. Security and ACLs
12345678910111213# Access Control Lists (Redis 6+)
ACL LIST # Show all users
ACL WHOAMI # Current user
ACL SETUSER alice on >SuperSecret ~cache:* +@read +@write -@dangerous
ACL GETUSER alice
ACL DELUSER alice
# Require TLS (configured in redis.conf)
# tls-port 6379
# tls-cert-file /etc/redis/redis.crt
# tls-key-file /etc/redis/redis.key
# tls-ca-cert-file /etc/redis/ca.crt
Use ACL users instead of the legacy
requirepasswhenever possible, and protect the network with TLS + firewalling. Never expose Redis to the public internet without authentication.
14. Performance Optimization
123456789101112131415# Memory Management
CONFIG SET maxmemory 2gb
CONFIG SET maxmemory-policy allkeys-lru # or allkeys-lfu, volatile-ttl, noeviction, etc.
MEMORY USAGE key # Bytes used by a key
MEMORY STATS # Detailed memory breakdown
OBJECT ENCODING key # Inspect internal encoding
# Slow query investigation
SLOWLOG GET 10
LATENCY DOCTOR
CLIENT LIST / CLIENT KILL
# Client-side caching (RESP3, Redis 6+)
CLIENT TRACKING ON
Performance tips:
- Pick the right data structure; avoid mega-keys (large lists/sets/hashes).
- Use
SCAN/HSCAN/SSCAN/ZSCANinstead ofKEYS/HGETALLon huge collections. - Batch with pipelining or
MULTI/EXEC; prefer non-blocking variants (UNLINK,FLUSHDB ASYNC). - Keep value sizes small; compress JSON or use Hash field packing for small objects.
15. Common Caching Patterns
123456789101112131415161718192021# Cache-aside pattern (Python, redis-py)
def get_user(user_id):
key = f'user:{user_id}'
user = redis_client.get(key)
if user is None:
user = database.get_user(user_id)
redis_client.set(key, user, ex=3600) # SET with EX option
return user
# Sliding-window rate limiting
def is_allowed(user_id, limit=10, window=60):
key = f'rate_limit:{user_id}'
pipe = redis_client.pipeline()
pipe.incr(key)
pipe.expire(key, window, nx=True) # Set TTL only on first hit (7.0+)
current, _ = pipe.execute()
return current <= limit
# Distributed lock — use the Redlock algorithm or a vetted library
# (e.g. redis-py's redis.lock.Lock, redsync for Go, Redisson for Java)
16. Clustering and High Availability
12345678910# Redis Sentinel (HA with automatic failover for primary/replica setups)
sentinel monitor mymaster 127.0.0.1 6379 2
# Redis Cluster (sharded, no central proxy)
redis-cli --cluster create node1:6379 node2:6379 node3:6379 \
node4:6379 node5:6379 node6:6379 --cluster-replicas 1
CLUSTER INFO
CLUSTER NODES
CLUSTER SHARDS # Cluster topology (7.0+)
In Cluster mode, use hash tags (
{tag}) in keys to keep related keys on the same slot for multi-key operations.
Best Practices
- Choose the right data structure for the access pattern.
- Always set TTLs on cache keys; pair them with a sensible eviction policy.
- Use
SCANrather thanKEYS, andUNLINKrather thanDELfor large values. - Pipeline aggressively; use Lua scripts or Functions for atomic multi-step logic.
- Enable AOF (with
everysec) plus RDB for resilient durability. - Lock down access with ACLs, TLS, and network isolation.
- Monitor
INFO,SLOWLOG,LATENCY, and memory fragmentation continuously. - Test failover behavior (Sentinel/Cluster) before relying on it in production.
Recommended Tools
redis-cliandredis-benchmark- RedisInsight (official GUI, replacement for the discontinued Redis Desktop Manager)
- Prometheus
redis_exporter+ Grafana dashboards - redis-py (Python), ioredis / node-redis (Node.js), Lettuce / Jedis (Java), go-redis (Go), StackExchange.Redis (.NET)
- Valkey (BSD-licensed, Redis-compatible fork) and KeyDB as alternative-license forks
Learning Resources
- Official Redis Documentation — redis.io/docs
- Redis University — university.redis.io
- Redis in Action and Redis Stack Essentials
- Redis Engineering Blog
- Valkey Project Documentation — valkey.io
Continue Learning
Discover more cheatsheets to boost your productivity