Skip to content

Redis Cheatsheet ​

A dense quick reference for redis-cli, the commands of each data type with complexity, transactions, persistence, replication, ACL, diagnostics, eviction, and Go and Laravel snippets. Concepts live in the Redis chapter.

redis-cli ​

TaskCommandNotes
Connectredis-cli -h host -p 6379 -a pass --user app -n 2-n selects the logical DB; --user needs -a; prefer REDISCLI_AUTH over -a
TLSredis-cli --tls --cacert ca.crt --cert c.crt --key c.key -h host -p 6380
URIredis-cli -u redis://user:pass@host:6379/0rediss:// for TLS
One-shotredis-cli GET keyRaw output when stdout is not a tty; --no-raw forces formatted output
Cluster moderedis-cli -c -p 7000Follows MOVED and ASK redirects
Scan keysredis-cli --scan --pattern 'user:*' --count 500Uses SCAN, so it does not block the server; --count defaults to 10; never use KEYS in production
Big keysredis-cli --bigkeysSamples with SCAN; --memkeys reports memory
Latencyredis-cli --latency / --latency-history / --latency-distRound-trip from the client
Intrinsic latencyredis-cli --intrinsic-latency 5Run on the server host for 5 seconds
Stat streamredis-cli --statRolling keys, memory, clients, ops
Monitorredis-cli MONITORPrints every command; heavy, short use only
Bulk loadcat cmds.txt | redis-cli --pipeProtocol-mass insert
RDB from remoteredis-cli --rdb dump.rdbTriggers a sync and saves the snapshot
Replayredis-cli -r 5 -i 1 PING-r repeat count, -i interval seconds
HelpHELP @sorted_set or HELP ZADDInside the shell
Cluster createredis-cli --cluster create h1:7000 h2:7001 h3:7002 --cluster-replicas 1Also add-node and reshard; check, fix, rebalance not verified

References: redis-cli, Commands.

Keys and expiry ​

TaskCommandNotes
Exists, deleteEXISTS k, DEL k1 k2O(N) in keys; UNLINK k frees memory in the background
Set TTL (s / ms)EXPIRE k 60, PEXPIRE k 60000Options NX, XX, GT, LT since 7.0; O(1)
Absolute expiryEXPIREAT k 1767225600, PEXPIREATUnix time
Read TTLTTL k, PTTL k-1 no expiry, -2 key missing
Remove TTLPERSIST kO(1)
Expiry timeEXPIRETIME kAbsolute Unix time, 7.0+
RenameRENAME k k2, RENAMENXOverwrites target; in Cluster both keys need one slot
TypeTYPE kstring, list, set, zset, hash, stream; the latest docs also list bitmap and vectorset
IterateSCAN 0 MATCH user:* COUNT 100 TYPE hashLoop until cursor returns 0; may repeat keys
Collection scansHSCAN, SSCAN, ZSCAN k cursorSame cursor semantics
EncodingOBJECT ENCODING klistpack, quicklist, intset, hashtable, skiplist, embstr, int, raw
Idle, frequencyOBJECT IDLETIME k, OBJECT FREQ kFREQ needs an LFU policy
MemoryMEMORY USAGE k SAMPLES 0Bytes including overhead; SAMPLES 0 means all elements
CopyCOPY src dst REPLACE6.2+
Move DBMOVE k 1Not for Cluster
SortSORT list BY weight_* LIMIT 0 10 GET obj_*O(N log M); SORT_RO is read-only
Count keysDBSIZEO(1)
WipeFLUSHDB ASYNC, FLUSHALL ASYNCDangerous; rename or ACL-deny in production
Dump and restoreDUMP k then RESTORE k 0 payload REPLACEOpaque serialized value; MIGRATE moves between servers
Wait for replicasWAIT 1 100Replicas acked within 100 ms; returns the count

References: Keyspace, Key eviction.

String ​

TaskCommandNotes
SetSET k v EX 60 NXOptions EX, PX, EXAT, PXAT, NX, XX, KEEPTTL, GET; O(1)
GetGET k, MGET k1 k2, MSET k1 v1 k2 v2O(1), O(N) for multi-key
Get and delete or expireGETDEL k, GETEX k EX 60O(1)
CounterINCR k, INCRBY k 5, DECR k, INCRBYFLOAT k 1.5Atomic, O(1); value must be integer-like
AppendAPPEND k sO(1) amortized
Length, rangeSTRLEN k, GETRANGE k 0 -1, SETRANGE k 3 xxO(1) and O(N)
LockSET lock:x token NX PX 30000Release only if token matches (Lua compare-and-delete)
Longest commonLCS a b LEN7.0+

