📡 You're offline — showing cached content
New version available!
Quick Access
Redis Reference

Redis

In-memory data structures, caching strategies, pub/sub, and persistence.

All Topics

Core Data Types

SET key value EX 3600
Set a string key with an expiry of 3600 seconds (TTL). Use NX to set only if not exists.
Example: SET session:abc "userData" EX 3600 NX
MSET / MGET
Set/Get multiple keys atomically in one round-trip — critical for performance.
Example: MSET k1 v1 k2 v2; MGET k1 k2
INCR / INCRBY / DECR
Atomic integer increment/decrement — perfect for counters, rate limits, and sequences.
Example: INCR visits:2024-01-01; INCRBY balance 500
HSET / HGET / HGETALL
Hash — store structured object fields. More memory-efficient than separate keys.
Example: HSET user:1 name "Alice" age 30; HGETALL user:1
LPUSH / RPUSH / LRANGE
List — push to left/right end / retrieve a range. Powers queues and activity feeds.
Example: LPUSH jobs "task1"; LRANGE jobs 0 -1
SADD / SMEMBERS / SINTER
Set — unique unordered members. SINTER finds intersection. SUNION merges sets.
Example: SADD tags:post1 php redis; SINTER tags:post1 tags:post2

Sorted Sets & Leaderboards

ZADD key score member
Add member with a float score. Auto-sorted. Perfect for rankings, priorities, and timelines.
Example: ZADD leaderboard 4200 "alice" 3800 "bob"
ZRANGE / ZREVRANGE
Retrieve members sorted ascending/descending. Add WITHSCORES for scores.
Example: ZREVRANGE leaderboard 0 9 WITHSCORES
ZRANK / ZREVRANK
Get the rank (0-indexed) of a member in ascending/descending order.
Example: ZREVRANK leaderboard "alice" // returns 0 (top)
ZINCRBY key amount member
Atomically increment a member's score — ideal for real-time score updates.
Example: ZINCRBY leaderboard 50 "alice"
ZRANGEBYSCORE key min max
Get members within a score range. Use -inf and +inf for open bounds.
Example: ZRANGEBYSCORE events 1700000000 +inf LIMIT 0 20
ZPOPMIN / ZPOPMAX
Atomically remove and return the member with the lowest/highest score.
Example: ZPOPMIN priority_queue 1 // dequeue next task

Caching Patterns

SETNX / SET NX EX
Distributed lock pattern — set key only if Not eXists, with expiry to prevent deadlocks.
Example: SET lock:job1 "worker1" NX EX 30
EXPIRE / EXPIREAT / TTL
Set expiry in seconds / at UNIX timestamp / check remaining TTL (-1 = no expiry, -2 = gone).
Example: TTL session:abc; EXPIREAT cache:menu 1735689600
PERSIST key
Remove TTL from a key — make it persistent indefinitely.
Example: PERSIST config:settings
OBJECT ENCODING key
Inspect internal Redis encoding — helps tune memory (ziplist vs hashtable etc.).
Example: OBJECT ENCODING user:1 // "ziplist" or "hashtable"
SCAN cursor MATCH pattern
Cursor-based iteration over keys — never use KEYS * in production (blocks server).
Example: SCAN 0 MATCH "session:*" COUNT 100
maxmemory / eviction policy
Configure max memory and eviction strategy (allkeys-lru is most common for cache).
Example: CONFIG SET maxmemory-policy allkeys-lru

Pub/Sub & Streams

PUBLISH channel message
Publish a message to a channel — all SUBSCRIBE listeners receive it instantly.
Example: PUBLISH notifications "{\"type\":\"order\",\"id\":42}"
SUBSCRIBE / PSUBSCRIBE
Subscribe to specific channels / subscribe to pattern (e.g., events.*).
Example: PSUBSCRIBE "order.*" // matches order.paid, order.shipped
XADD / XREAD (Streams)
Append entries to a persistent stream / read new entries. Redis Streams = durable Pub/Sub.
Example: XADD events * action "login" user "alice"
XGROUP CREATE / XREADGROUP
Consumer groups allow multiple workers to share stream processing (like Kafka consumers).
Example: XGROUP CREATE events mygroup $ MKSTREAM
XACK stream group id
Acknowledge a message has been processed — removes it from the pending list.
Example: XACK events mygroup 1700000000000-0
XLEN / XRANGE / XTRIM
Count entries / read range / trim stream to MAXLEN — prevents unbounded growth.
Example: XTRIM events MAXLEN ~ 10000

Scripting & Transactions

MULTI / EXEC / DISCARD
Begin / commit / discard a transaction block. All commands run atomically.
Example: MULTI; INCR views; ZADD timeline 100 post1; EXEC
WATCH key
Optimistic locking — EXEC returns nil if watched key changed (retry logic needed).
Example: WATCH balance; MULTI; DECRBY balance 100; EXEC
EVAL script numkeys keys args
Execute a Lua script atomically — powerful for complex operations without race conditions.
Example: EVAL "return redis.call('GET', KEYS[1])" 1 mykey
PIPELINE
Client-side batching — send multiple commands without waiting for each reply (huge speedup).
Example: pipe = r.pipeline(); pipe.set('a',1); pipe.get('a'); pipe.execute()
DEBUG SLEEP / OBJECT FREQ
Test tools: simulate latency / inspect access frequency for LFU eviction tuning.
Example: OBJECT FREQ mykey // requires maxmemory-policy *-lfu
INFO server / INFO stats
Comprehensive server diagnostics — memory usage, hit rate, connected clients, etc.
Example: INFO stats | grep keyspace_hits

Persistence & Replication

RDB (snapshot) vs AOF
RDB: periodic snapshots (fast restore, data loss risk). AOF: every-write log (durable, slower).
Example: appendonly yes; appendfsync everysec // AOF config
BGSAVE / BGREWRITEAOF
Trigger background RDB save / compact the AOF file without blocking the server.
Example: BGSAVE; LASTSAVE // check time of last successful save
REPLICAOF host port
Make this Redis instance a replica of another (for read scaling and failover).
Example: REPLICAOF 192.168.1.10 6379
Redis Sentinel
HA monitoring — auto-failover: promotes replica to master if master goes down.
Example: sentinel monitor mymaster 127.0.0.1 6379 2
Redis Cluster
Horizontal sharding across 16384 hash slots — data split across multiple nodes.
Example: cluster-enabled yes; cluster-config-file nodes.conf
ACL SETUSER / ACL LIST
Fine-grained access control — restrict users to specific commands and key patterns.
Example: ACL SETUSER api on >secret ~cache:* +GET +SET