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
| Task | Command | Notes |
|---|---|---|
| Connect | redis-cli -h host -p 6379 -a pass --user app -n 2 | -n selects the logical DB; --user needs -a; prefer REDISCLI_AUTH over -a |
| TLS | redis-cli --tls --cacert ca.crt --cert c.crt --key c.key -h host -p 6380 | |
| URI | redis-cli -u redis://user:pass@host:6379/0 | rediss:// for TLS |
| One-shot | redis-cli GET key | Raw output when stdout is not a tty; --no-raw forces formatted output |
| Cluster mode | redis-cli -c -p 7000 | Follows MOVED and ASK redirects |
| Scan keys | redis-cli --scan --pattern 'user:*' --count 500 | Uses SCAN, so it does not block the server; --count defaults to 10; never use KEYS in production |
| Big keys | redis-cli --bigkeys | Samples with SCAN; --memkeys reports memory |
| Latency | redis-cli --latency / --latency-history / --latency-dist | Round-trip from the client |
| Intrinsic latency | redis-cli --intrinsic-latency 5 | Run on the server host for 5 seconds |
| Stat stream | redis-cli --stat | Rolling keys, memory, clients, ops |
| Monitor | redis-cli MONITOR | Prints every command; heavy, short use only |
| Bulk load | cat cmds.txt | redis-cli --pipe | Protocol-mass insert |
| RDB from remote | redis-cli --rdb dump.rdb | Triggers a sync and saves the snapshot |
| Replay | redis-cli -r 5 -i 1 PING | -r repeat count, -i interval seconds |
| Help | HELP @sorted_set or HELP ZADD | Inside the shell |
| Cluster create | redis-cli --cluster create h1:7000 h2:7001 h3:7002 --cluster-replicas 1 | Also add-node and reshard; check, fix, rebalance not verified |
References: redis-cli, Commands.
Keys and expiry
| Task | Command | Notes |
|---|---|---|
| Exists, delete | EXISTS k, DEL k1 k2 | O(N) in keys; UNLINK k frees memory in the background |
| Set TTL (s / ms) | EXPIRE k 60, PEXPIRE k 60000 | Options NX, XX, GT, LT since 7.0; O(1) |
| Absolute expiry | EXPIREAT k 1767225600, PEXPIREAT | Unix time |
| Read TTL | TTL k, PTTL k | -1 no expiry, -2 key missing |
| Remove TTL | PERSIST k | O(1) |
| Expiry time | EXPIRETIME k | Absolute Unix time, 7.0+ |
| Rename | RENAME k k2, RENAMENX | Overwrites target; in Cluster both keys need one slot |
| Type | TYPE k | string, list, set, zset, hash, stream; the latest docs also list bitmap and vectorset |
| Iterate | SCAN 0 MATCH user:* COUNT 100 TYPE hash | Loop until cursor returns 0; may repeat keys |
| Collection scans | HSCAN, SSCAN, ZSCAN k cursor | Same cursor semantics |
| Encoding | OBJECT ENCODING k | listpack, quicklist, intset, hashtable, skiplist, embstr, int, raw |
| Idle, frequency | OBJECT IDLETIME k, OBJECT FREQ k | FREQ needs an LFU policy |
| Memory | MEMORY USAGE k SAMPLES 0 | Bytes including overhead; SAMPLES 0 means all elements |
| Copy | COPY src dst REPLACE | 6.2+ |
| Move DB | MOVE k 1 | Not for Cluster |
| Sort | SORT list BY weight_* LIMIT 0 10 GET obj_* | O(N log M); SORT_RO is read-only |
| Count keys | DBSIZE | O(1) |
| Wipe | FLUSHDB ASYNC, FLUSHALL ASYNC | Dangerous; rename or ACL-deny in production |
| Dump and restore | DUMP k then RESTORE k 0 payload REPLACE | Opaque serialized value; MIGRATE moves between servers |
| Wait for replicas | WAIT 1 100 | Replicas acked within 100 ms; returns the count |
References: Keyspace, Key eviction.
String
| Task | Command | Notes |
|---|---|---|
| Set | SET k v EX 60 NX | Options EX, PX, EXAT, PXAT, NX, XX, KEEPTTL, GET; O(1) |
| Get | GET k, MGET k1 k2, MSET k1 v1 k2 v2 | O(1), O(N) for multi-key |
| Get and delete or expire | GETDEL k, GETEX k EX 60 | O(1) |
| Counter | INCR k, INCRBY k 5, DECR k, INCRBYFLOAT k 1.5 | Atomic, O(1); value must be integer-like |
| Append | APPEND k s | O(1) amortized |
| Length, range | STRLEN k, GETRANGE k 0 -1, SETRANGE k 3 xx | O(1) and O(N) |
| Lock | SET lock:x token NX PX 30000 | Release only if token matches (Lua compare-and-delete) |
| Longest common | LCS a b LEN | 7.0+ |
Hash
| Task | Command | Notes |
|---|---|---|
| Set fields | HSET h f1 v1 f2 v2 | O(N) in pairs; HMSET is deprecated |
| Get | HGET h f, HMGET h f1 f2, HGETALL h | HGETALL is O(N), avoid on big hashes |
| Missing only | HSETNX h f v | O(1) |
| Delete, exists | HDEL h f, HEXISTS h f | O(1) per field |
| Counters | HINCRBY h f 1, HINCRBYFLOAT | O(1) |
| Keys, values, size | HKEYS, HVALS, HLEN | O(N), O(N), O(1) |
| Random | HRANDFIELD h 3 WITHVALUES | 6.2+ |
| Field TTL | HEXPIRE h 60 FIELDS 1 f, HTTL | Redis 7.4+ |
List
| Task | Command | Notes |
|---|---|---|
| Push | LPUSH l a b, RPUSH l a b | O(1) per element; LPUSHX only if exists |
| Pop | LPOP l 2, RPOP l | O(N) for N popped |
| Blocking pop | BLPOP l1 l2 5, BRPOP | Timeout seconds, 0 blocks forever |
| Move | LMOVE src dst LEFT RIGHT, BLMOVE | Replaces RPOPLPUSH; reliable queue pattern |
| Range | LRANGE l 0 -1 | O(S+N); avoid unbounded ranges |
| Index | LINDEX l 0, LSET l 0 v | O(N) |
| Length | LLEN l | O(1) |
| Trim | LTRIM l 0 99 | Capped list: LPUSH then LTRIM |
| Remove | LREM l 0 v | O(N+M); count 0 removes all |
| Insert | LINSERT l BEFORE pivot v | O(N) |
| Position | LPOS l v RANK 1 | O(N) |
| Multi-pop | LMPOP 2 l1 l2 LEFT COUNT 10 | 7.0+ |
Set
| Task | Command | Notes |
|---|---|---|
| Add, remove | SADD s a b, SREM s a | O(N) in elements |
| Member | SISMEMBER s a, SMISMEMBER s a b | O(1) per element |
| All, count | SMEMBERS s, SCARD s | O(N), O(1); prefer SSCAN for big sets |
| Random | SRANDMEMBER s 3, SPOP s 2 | O(N) for count |
| Algebra | SINTER a b, SUNION a b, SDIFF a b | Add STORE variants; SINTERCARD 2 a b LIMIT 10 |
| Move | SMOVE src dst m | O(1) |
Sorted set
| Task | Command | Notes |
|---|---|---|
| Add | ZADD z GT CH 10 a 20 b | O(log N) each; options NX, XX, GT, LT, CH, INCR; GT, LT and NX are mutually exclusive |
| Increment | ZINCRBY z 5 a | O(log N) |
| Score, rank | ZSCORE z a, ZRANK z a, ZREVRANK z a | O(1), O(log N) |
| Range (6.2 unified) | ZRANGE z 0 9 REV WITHSCORES | BYSCORE, BYLEX, LIMIT off n options |
| By score | ZRANGE z (10 +inf BYSCORE LIMIT 0 20 | ( makes the bound exclusive |
| Count | ZCARD z, ZCOUNT z 10 20 | O(1), O(log N) |
| Remove | ZREM z a, ZREMRANGEBYSCORE z 0 9, ZREMRANGEBYRANK z 0 -101 | O(log N + M) |
| Pop | ZPOPMIN z 3, BZPOPMIN z 5 | O(log N * M) |
| Algebra | ZUNIONSTORE out 2 a b WEIGHTS 1 2, ZINTERSTORE, ZDIFF | Aggregate SUM, MIN or MAX |
| Multi-pop | ZMPOP 2 a b MIN COUNT 5 | 7.0+ |
Stream
| Task | Command | Notes |
|---|---|---|
| Append | XADD s MAXLEN ~ 10000 * f v | * auto id; ~ approximate trim; O(1) |
| Read range | XRANGE s - + COUNT 10, XREVRANGE s + - | O(log N + M) |
| Read new | XREAD COUNT 10 BLOCK 5000 STREAMS s $ | $ means only new entries |
| Create group | XGROUP CREATE s g $ MKSTREAM | 0 starts from the beginning |
| Group read | XREADGROUP GROUP g c1 COUNT 10 BLOCK 5000 STREAMS s > | > delivers never-delivered entries |
| Ack | XACK s g id | Removes from the pending list |
| Pending | XPENDING s g - + 10 | Shows owner, idle time, delivery count |
| Claim | XAUTOCLAIM s g c2 60000 0-0 COUNT 10 | Take over idle messages (6.2+) |
| Trim, delete | XTRIM s MINID ~ id, XDEL s id | |
| Info | XLEN s, XINFO STREAM s, XINFO GROUPS s, XINFO CONSUMERS s g |
HyperLogLog, Bitmap, Geo
| Task | Command | Notes |
|---|---|---|
| HLL add | PFADD hll a b c | O(1); about 0.81% standard error, 12 KB max |
| HLL count | PFCOUNT hll1 hll2 | O(1) single key |
| HLL merge | PFMERGE out hll1 hll2 | O(N) |
| Set bit | SETBIT bm 7 1, GETBIT bm 7 | O(1) |
| Count bits | BITCOUNT bm 0 -1 BYTE | O(N); BIT unit since 7.0 |
| Bit ops | BITOP AND dest a b | AND, OR, XOR, NOT; O(N) |
| First bit | BITPOS bm 1 | O(N) |
| Bit fields | BITFIELD k INCRBY u8 0 1 OVERFLOW SAT | Packed counters |
| Geo add | GEOADD g 13.36 38.11 palermo | O(log N); stored in a sorted set |
| Distance | GEODIST g a b km | O(1) |
| Radius search | GEOSEARCH g FROMLONLAT 15 37 BYRADIUS 200 km ASC WITHDIST | Replaces GEORADIUS (6.2+); BYBOX also |
| Store search | GEOSEARCHSTORE dst g FROMMEMBER a BYRADIUS 50 km |
Pub/Sub
| Task | Command | Notes |
|---|---|---|
| Publish | PUBLISH ch msg | O(N + M); fire and forget, no persistence |
| Subscribe | SUBSCRIBE ch1 ch2, PSUBSCRIBE news.* | Connection enters subscriber mode |
| Unsubscribe | UNSUBSCRIBE, PUNSUBSCRIBE | |
| Sharded | SSUBSCRIBE ch, SPUBLISH ch msg | Cluster-scoped to a slot, 7.0+ |
| Introspect | PUBSUB CHANNELS, PUBSUB NUMSUB ch, PUBSUB NUMPAT | |
| Keyspace events | CONFIG SET notify-keyspace-events KEA | Then subscribe to __keyevent@0__:expired |
References: Data types, Commands by group.
Transactions, scripting and Functions
| Task | Command | Notes |
|---|---|---|
| Transaction | MULTI ... EXEC | Queued, run atomically; no rollback on runtime errors |
| Abort | DISCARD | |
| Optimistic lock | WATCH k then MULTI ... EXEC | EXEC returns nil if k changed |
| Unwatch | UNWATCH | |
| Eval | EVAL "return redis.call('GET', KEYS[1])" 1 k | Declare all keys in KEYS for Cluster |
| Cached script | SCRIPT LOAD src, EVALSHA sha 1 k | On NOSCRIPT, reload and retry |
| Script admin | SCRIPT EXISTS sha, SCRIPT FLUSH | |
| Read-only eval | EVAL_RO, EVALSHA_RO | Safe on replicas |
| Functions | FUNCTION LOAD "#!lua name=lib\nredis.register_function('f', function(keys, args) return 1 end)" | 7.0+; persisted and replicated |
| Call function | FCALL f 1 k arg, FCALL_RO | |
| Function admin | FUNCTION LIST, FUNCTION DELETE lib, FUNCTION DUMP, FUNCTION RESTORE | |
| Pipeline | Client batches commands without MULTI | Saves round trips, not atomic |
Lua compare-and-delete lock release:
if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 endReferences: Transactions, Lua scripting, Functions.
Persistence and CONFIG
| Task | Command | Notes |
|---|---|---|
| Read config | CONFIG GET maxmemory* | Glob patterns |
| Set at runtime | CONFIG SET maxmemory 2gb | Not persisted by itself |
| Persist to file | CONFIG REWRITE | Writes back to redis.conf |
| RDB trigger | BGSAVE, SAVE | SAVE blocks; avoid it |
| RDB schedule | save 3600 1 300 100 60 10000 | Config: seconds and changes; this is the default per the current redis.conf |
| Last save | LASTSAVE | Unix time |
| AOF enable | appendonly yes | Config, Redis also supports a multi-part AOF since 7.0 |
| AOF fsync | appendfsync everysec | always, everysec, no |
| AOF rewrite | BGREWRITEAOF | Compacts the log; also automatic via auto-aof-rewrite-percentage |
| Hybrid | aof-use-rdb-preamble yes | RDB header plus AOF tail |
| Check files | redis-check-aof --fix file | Offline AOF repair; redis-check-rdb is not verified |
| Shutdown | SHUTDOWN NOSAVE or SHUTDOWN SAVE | |
| Reset stats | CONFIG RESETSTAT | |
| Data dir | CONFIG GET dir | Also 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
| Task | Command | Notes |
|---|---|---|
| Make replica | REPLICAOF host 6379 | REPLICAOF NO ONE promotes; SLAVEOF is deprecated |
| Role | ROLE | master or replica with offsets |
| Replication info | INFO replication | master_repl_offset, connected_slaves, lag |
| Backlog | repl-backlog-size 64mb | Larger avoids full resync after short outages |
| Require replicas | min-replicas-to-write 1, min-replicas-max-lag 10 | Refuse writes when replicas lag |
| Failover | FAILOVER TO host port | Coordinated switch, 6.2+ |
| Sentinel masters | SENTINEL masters, SENTINEL get-master-addr-by-name mymaster | Run against port 26379 |
| Sentinel failover | SENTINEL failover mymaster | Forces a failover |
| Sentinel health | SENTINEL ckquorum mymaster | Checks quorum |
| Cluster info | CLUSTER INFO, CLUSTER NODES, CLUSTER SHARDS | cluster_state:ok expected |
| Slot of a key | CLUSTER KEYSLOT k | CRC16 mod 16384; hash tags {user:1}:a colocate keys |
| Slot owner | CLUSTER SLOTS | Deprecated since 7.0; prefer CLUSTER SHARDS |
| Manual failover | CLUSTER FAILOVER (on a replica) | Option FORCE or TAKEOVER |
| Add node | redis-cli --cluster add-node new existing | |
| Move slots | redis-cli --cluster reshard host:port | Moves slots; see the cluster tutorial |
| Forget | CLUSTER FORGET node-id | Run on every node; sets a 60-second ban on re-adding that node ID |
| Read from replica | READONLY | Per connection, cluster replicas only |
References: Replication, Sentinel, Cluster spec.
ACL and security
| Task | Command | Notes |
|---|---|---|
| Create user | ACL SETUSER app on >secret ~app:* &* +@read +@write -@dangerous | on, >password, ~keypattern, &channel, +@category |
| Command rule | +get +set -flushall | Allow or deny single commands; +config|get for subcommands |
| Key permissions | %R~cache:* %W~out:* | Read-only and write-only key patterns, 7.0+ |
| List | ACL LIST, ACL USERS, ACL GETUSER app | |
| Who am I | ACL WHOAMI | |
| Categories | ACL CAT, ACL CAT dangerous | |
| Delete | ACL DELUSER app | |
| Persist | ACL SAVE, ACL LOAD | Needs aclfile in config |
| Audit | ACL LOG, ACL LOG RESET | Recent denials |
| Authenticate | AUTH user pass | AUTH pass targets default |
| Disable default | ACL SETUSER default off | After creating real users |
| Bind and protect | bind 10.0.0.5, protected-mode yes | Never expose Redis to the internet |
| TLS | tls-port 6380, tls-cert-file, tls-key-file, tls-ca-cert-file | Set port 0 to disable plaintext |
| Hide commands | rename-command is legacy | Prefer ACL |
INFO sections and diagnostics
| Task | Command | Notes |
|---|---|---|
| All stats | INFO or INFO all | Sections: server, clients, memory, persistence, stats, replication, cpu, commandstats, cluster, keyspace |
| Hit ratio | INFO stats | keyspace_hits, keyspace_misses, evicted_keys, expired_keys |
| Memory | INFO memory | used_memory, used_memory_rss, mem_fragmentation_ratio, maxmemory |
| Per command | INFO commandstats | calls, usec_per_call |
| Keys per DB | INFO keyspace | keys, expires, avg_ttl |
| Clients | CLIENT LIST, CLIENT KILL ID n, CLIENT SETNAME app | INFO clients has blocked_clients |
| Slow log | SLOWLOG GET 10, SLOWLOG LEN, SLOWLOG RESET | Threshold slowlog-log-slower-than 10000 microseconds |
| Latency events | LATENCY LATEST, LATENCY HISTORY command, LATENCY DOCTOR | Needs latency-monitor-threshold 100 |
| Latency graph | LATENCY GRAPH command | ASCII chart |
| Memory doctor | MEMORY DOCTOR, MEMORY STATS, MEMORY PURGE | |
| Big keys | MEMORY USAGE k, redis-cli --bigkeys | |
| Ping, time | PING, TIME | |
| Command docs | COMMAND DOCS get, COMMAND COUNT |
References: INFO, Latency monitoring, Slow log.
Eviction policies
| Policy | Evicts | Notes |
|---|---|---|
noeviction | Nothing; writes fail with OOM | Default; right for queues and primary data |
allkeys-lru | Least recently used, any key | Good general cache |
allkeys-lrm | Least recently modified, any key | Redis 8.6+; reads do not refresh it |
allkeys-lfu | Least frequently used, any key | Better for skewed popularity, 4.0+ |
allkeys-random | Random key | |
volatile-lru | LRU among keys with a TTL | Keys without TTL stay |
volatile-lrm | LRM among keys with a TTL | Redis 8.6+ |
volatile-lfu | LFU among keys with a TTL | |
volatile-random | Random among keys with a TTL | |
volatile-ttl | Shortest 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
| Error | Cause | Fix |
|---|---|---|
WRONGTYPE Operation against a key holding the wrong kind of value | Command does not match the key type | Check TYPE k; fix key naming |
MOVED 3999 host:6381 | Cluster key lives on another node | Use a cluster-aware client or redis-cli -c |
ASK 3999 host:6381 | Slot is migrating | Client sends ASKING then retries |
CROSSSLOT Keys in request don't hash to the same slot | Multi-key command spans slots | Use hash tags {id} |
OOM command not allowed when used memory > 'maxmemory' | Memory full with noeviction | Raise maxmemory, set eviction, add TTLs |
NOAUTH Authentication required | No password supplied | AUTH or fix the URL |
WRONGPASS invalid username-password pair or user is disabled. | Bad credentials or disabled user | Check the ACL user |
NOPERM User app has no permissions to run the 'x' command | ACL denial | ACL LOG, adjust rules |
READONLY You can't write against a read only replica | Writing to a replica or after failover | Connect to the primary; use Sentinel-aware client |
LOADING Redis is loading the dataset in memory | Startup or full sync | Retry with backoff |
BUSY Redis is busy running a script | Long Lua script | SCRIPT KILL or FUNCTION KILL |
MISCONF Redis is configured to save RDB snapshots | BGSAVE failing (disk or permissions) | Fix disk; check logs; stop-writes-on-bgsave-error |
ERR max number of clients reached | maxclients hit | Pool connections; raise limit and ulimit -n |
EXECABORT Transaction discarded because of previous errors | Syntax error while queueing | Fix the command and retry |
NOSCRIPT No matching script | EVALSHA on a cold cache | SCRIPT LOAD then retry |
References: Cluster spec, ACL, Redis source, error replies, redis.conf.
Go (go-redis) and Laravel
| Task | Snippet | Notes |
|---|---|---|
| Go connect | rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379", PoolSize: 20}) | github.com/redis/go-redis/v9 |
| Go URL | opt, _ := redis.ParseURL("redis://user:pass@h:6379/0") | Then redis.NewClient(opt) |
| Go set and get | rdb.Set(ctx, "k", "v", time.Minute), rdb.Get(ctx, "k").Result() | Missing key returns redis.Nil |
| Go pipeline | pipe := rdb.Pipeline(); pipe.Incr(ctx, "n"); _, err := pipe.Exec(ctx) | TxPipeline wraps MULTI and EXEC |
| Go watch | rdb.Watch(ctx, func(tx *redis.Tx) error { ... }, "k") | Returns redis.TxFailedErr on conflict |
| Go script | redis.NewScript(src).Run(ctx, rdb, []string{"k"}, arg) | Handles EVALSHA and fallback |
| Go cluster | redis.NewClusterClient(&redis.ClusterOptions{Addrs: []string{"h1:7000"}}) | Follows MOVED automatically |
| Go Sentinel | redis.NewFailoverClient(&redis.FailoverOptions{MasterName: "mymaster", SentinelAddrs: addrs}) | |
| Laravel env | REDIS_CLIENT=phpredis, REDIS_HOST, REDIS_PASSWORD, REDIS_PORT, REDIS_DB | predis is the pure PHP client |
| Laravel facade | Redis::set('k', 'v'), Redis::get('k'), Redis::connection('cache')->incr('n') | Connections in config/database.php under redis |
| Laravel pipeline | Redis::pipeline(function ($pipe) { $pipe->set('a', 1); }) | |
| Laravel pub/sub | Redis::subscribe(['ch'], fn ($m) => ...), Redis::publish('ch', $msg) | |
| Laravel cache | CACHE_STORE=redis, Cache::remember('k', 600, fn () => ...) | Cache::lock('x', 10)->get() for locks |
| Laravel queue | QUEUE_CONNECTION=redis, php artisan queue:work redis --queue=default | Horizon manages workers |
| Laravel session | SESSION_DRIVER=redis | |
| Laravel throttle | Redis::throttle('k')->allow(10)->every(60)->then(fn () => ..., fn () => ...) | Rate limiting helper |
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.