Hash ​

TaskCommandNotes
Set fieldsHSET h f1 v1 f2 v2O(N) in pairs; HMSET is deprecated
GetHGET h f, HMGET h f1 f2, HGETALL hHGETALL is O(N), avoid on big hashes
Missing onlyHSETNX h f vO(1)
Delete, existsHDEL h f, HEXISTS h fO(1) per field
CountersHINCRBY h f 1, HINCRBYFLOATO(1)
Keys, values, sizeHKEYS, HVALS, HLENO(N), O(N), O(1)
RandomHRANDFIELD h 3 WITHVALUES6.2+
Field TTLHEXPIRE h 60 FIELDS 1 f, HTTLRedis 7.4+

List ​

TaskCommandNotes
PushLPUSH l a b, RPUSH l a bO(1) per element; LPUSHX only if exists
PopLPOP l 2, RPOP lO(N) for N popped
Blocking popBLPOP l1 l2 5, BRPOPTimeout seconds, 0 blocks forever
MoveLMOVE src dst LEFT RIGHT, BLMOVEReplaces RPOPLPUSH; reliable queue pattern
RangeLRANGE l 0 -1O(S+N); avoid unbounded ranges
IndexLINDEX l 0, LSET l 0 vO(N)
LengthLLEN lO(1)
TrimLTRIM l 0 99Capped list: LPUSH then LTRIM
RemoveLREM l 0 vO(N+M); count 0 removes all
InsertLINSERT l BEFORE pivot vO(N)
PositionLPOS l v RANK 1O(N)
Multi-popLMPOP 2 l1 l2 LEFT COUNT 107.0+

Set ​

TaskCommandNotes
Add, removeSADD s a b, SREM s aO(N) in elements
MemberSISMEMBER s a, SMISMEMBER s a bO(1) per element
All, countSMEMBERS s, SCARD sO(N), O(1); prefer SSCAN for big sets
RandomSRANDMEMBER s 3, SPOP s 2O(N) for count
AlgebraSINTER a b, SUNION a b, SDIFF a bAdd STORE variants; SINTERCARD 2 a b LIMIT 10
MoveSMOVE src dst mO(1)

Sorted set ​

