Redis Cheat Sheet

Redis CLI and data-type commands covering strings, lists, hashes, sets, sorted sets, key management, pub/sub, and persistence.

Reference
redis
nosql
cache

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.

bash
# 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
Table
CommandPurpose
PINGReturns PONG if the server is reachable
SELECT <db>Pick a logical database (0–15 by default)
INFO serverPrint version, uptime, and config
INFO memoryMemory usage and fragmentation
CLIENT LISTActive client connections
CONFIG GET maxmemoryRead 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.

bash
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
Table
CommandEffect
SET key valueSet the value
SET key value EX 60Set with 60-second expiry
SET key value NXOnly set if not exists
GET keyRead value (or nil)
INCR / DECRAtomic integer change
APPENDConcatenate to existing string
STRLENLength in bytes
MSET / MGETSet/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.

bash
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
Table
CommandDirectionBehavior
LPUSH / LPOPHeadInsert/remove on the left
RPUSH / RPOPTailInsert/remove on the right
LLENLength
LINDEX key iElement at index i
LRANGE key s eSlice from s to e
LREM key count valueRemove 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.

bash
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
Table
CommandEffect
HSET key f v [f v ...]Set one or more fields
HGET key fRead one field
HGETALL keyRead all fields
HDEL key fRemove one field
HINCRBY key f nAtomic integer increment
HSETNX key f vSet 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.

bash
# 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"
Table
Set typeWhen to use
SADD / SMEMBERSUnique tags, deduplication, intersection logic
ZADD / ZRANGELeaderboards, time-windowed queues (score = timestamp)
ZREVRANGEBYSCOREMost-recent-N in O(log N + M)
ZINCRBYAtomic 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.

bash
# 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
Table
CommandEffect
SCAN cursor MATCH pattern COUNT nIterate the keyspace
DEL k [k ...]Remove one or many keys
EXISTS k1 if present, 0 otherwise
EXPIRE k secondsSet TTL
TTL kRemaining seconds; -2 missing, -1 no TTL
PERSIST kRemove TTL
TYPE kString, 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.

bash
# 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
Table
MechanismUse when
PUBLISH / SUBSCRIBELive notifications, presence, low-stakes fan-out
XADD / XREAD / XACKDurable 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.

bash
# Force a snapshot now
BGSAVE

# Inspect AOF status
INFO persistence
CONFIG GET appendonly
CONFIG GET appendfsync
Table
ModeWhat it doesTrade-off
RDB (snapshotting)Periodic point-in-time dumpFaster restart, can lose seconds to minutes
AOF (append-only file)Logs every write operationSmaller data loss, larger disk usage
appendfsync everysecAOF flush once per secondGood default balance
appendfsync alwaysAOF flush per writeSlowest, most durable

References