Cheat Sheet

Redis Commands

Commands grouped by data type with the complexity from the official reference and the gotcha that bites in production. Read the complexity column first: it tells you what is safe on a big key.

11
Groups
Redis docs
Complexity source
redis-cli
Options checked
Index ยท Spring ยท SQL ยท Git ยท Docker/kubectl ยท Kafka/Rabbit CLI ยท Redis ยท Big-O
01
Chapter 1 - How to read this sheet

Complexity Is the Point

Redis runs commands on one thread, so one slow command delays every client. The Complexity column is copied from the command reference (redis.io/docs/latest/commands, data file commands.json in the redis/docs repository, checked 2026-10-31). N is almost always the size of the key or the number of items returned. Anything O(N) on a large key is a latency risk.

ComplexityMeaning for you
O(1)Safe at any size
O(log N)Safe; sorted sets and similar
O(N) with N = items returnedSafe if you page (COUNT, LIMIT); dangerous when you ask for everything
O(N) with N = size of the key or keyspaceAvoid on big data in production (KEYS, SMEMBERS, HGETALL, LRANGE 0 -1)
02
Chapter 2 - Strings and generic keys

Strings, Counters, Key Management

Strings hold text, numbers or bytes (up to the string size limit in the docs). Counters use INCR.

CommandWhat it doesComplexityGotcha
SET k v [EX s | PX ms] [NX | XX] [GET] [KEEPTTL]Set a value with optional expiry and conditionsO(1)SET clears an existing TTL unless KEEPTTL; NX + EX is the basic lock primitive; GET option since 6.2
GET kRead a stringO(1)Returns nil for a missing key; WRONGTYPE error for other types
SETNX, SETEX, PSETEXOlder set variantsO(1)Marked deprecated in the command reference; use SET options
MSET / MGETSet / get many keysO(N), N = number of keysIn Redis Cluster all keys must share one hash slot
INCR / INCRBY / DECRAtomic integer counterO(1)Value must be an integer string; creates the key at 0 if missing
INCRBYFLOATAtomic float addO(1)Float rounding applies
APPEND k vAppend to a stringO(1) amortisedGood for small appends
GETDEL kRead and delete atomicallyO(1)Since 6.2
GETEX k EX sRead and change expiryO(1)Since 6.2; sliding-expiry cache pattern
STRLEN / GETRANGE / SETRANGELength / substring / overwrite partO(1) / O(N) returned / O(1) or O(M) copiedOffsets are in bytes
EXISTS k [k ...]Count how many keys existO(N), N = keys checkedPassing the same key twice counts twice
DEL k [k ...]Delete keysO(N) keys; O(M) per big collectionDeleting a huge collection blocks the server
UNLINK k [k ...]Delete without blocking (memory freed in another thread)O(1) per keySince 4.0; prefer over DEL for big keys
TYPE kData type of the keyO(1)Returns none if missing
RENAME a bRename a keyO(1)Overwrites b; in Cluster both keys need the same slot
COPY src dstCopy a keyO(N) for collectionsSince 6.2
SCAN cursor [MATCH p] [COUNT n] [TYPE t]Iterate keys without blockingO(1) per call, O(N) for a full passMay return duplicates; a key present throughout is returned at least once; loop until the cursor is 0
KEYS patternList all matching keysO(N) over the whole keyspaceNever in production; use SCAN
OBJECT ENCODING k / OBJECT FREQ kInternal encoding / access frequency (LFU policies)O(1)OBJECT FREQ needs an LFU maxmemory-policy
MEMORY USAGE kBytes a key usesO(N), N = samplesSince 4.0; includes overhead
03
Chapter 3 - Hashes and lists

Hashes (objects) and Lists (queues)

Hashes model an object with fields. Lists are linked sequences, good at the two ends.