TaskCommandNotes
AddZADD z GT CH 10 a 20 bO(log N) each; options NX, XX, GT, LT, CH, INCR; GT, LT and NX are mutually exclusive
IncrementZINCRBY z 5 aO(log N)
Score, rankZSCORE z a, ZRANK z a, ZREVRANK z aO(1), O(log N)
Range (6.2 unified)ZRANGE z 0 9 REV WITHSCORESBYSCORE, BYLEX, LIMIT off n options
By scoreZRANGE z (10 +inf BYSCORE LIMIT 0 20( makes the bound exclusive
CountZCARD z, ZCOUNT z 10 20O(1), O(log N)
RemoveZREM z a, ZREMRANGEBYSCORE z 0 9, ZREMRANGEBYRANK z 0 -101O(log N + M)
PopZPOPMIN z 3, BZPOPMIN z 5O(log N * M)
AlgebraZUNIONSTORE out 2 a b WEIGHTS 1 2, ZINTERSTORE, ZDIFFAggregate SUM, MIN or MAX
Multi-popZMPOP 2 a b MIN COUNT 57.0+

Stream ​

TaskCommandNotes
AppendXADD s MAXLEN ~ 10000 * f v* auto id; ~ approximate trim; O(1)
Read rangeXRANGE s - + COUNT 10, XREVRANGE s + -O(log N + M)
Read newXREAD COUNT 10 BLOCK 5000 STREAMS s $$ means only new entries
Create groupXGROUP CREATE s g $ MKSTREAM0 starts from the beginning
Group readXREADGROUP GROUP g c1 COUNT 10 BLOCK 5000 STREAMS s >> delivers never-delivered entries
AckXACK s g idRemoves from the pending list
PendingXPENDING s g - + 10Shows owner, idle time, delivery count
ClaimXAUTOCLAIM s g c2 60000 0-0 COUNT 10Take over idle messages (6.2+)
Trim, deleteXTRIM s MINID ~ id, XDEL s id
InfoXLEN s, XINFO STREAM s, XINFO GROUPS s, XINFO CONSUMERS s g

HyperLogLog, Bitmap, Geo ​

TaskCommandNotes
HLL addPFADD hll a b cO(1); about 0.81% standard error, 12 KB max
HLL countPFCOUNT hll1 hll2O(1) single key
HLL mergePFMERGE out hll1 hll2O(N)
Set bitSETBIT bm 7 1, GETBIT bm 7O(1)
Count bitsBITCOUNT bm 0 -1 BYTEO(N); BIT unit since 7.0
Bit opsBITOP AND dest a bAND, OR, XOR, NOT; O(N)
First bitBITPOS bm 1O(N)
Bit fieldsBITFIELD k INCRBY u8 0 1 OVERFLOW SATPacked counters
Geo addGEOADD g 13.36 38.11 palermoO(log N); stored in a sorted set
DistanceGEODIST g a b kmO(1)
Radius searchGEOSEARCH g FROMLONLAT 15 37 BYRADIUS 200 km ASC WITHDISTReplaces GEORADIUS (6.2+); BYBOX also
Store searchGEOSEARCHSTORE dst g FROMMEMBER a BYRADIUS 50 km

Pub/Sub ​

TaskCommandNotes
PublishPUBLISH ch msgO(N + M); fire and forget, no persistence
SubscribeSUBSCRIBE ch1 ch2, PSUBSCRIBE news.*Connection enters subscriber mode
UnsubscribeUNSUBSCRIBE, PUNSUBSCRIBE
ShardedSSUBSCRIBE ch, SPUBLISH ch msgCluster-scoped to a slot, 7.0+
IntrospectPUBSUB CHANNELS, PUBSUB NUMSUB ch, PUBSUB NUMPAT
Keyspace eventsCONFIG SET notify-keyspace-events KEAThen subscribe to __keyevent@0__:expired

References: Data types, Commands by group.

Transactions, scripting and Functions ​

TaskCommandNotes
TransactionMULTI ... EXECQueued, run atomically; no rollback on runtime errors
AbortDISCARD
Optimistic lockWATCH k then MULTI ... EXECEXEC returns nil if k changed
UnwatchUNWATCH
EvalEVAL "return redis.call('GET', KEYS[1])" 1 kDeclare all keys in KEYS for Cluster
Cached scriptSCRIPT LOAD src, EVALSHA sha 1 kOn NOSCRIPT, reload and retry
Script adminSCRIPT EXISTS sha, SCRIPT FLUSH
Read-only evalEVAL_RO, EVALSHA_ROSafe on replicas
FunctionsFUNCTION LOAD "#!lua name=lib\nredis.register_function('f', function(keys, args) return 1 end)"7.0+; persisted and replicated
Call functionFCALL f 1 k arg, FCALL_RO
Function adminFUNCTION LIST, FUNCTION DELETE lib, FUNCTION DUMP, FUNCTION RESTORE
PipelineClient batches commands without MULTISaves round trips, not atomic

Lua compare-and-delete lock release:

lua
if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end

References: Transactions, Lua scripting, Functions.

Persistence and CONFIG ​

TaskCommandNotes
Read configCONFIG GET maxmemory*Glob patterns
Set at runtimeCONFIG SET maxmemory 2gbNot persisted by itself
Persist to fileCONFIG REWRITEWrites back to redis.conf
RDB triggerBGSAVE, SAVESAVE blocks; avoid it
RDB schedulesave 3600 1 300 100 60 10000Config: seconds and changes; this is the default per the current redis.conf
Last saveLASTSAVEUnix time
AOF enableappendonly yesConfig, Redis also supports a multi-part AOF since 7.0
AOF fsyncappendfsync everysecalways, everysec, no
AOF rewriteBGREWRITEAOFCompacts the log; also automatic via auto-aof-rewrite-percentage
Hybridaof-use-rdb-preamble yesRDB header plus AOF tail
Check filesredis-check-aof --fix fileOffline AOF repair; redis-check-rdb is not verified
ShutdownSHUTDOWN NOSAVE or SHUTDOWN SAVE
Reset statsCONFIG RESETSTAT
Data dirCONFIG GET dirAlso dbfilename, appenddirname

Persistence choice: RDB only gives fast restarts and loses minutes; AOF everysec loses about one second; both together is the common default; neither is a cache.

References: Persistence, CONFIG.

Replication, Sentinel and Cluster ​

TaskCommandNotes
Make replicaREPLICAOF host 6379REPLICAOF NO ONE promotes; SLAVEOF is deprecated
RoleROLEmaster or replica with offsets
Replication infoINFO replicationmaster_repl_offset, connected_slaves, lag
Backlogrepl-backlog-size 64mbLarger avoids full resync after short outages
Require replicasmin-replicas-to-write 1, min-replicas-max-lag 10Refuse writes when replicas lag
FailoverFAILOVER TO host portCoordinated switch, 6.2+
Sentinel mastersSENTINEL masters, SENTINEL get-master-addr-by-name mymasterRun against port 26379
Sentinel failoverSENTINEL failover mymasterForces a failover
Sentinel healthSENTINEL ckquorum mymasterChecks quorum
Cluster infoCLUSTER INFO, CLUSTER NODES, CLUSTER SHARDScluster_state:ok expected
Slot of a keyCLUSTER KEYSLOT kCRC16 mod 16384; hash tags {user:1}:a colocate keys
Slot ownerCLUSTER SLOTSDeprecated since 7.0; prefer CLUSTER SHARDS
Manual failoverCLUSTER FAILOVER (on a replica)Option FORCE or TAKEOVER
Add noderedis-cli --cluster add-node new existing
Move slotsredis-cli --cluster reshard host:portMoves slots; see the cluster tutorial
ForgetCLUSTER FORGET node-idRun on every node; sets a 60-second ban on re-adding that node ID
Read from replicaREADONLYPer connection, cluster replicas only

References: Replication, Sentinel, Cluster spec.

ACL and security ​

TaskCommandNotes
Create userACL SETUSER app on >secret ~app:* &* +@read +@write -@dangerouson, >password, ~keypattern, &channel, +@category
Command rule+get +set -flushallAllow or deny single commands; +config|get for subcommands
Key permissions%R~cache:* %W~out:*Read-only and write-only key patterns, 7.0+
ListACL LIST, ACL USERS, ACL GETUSER app
Who am IACL WHOAMI
CategoriesACL CAT, ACL CAT dangerous
DeleteACL DELUSER app
PersistACL SAVE, ACL LOADNeeds aclfile in config
AuditACL LOG, ACL LOG RESETRecent denials
AuthenticateAUTH user passAUTH pass targets default
Disable defaultACL SETUSER default offAfter creating real users
Bind and protectbind 10.0.0.5, protected-mode yesNever expose Redis to the internet
TLStls-port 6380, tls-cert-file, tls-key-file, tls-ca-cert-fileSet port 0 to disable plaintext
Hide commandsrename-command is legacyPrefer ACL

References: ACL, Security.

INFO sections and diagnostics ​

TaskCommandNotes
All statsINFO or INFO allSections: server, clients, memory, persistence, stats, replication, cpu, commandstats, cluster, keyspace
Hit ratioINFO statskeyspace_hits, keyspace_misses, evicted_keys, expired_keys
MemoryINFO memoryused_memory, used_memory_rss, mem_fragmentation_ratio, maxmemory
Per commandINFO commandstatscalls, usec_per_call
Keys per DBINFO keyspacekeys, expires, avg_ttl
ClientsCLIENT LIST, CLIENT KILL ID n, CLIENT SETNAME appINFO clients has blocked_clients
Slow logSLOWLOG GET 10, SLOWLOG LEN, SLOWLOG RESETThreshold slowlog-log-slower-than 10000 microseconds
Latency eventsLATENCY LATEST, LATENCY HISTORY command, LATENCY DOCTORNeeds latency-monitor-threshold 100
Latency graphLATENCY GRAPH commandASCII chart
Memory doctorMEMORY DOCTOR, MEMORY STATS, MEMORY PURGE
Big keysMEMORY USAGE k, redis-cli --bigkeys
Ping, timePING, TIME
Command docsCOMMAND DOCS get, COMMAND COUNT

References: INFO, Latency monitoring, Slow log.

Eviction policies ​

PolicyEvictsNotes
noevictionNothing; writes fail with OOMDefault; right for queues and primary data
allkeys-lruLeast recently used, any keyGood general cache
allkeys-lrmLeast recently modified, any keyRedis 8.6+; reads do not refresh it
allkeys-lfuLeast frequently used, any keyBetter for skewed popularity, 4.0+
allkeys-randomRandom key
volatile-lruLRU among keys with a TTLKeys without TTL stay
volatile-lrmLRM among keys with a TTLRedis 8.6+
volatile-lfuLFU among keys with a TTL
volatile-randomRandom among keys with a TTL
volatile-ttlShortest remaining TTL first

Set with CONFIG SET maxmemory 2gb and CONFIG SET maxmemory-policy allkeys-lfu; tune accuracy with maxmemory-samples 5. Replicas ignore eviction and follow the primary.

References: Eviction.

Common errors ​

ErrorCauseFix
WRONGTYPE Operation against a key holding the wrong kind of valueCommand does not match the key typeCheck TYPE k; fix key naming
MOVED 3999 host:6381Cluster key lives on another nodeUse a cluster-aware client or redis-cli -c
ASK 3999 host:6381Slot is migratingClient sends ASKING then retries
CROSSSLOT Keys in request don't hash to the same slotMulti-key command spans slotsUse hash tags {id}
OOM command not allowed when used memory > 'maxmemory'Memory full with noevictionRaise maxmemory, set eviction, add TTLs
NOAUTH Authentication requiredNo password suppliedAUTH or fix the URL
WRONGPASS invalid username-password pair or user is disabled.Bad credentials or disabled userCheck the ACL user
NOPERM User app has no permissions to run the 'x' commandACL denialACL LOG, adjust rules
READONLY You can't write against a read only replicaWriting to a replica or after failoverConnect to the primary; use Sentinel-aware client
LOADING Redis is loading the dataset in memoryStartup or full syncRetry with backoff
BUSY Redis is busy running a scriptLong Lua scriptSCRIPT KILL or FUNCTION KILL
MISCONF Redis is configured to save RDB snapshotsBGSAVE failing (disk or permissions)Fix disk; check logs; stop-writes-on-bgsave-error
ERR max number of clients reachedmaxclients hitPool connections; raise limit and ulimit -n
EXECABORT Transaction discarded because of previous errorsSyntax error while queueingFix the command and retry
NOSCRIPT No matching scriptEVALSHA on a cold cacheSCRIPT LOAD then retry

References: Cluster spec, ACL, Redis source, error replies, redis.conf.

Go (go-redis) and Laravel ​

TaskSnippetNotes
Go connectrdb := redis.NewClient(&redis.Options{Addr: "localhost:6379", PoolSize: 20})github.com/redis/go-redis/v9
Go URLopt, _ := redis.ParseURL("redis://user:pass@h:6379/0")Then redis.NewClient(opt)
Go set and getrdb.Set(ctx, "k", "v", time.Minute), rdb.Get(ctx, "k").Result()Missing key returns redis.Nil
Go pipelinepipe := rdb.Pipeline(); pipe.Incr(ctx, "n"); _, err := pipe.Exec(ctx)TxPipeline wraps MULTI and EXEC
Go watchrdb.Watch(ctx, func(tx *redis.Tx) error { ... }, "k")Returns redis.TxFailedErr on conflict
Go scriptredis.NewScript(src).Run(ctx, rdb, []string{"k"}, arg)Handles EVALSHA and fallback
Go clusterredis.NewClusterClient(&redis.ClusterOptions{Addrs: []string{"h1:7000"}})Follows MOVED automatically
Go Sentinelredis.NewFailoverClient(&redis.FailoverOptions{MasterName: "mymaster", SentinelAddrs: addrs})
Laravel envREDIS_CLIENT=phpredis, REDIS_HOST, REDIS_PASSWORD, REDIS_PORT, REDIS_DBpredis is the pure PHP client
Laravel facadeRedis::set('k', 'v'), Redis::get('k'), Redis::connection('cache')->incr('n')Connections in config/database.php under redis
Laravel pipelineRedis::pipeline(function ($pipe) { $pipe->set('a', 1); })
Laravel pub/subRedis::subscribe(['ch'], fn ($m) => ...), Redis::publish('ch', $msg)
Laravel cacheCACHE_STORE=redis, Cache::remember('k', 600, fn () => ...)Cache::lock('x', 10)->get() for locks
Laravel queueQUEUE_CONNECTION=redis, php artisan queue:work redis --queue=defaultHorizon manages workers
Laravel sessionSESSION_DRIVER=redis
Laravel throttleRedis::throttle('k')->allow(10)->every(60)->then(fn () => ..., fn () => ...)Rate limiting helper
go
val, err := rdb.Get(ctx, "k").Result()
switch {
case errors.Is(err, redis.Nil):
	// key does not exist
case err != nil:
	return err
default:
	fmt.Println(val)
}

References: go-redis and README, Laravel Redis, Laravel Cache, Laravel Queues.

Built by Morteza Negahi