Redis Cheat Sheet
Redis commands for strings, lists, sets, hashes, sorted sets, pub/sub, and expiration, covering the core in-memory data structure operations.
Strings & Expiry
Basic key/value operations and TTLs.
redis-cliSET key "value"GET keySETEX key 60 "value" # set with 60s expiryINCR counterEXPIRE key 30 # set TTL in secondsTTL key # seconds remaining, -1 = no expiryDEL key
Data Structures
Lists, sets, hashes, and sorted sets.
LPUSH mylist "a" "b" # listLRANGE mylist 0 -1SADD myset "a" "b" # setSMEMBERS mysetHSET user:1 name "Alice" age 30 # hashHGETALL user:1ZADD leaderboard 100 "alice" # sorted setZRANGE leaderboard 0 -1 WITHSCORES
Common Commands
Frequently used commands beyond basic gets/sets.
- KEYS pattern- finds keys matching a pattern; blocks the server, avoid in production
- SCAN cursor- cursor-based, non-blocking key iteration; production-safe alternative to KEYS
- EXPIRE / PERSIST- set or remove a key's time-to-live
- MULTI / EXEC- queues commands and executes them atomically as a transaction
- PUBLISH / SUBSCRIBE- publish/subscribe messaging between clients
- FLUSHDB- deletes every key in the currently selected database
Pub/Sub & Pipelines
Messaging and batching commands from a client.
# Pub/Sub (redis-cli)# SUBSCRIBE channel1# PUBLISH channel1 "hello"# Pipeline example (redis-py)import redisr = redis.Redis()pipe = r.pipeline()pipe.set('a', 1)pipe.incr('a')results = pipe.execute() # batches commands in one round trip
Lua Scripting (EVAL)
Running atomic multi-command logic server-side.
-- increment.lua: atomically increment only if below a capEVAL "local v = tonumber(redis.call('GET', KEYS[1]) or 0)\nif v < tonumber(ARGV[1]) then\n return redis.call('INCR', KEYS[1])\nend\nreturn v" 1 requests:count 100# Cache a script server-side and invoke it by SHA (avoids re-sending source)SCRIPT LOAD "return redis.call('GET', KEYS[1])"EVALSHA <sha1> 1 mykey
Streams (XADD / XREAD / Consumer Groups)
Append-only log data structure for event pipelines and message queues.
XADD orders '*' order_id 1001 status "placed"XLEN ordersXRANGE orders - +XGROUP CREATE orders workers '$' MKSTREAMXREADGROUP GROUP workers consumer1 COUNT 10 STREAMS orders '>'XACK orders workers <entry-id>XPENDING orders workers # inspect unacknowledged messages
Optimistic Locking with WATCH
Check-and-set semantics across multiple clients without a distributed lock.
WATCH balance:1val = GET balance:1MULTISET balance:1 (val - 100)EXEC # returns nil if balance:1 changed since WATCH, retry the whole flowUNWATCH # clear watches manually if aborting early
Bitmaps & HyperLogLog
Space-efficient counting and flag tracking at scale.
SETBIT active_users:2026-07-21 12345 1 # mark user 12345 active todayBITCOUNT active_users:2026-07-21 # count active usersBITOP AND result active_users:day1 active_users:day2 # users active both daysPFADD unique_visitors user123 user456PFADD unique_visitors user123 # duplicate, ignoredPFCOUNT unique_visitors # ~cardinality estimate, ~0.81% error, fixed memory
Persistence & Scaling Concepts
How Redis survives restarts and scales beyond a single node.
- RDB snapshotting- point-in-time binary dump on a schedule (SAVE/BGSAVE); fast restarts, can lose recent writes
- AOF (Append Only File)- logs every write command; replay on restart for near-zero data loss with appendfsync everysec
- Replication (REPLICAOF)- async master-replica copying for read scaling and failover candidates
- Redis Sentinel- monitors masters/replicas and automates failover for non-clustered deployments
- Redis Cluster- shards keys across nodes via 16384 hash slots, each key mapped by CRC16(key) mod 16384
- maxmemory-policy- eviction strategy (allkeys-lru, volatile-ttl, noeviction, etc.) applied once maxmemory is hit
- Hash tags- {user1000} in a key confines its slot so multi-key ops work correctly on a cluster
Never run the KEYS command against a production instance — it scans the entire keyspace and blocks the single-threaded event loop; use SCAN instead for safe, incremental iteration.