CommandWhat it doesComplexityGotcha
HSET k f v [f v ...]Set one or more fieldsO(1) per pairMultiple pairs accepted since 4.0 (replaces HMSET)
HGET k f, HMGET k f1 f2Read one / several fieldsO(1) / O(N) fieldsMissing field returns nil
HGETALL kAll fields and valuesO(N), N = hash sizeAvoid on big hashes; use HSCAN
HDEL k f, HLEN k, HKEYS kRemove field, count, list namesO(N) removed / O(1) / O(N)HKEYS is also O(N) of the whole hash
HINCRBY k f nAtomic counter in a fieldO(1)Per-object counters without read-modify-write
HSCAN k cursor [MATCH p] [COUNT n]Iterate fieldsO(1) per callSame duplicate caveat as SCAN
HEXPIRE k seconds FIELDS n f ...Expire individual hash fieldsO(N), N = fieldsHash field expiration listed since 7.4.0 in the reference
LPUSH / RPUSH k v ...Add to head / tailO(1) per elementOrder of several values: LPUSH a b c leaves c first
LPOP / RPOP k [count]Remove from head / tailO(N), N = elements returnedThe count form needs 6.2+
LRANGE k start stopRead a rangeO(S+N)LRANGE k 0 -1 returns everything: avoid on long lists
LINDEX k i, LSET k i vRead / write by indexO(N) to the index (O(1) at either end)Middle access is slow on long lists
LLEN kLengthO(1)
LTRIM k start stopKeep only a rangeO(N) removedLPUSH + LTRIM 0 99 = capped recent list
LREM k count vRemove matching valuesO(N+M)Scans the list
LMOVE src dst LEFT RIGHTAtomically move an element between listsO(1)Since 6.2; reliable-queue building block (replaces RPOPLPUSH)
BLPOP k [k ...] timeoutBlocking popO(N) keysTimeout 0 blocks forever; blocking commands hold the client connection
04
Chapter 4 - Sets and sorted sets

Sets, Sorted Sets, Probabilistic Types

Sets: unique members. Sorted sets: unique members ordered by a score (leaderboards, delay queues, rate-limit windows).

