Redis Cheat Sheet
Redis CLI and data-type commands covering strings, lists, hashes, sets, sorted sets, key management, pub/sub, and persistence.
Redis is an in-memory data store with five core data types and a wire protocol simple enough to use from a one-liner. Avoid KEYS in production — it blocks the server — and prefer SCAN whenever you need to walk a keyspace.
Connecting and basic interaction
The CLI accepts a URI, individual flags, or no flags at all when a local server with no auth is running. Pass -a for password only on trusted hosts, since the password is visible in ps output.
# Local default
redis-cli
# Remote with auth
redis-cli -h cache.example.com -p 6379 -a 's3cr3t'
# URI form (supports TLS via rediss://)
redis-cli -u redis://default:s3cr3t@cache.example.com:6379/0
# Switch to logical database
redis-cli -n 2
| Command | Purpose |
|---|---|
PING | Returns PONG if the server is reachable |
SELECT <db> | Pick a logical database (0–15 by default) |
INFO server | Print version, uptime, and config |
INFO memory | Memory usage and fragmentation |
CLIENT LIST | Active client connections |
CONFIG GET maxmemory | Read a runtime config value |
Strings — the workhorse type
Strings hold any binary data up to 512 MB: serialized JSON, integers, JWTs, HTML fragments. Use SET with EX (seconds) or PX (milliseconds) to make a key self-expiring.
SET user:42:name "Ada Lovelace"
GET user:42:name
# Atomic increment for counters
INCR page:views:home
INCRBY api:requests 5
# Set with TTL + only-if-absent in one call (atomic)
SET session:abc123 "payload" EX 900 NX
TTL session:abc123
| Command | Effect |
|---|---|
SET key value | Set the value |
SET key value EX 60 | Set with 60-second expiry |
SET key value NX | Only set if not exists |
GET key | Read value (or nil) |
INCR / DECR | Atomic integer change |
APPEND | Concatenate to existing string |
STRLEN | Length in bytes |
MSET / MGET | Set/get many keys in one round-trip |
Lists — head/tail queues
Lists are linked lists, not arrays. LPUSH/RPUSH insert at the head/tail, LPOP/RPOP remove, and LRANGE is the universal read tool. Use them for queues, recent-activity feeds, and capped logs.
LPUSH jobs:email "send:42" "send:41"
RPUSH jobs:email "send:43"
LPOP jobs:email
RPOP jobs:email
# Read the last 10 (or all)
LRANGE jobs:email 0 9
LRANGE jobs:email 0 -1
# Blocking pop — waits up to N seconds
BRPOP jobs:email 5
# Trim to keep only the latest 1000 items
LTRIM events:audit 0 999
| Command | Direction | Behavior |
|---|---|---|
LPUSH / LPOP | Head | Insert/remove on the left |
RPUSH / RPOP | Tail | Insert/remove on the right |
LLEN | — | Length |
LINDEX key i | — | Element at index i |
LRANGE key s e | — | Slice from s to e |
LREM key count value | — | Remove matching elements |
Hashes — record-per-key
A hash maps field-value pairs under one key. Use hashes when you want to update one field of an object without rewriting the whole record.
HSET user:42 name "Ada" email "ada@example.com" age 36
HGET user:42 name
HGETALL user:42
HMGET user:42 name email
HDEL user:42 age
HEXISTS user:42 email
HINCRBY user:42 age 1
HKEYS user:42
HVALS user:42
| Command | Effect |
|---|---|
HSET key f v [f v ...] | Set one or more fields |
HGET key f | Read one field |
HGETALL key | Read all fields |
HDEL key f | Remove one field |
HINCRBY key f n | Atomic integer increment |
HSETNX key f v | Set only if field absent |
Sets and Sorted Sets
Sets are unordered collections of unique members. Sorted sets add a score that drives ordering — perfect for leaderboards, rate-limit windows, and time-indexed feeds.
# Sets
SADD tags:post:1 "redis" "cache" "db"
SMEMBERS tags:post:1
SISMEMBER tags:post:1 "redis"
SCARD tags:post:1
SINTER tags:post:1 tags:post:2
SUNION tags:post:1 tags:post:2
# Sorted sets
ZADD leaderboard 100 "ada" 95 "grace" 110 "linus"
ZRANGE leaderboard 0 -1 WITHSCORES
ZREVRANGE leaderboard 0 9 WITHSCORES
ZRANK leaderboard "ada"
ZSCORE leaderboard "ada"
| Set type | When to use |
|---|---|
SADD / SMEMBERS | Unique tags, deduplication, intersection logic |
ZADD / ZRANGE | Leaderboards, time-windowed queues (score = timestamp) |
ZREVRANGEBYSCORE | Most-recent-N in O(log N + M) |
ZINCRBY | Atomic score bump |
Key management — never use KEYS on a hot server
KEYS pattern walks the entire keyspace and blocks the server for the duration. SCAN is incremental, cursor-based, and safe to call from production.
# Avoid in production — O(N), blocking
KEYS user:* # ❌
# Use instead — cursor-based, non-blocking
SCAN 0 MATCH user:* COUNT 100
# Returns: 1) "cursor" 2) 1) "user:1" 2) "user:2"
DEL user:1 user:2
EXISTS user:1
TYPE user:1
# Expiry
EXPIRE user:1 60
PEXPIRE user:1 60000
TTL user:1
PERSIST user:1
# Atomic rename (deletes target)
RENAME user:1 user:old:1
| Command | Effect |
|---|---|
SCAN cursor MATCH pattern COUNT n | Iterate the keyspace |
DEL k [k ...] | Remove one or many keys |
EXISTS k | 1 if present, 0 otherwise |
EXPIRE k seconds | Set TTL |
TTL k | Remaining seconds; -2 missing, -1 no TTL |
PERSIST k | Remove TTL |
TYPE k | String, list, hash, set, zset, stream, none |
Pub/Sub and Streams
Pub/Sub is fire-and-forget — subscribers must be connected at publish time, and messages are not stored. For at-least-once delivery, use Streams instead.
# Publisher
PUBLISH news:tech "Redis 8 released"
# Subscriber (blocks; only receives messages sent while connected)
SUBSCRIBE news:tech
PSUBSCRIBE news:*
# Streams — durable message log
XADD events:click * user 42 page "/pricing"
XLEN events:click
XRANGE events:click - +
XREAD COUNT 10 STREAMS events:click 0
| Mechanism | Use when |
|---|---|
PUBLISH / SUBSCRIBE | Live notifications, presence, low-stakes fan-out |
XADD / XREAD / XACK | Durable queue, consumer groups, replayable history |
Persistence — RDB snapshots and AOF
Redis persists to disk so it can recover after a restart. Pick a strategy based on how much data loss you can tolerate; most production setups run with both AOF and RDB enabled.
# Force a snapshot now
BGSAVE
# Inspect AOF status
INFO persistence
CONFIG GET appendonly
CONFIG GET appendfsync
| Mode | What it does | Trade-off |
|---|---|---|
| RDB (snapshotting) | Periodic point-in-time dump | Faster restart, can lose seconds to minutes |
| AOF (append-only file) | Logs every write operation | Smaller data loss, larger disk usage |
appendfsync everysec | AOF flush once per second | Good default balance |
appendfsync always | AOF flush per write | Slowest, most durable |