CommandWhat it doesComplexityGotcha
SADD / SREM k m ...Add / remove membersO(1) per add / O(N) removedReturns the number actually added
SISMEMBER k m, SMISMEMBER k m1 m2Membership testO(1) / O(N) testedSMISMEMBER since 6.2
SMEMBERS kAll membersO(N), N = set sizeUse SSCAN for big sets
SCARD kSizeO(1)
SINTER / SUNION / SDIFFSet algebraO(N*M) worst case / O(N) / O(N)Large sets block; ...STORE variants save the result
SPOP / SRANDMEMBER k [count]Remove / read random membersO(1) without count, O(N) with
ZADD k [NX|XX] [GT|LT] [CH] score mAdd or update a member's scoreO(log N) per itemGT / LT since 6.2; CH counts changed members
ZRANGE k start stop [BYSCORE|BYLEX] [REV] [LIMIT o c] [WITHSCORES]Range by rank, score or lexicographic orderO(log N + M)The unified form since 6.2; older ZRANGEBYSCORE and ZREVRANGE are deprecated in the reference
ZRANK k m, ZSCORE k mRank / score of a memberO(log N) / O(1)Rank is 0-based
ZINCRBY k n mAdd to a scoreO(log N)Atomic leaderboard update
ZCARD / ZCOUNT k min maxSize / count in a score rangeO(1) / O(log N)Use ( for exclusive bounds: (5
ZREM k mRemove membersO(M log N)
ZPOPMIN / ZPOPMAX k [count]Pop lowest / highest scoresO(log N * M)Basis of a simple priority or delay queue
ZREMRANGEBYRANK / ...BYSCORETrim a sorted setO(log N + M)Sliding-window rate limiting: remove old scores
PFADD / PFCOUNTHyperLogLog: approximate distinct countO(1)Fixed small memory; approximate by design
SETBIT / GETBIT / BITCOUNTBit arraysO(1) / O(1) / O(N)Compact flags per user id
GEOADD / GEOSEARCHGeospatial index on a sorted setO(log N) per item / O(N+log M)Radius searches cost grows with results
05
Chapter 5 - Streams, pub/sub, scripting

Streams, Pub/Sub, Transactions and Scripts

Streams are an append-only log with consumer groups (a lightweight Kafka-like model).

CommandWhat it doesComplexityGotcha
XADD s * f v [MAXLEN ~ n]Append an entry (* = auto id)O(1), O(N) when trimming~ trims approximately and is cheaper
XLEN s, XRANGE s - + COUNT nLength / read a rangeO(1) / O(N) returnedAlways pass COUNT
XREAD COUNT n BLOCK ms STREAMS s idRead new entriesSee the reference (depends on streams)$ means "only entries after now"
XGROUP CREATE s g $ [MKSTREAM]Create a consumer groupDepends on subcommandGroup needs an existing stream or MKSTREAM
XREADGROUP GROUP g c COUNT n STREAMS s >Read as a group memberO(M) returned> means undelivered entries; an id such as 0 replays your pending ones
XACK s g idAcknowledge an entryO(1) per idUnacked entries stay in the pending list
XPENDING s gInspect unacknowledged entriesO(N) returnedFind stuck consumers
XAUTOCLAIM s g c min-idle 0Take over idle pending entriesO(1) with small COUNTReply gained an element in 7.0
XTRIM / XDELTrim by length or id / delete entriesO(N) evicted / O(1) eachXDEL removes entries by id; use XTRIM to bound stream size
PUBLISH ch msg, SUBSCRIBE chFire-and-forget messagingO(N+M) / O(N)Subscribers that are offline miss messages; use streams for durability
SPUBLISH / SSUBSCRIBESharded pub/sub for ClusterO(N) subscribersSince 7.0
MULTI ... EXECQueue commands and run them as one atomic blockDepends on commandsNo rollback: a command that errors at run time does not undo the others
WATCH k ... MULTI ... EXECOptimistic lockingO(1) per keyIf a watched key changes, EXEC returns nil: retry
EVAL script numkeys k ... arg ..., EVALSHARun a Lua script atomicallyDepends on the scriptDeclare keys in KEYS, not in the script text; long scripts block
FUNCTION LOAD, FCALLRedis Functions (server-side libraries)O(1) load, depends on functionSince 7.0; persisted with the dataset
06
Chapter 6 - TTL and eviction

Expiry and Memory Limits

Expiry removes keys by time; eviction removes keys when memory is full. Different mechanisms.

CommandWhat it doesComplexityGotcha
EXPIRE k s [NX|XX|GT|LT]Set a TTL in secondsO(1)Options since 7.0; PEXPIRE for milliseconds, EXPIREAT for a Unix time
TTL k / PTTL kRemaining timeO(1)-1 = no expiry, -2 = key does not exist
PERSIST kRemove the TTLO(1)
EXPIRETIME kAbsolute expiry timeO(1)Since 7.0
Overwriting a keySET removes the TTL; INCR, LPUSH and similar keep itn/aRe-apply the TTL after rewrites
CONFIG SET maxmemory 2gbMemory limitO(N) parametersWithout a limit Redis can grow until the OS kills it
maxmemory-policy noevictionWrites fail with an error when fulln/aDefault policy per the eviction docs
allkeys-lru / allkeys-lfu / allkeys-randomEvict any key by recency / frequency / randomlyn/aThe docs call allkeys-lru a good default when you have no other preference; LRU is approximate (sampling)
volatile-lru / volatile-lfu / volatile-random / volatile-ttlEvict only keys that have a TTLn/aWith no TTL keys they behave like noeviction
allkeys-lrm / volatile-lrmLeast recently modified policiesn/aListed in the current docs; not in older releases, check your version
INFO memory, INFO statsused_memory, evicted_keys, expired_keysO(1)Rising evicted_keys means the cache is too small
07
Chapter 7 - Persistence and replication

RDB, AOF, Replicas

Persistence choices checked against the Redis persistence documentation.

ItemWhat it doesComplexityGotcha
RDB (save <seconds> <changes>)Periodic point-in-time snapshot to dump.rdbn/aYou can lose writes since the last snapshot
BGSAVESnapshot in a child processO(1) to startFork can pause the main thread on very large datasets; SAVE blocks and is O(N)
LASTSAVETime of the last successful saveO(1)Use it to confirm snapshots happen
AOF (appendonly yes)Log of every write, replayed on startn/aSince 7.0 AOF is split into several files in the appenddirname directory
appendfsync everysecFsync once per second (the suggested default)n/aYou can lose about one second of writes
appendfsync alwaysFsync on every write batchn/aSafest and slowest
appendfsync noLet the OS flushn/aFastest, least safe
BGREWRITEAOFCompact the AOF in the backgroundO(1) to startRewrite uses disk and memory while running
WAIT n timeout, WAITAOFBlock until replicas or local AOF acknowledge the writesO(1)WAITAOF since 7.2; acknowledgement still is not a full consensus guarantee
REPLICAOF host port / REPLICAOF NO ONEMake this node a replica / promote itO(1)Old name SLAVEOF
ROLE, INFO replicationShow role, offsets, lagO(1)Compare master_repl_offset with replica offsets
FAILOVERCoordinated switchover to a replicaO(1)Since 6.2
08
Chapter 8 - Cluster and operations

Cluster, Diagnostics, Admin

Cluster spreads keys over 16384 hash slots (stated in the cluster documentation); a key's slot is a hash of its name, and {tag} parts force related keys into one slot.

CommandWhat it doesComplexityGotcha
CLUSTER INFOCluster state, slots assigned, known nodesO(1)cluster_state:ok is what you want
CLUSTER NODESAll nodes with ids, roles, slot ranges, flagsO(N) nodesfail and handshake flags show trouble
CLUSTER SHARDSShard-oriented view (since 7.0)O(N) nodesReplaces CLUSTER SLOTS, which is deprecated in the reference
CLUSTER KEYSLOT keyWhich slot a key maps toO(N) bytes in keyCheck hash-tag usage
CLUSTER COUNTKEYSINSLOT slotKeys in a slotO(1)Useful during resharding
CLUSTER MEET ip portIntroduce a nodeO(1)Usually done by redis-cli --cluster
CLUSTER FAILOVERManual replica takeover (run on the replica)O(1)Safer than killing the master
MOVED / ASK errorsKey lives on another node / slot is migratingn/aUse a cluster-aware client or redis-cli -c
INFO [section]Server metricsO(1)Sections: server, clients, memory, persistence, stats, replication, cpu, keyspace
DBSIZENumber of keys in the selected databaseO(1)
SLOWLOG GET 10Recent slow commandsO(N) returnedThreshold set by slowlog-log-slower-than
LATENCY DOCTORHuman-readable latency reportO(1)Needs the latency monitor threshold configured
MEMORY DOCTORMemory problem hintsO(1)
CLIENT LIST / CLIENT KILLList / disconnect clientsO(N) clientsLook for idle or blocked clients
MONITORStream every command receivedn/aHeavy; reduces throughput, never leave it running; also exposes data
CONFIG GET / CONFIG SET / CONFIG REWRITERead, change, persist configurationO(N) params / O(1)CONFIG SET is lost on restart unless rewritten
FLUSHDB / FLUSHALL [ASYNC]Delete all keys in one DB / all DBsO(N)No undo; many deployments restrict it with ACLs
ACL SETUSER, AUTH, HELLOUsers, authentication, protocol negotiationO(N) rules / O(N) passwords / O(1)HELLO 3 switches to RESP3
SHUTDOWN [NOSAVE|SAVE]Stop the serverO(N) when savingDefault saves if persistence is on
09
Chapter 9 - redis-cli

redis-cli Options

Option names checked against redis-cli.c in the Redis source (unstable branch); redis-cli --help shows your build's list.

OptionWhat it doesGotcha
-h host -p portConnect to a host and portDefaults to 127.0.0.1:6379
-u redis://user:pass@host:6379/0Connect with a URIPasswords on the command line show in the process list
-a password / --user name --pass pw / --askpassAuthenticate--askpass prompts so nothing is left in history
-n 2Select a databaseCluster mode has database 0 only
-cFollow MOVED and ASK redirectsNeeded for Cluster
--tls, --insecureUse TLS; skip certificate verification--insecure only for tests
-3Use RESP3Output format changes
--raw / --no-rawRaw or formatted outputRaw is the default when output is not a terminal
--csv, --jsonMachine-readable outputHandy for scripts
-xRead the last argument from stdinFor setting binary or multi-line values
-r 10 -i 1 cmdRepeat a command 10 times, 1 second apart-r -1 repeats forever
--scan --pattern "user:*" [--count n]Iterate keys with SCANSafe alternative to KEYS
--bigkeys, --memkeys, --keystatsSample the keyspace for the largest keys / memory use / statisticsUses SCAN; --memkeys and --keystats exist in newer builds
--hotkeysFind hot keysWorks only with an LFU eviction policy
--latency, --latency-history, --latency-distMeasure latency (live, over time, as a distribution)Measures from the client, includes the network
--intrinsic-latency 5Measure system latency on the machine running itRun on the Redis host, not remotely
--statRolling server statisticsA quick top for Redis
--rdb fileDownload an RDB snapshot from the serverTriggers a save on the server
--pipeMass insert from a stream of protocol textMuch faster than one command per line
--cluster create|check|reshard ...Cluster administrationManage with care; --cluster-yes auto-confirms
--eval script.lua keys , argsRun a Lua script fileA comma separates keys from arguments
10
Chapter 10 - Common mistakes

Redis Mistakes

โš  The ones that cost real time
  • **KEYS * in production.** O(N) over the keyspace, blocks everyone. Use SCAN.
  • **HGETALL, SMEMBERS, LRANGE 0 -1 on big keys.** Page with HSCAN, SSCAN, ranges.
  • **Caching without a TTL and without maxmemory.** The instance grows until it is killed. Set both.
  • **Assuming SET keeps the TTL.** It clears it unless you pass KEEPTTL.
  • Using pub/sub where messages must not be lost. Offline subscribers miss them; use Streams.
  • **Treating MULTI/EXEC like a database transaction.** There is no rollback.
  • Multi-key commands across slots in Cluster. Use hash tags like {user:1}:cart.
  • **Big deletes with DEL.** Use UNLINK.
  • **MONITOR left running.** It slows the server and leaks data.
  • **One lock key with SETNX and no expiry.** A crashed holder blocks everyone forever; use SET k v NX EX 30 and a unique value.
11
Chapter 11 - Go deeper

Long-form pages and what was checked

TopicPage
Redis data model, persistence and clustering in depthRedis
Caching strategies and invalidationCaching Patterns
Choosing a databaseNoSQL Fundamentals
Redis as a Spring cacheCaching & Resilience
Cache performancePerformance: Caching
Version note

Checked on 2026-10-31: every complexity string and "since" version in this sheet against the machine-readable command reference (commands.json in the redis/docs repository, which backs redis.io/docs/latest/commands); deprecation marks for SETNX, SETEX, ZRANGEBYSCORE, ZREVRANGE and CLUSTER SLOTS from the same file; eviction policies and the noeviction policy from the Redis eviction documentation (the current docs also list the lrm policies, which are newer); persistence behaviour (RDB, appendfsync modes, multi-part AOF since 7.0) from the persistence documentation; redis-cli option names from redis-cli.c (unstable). No Redis server was available locally, so no command was executed. The 16384-slot figure and the hash-tag rule are standard Redis Cluster facts not re-fetched for this sheet.