iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Cheatsheet

A condensed reference for the Redis commands and patterns you actually use day-to-day: data types, TTL, atomic ops, pub/sub, transactions, persistence, and the decision matrix between cache, queue, store, and lock. Keep it open during design review.

Redis decisions and commands in one page

EXAMPLE
# ===== Data types — pick by access pattern =====
# string    GET, SET, INCR             counters, simple cache, locks, JSON blobs
# list      LPUSH, RPOP, LRANGE         queues, recent activity feed
# hash      HSET, HGET, HGETALL         per-entity bags of fields (session)
# set       SADD, SISMEMBER, SUNION     unique members, tag clouds
# zset      ZADD, ZRANGE, ZRANGEBYSCORE leaderboards, time-series, schedules
# stream    XADD, XREADGROUP            durable queues with consumer groups
# hyperll   PFADD, PFCOUNT              approx unique counts (cheap)
# geo       GEOADD, GEOSEARCH           store finders, dispatch

# ===== Expiry / TTL =====
SET key value EX 60                # set with 60s TTL
EXPIRE key 60                      # set TTL on existing
PERSIST key                        # remove TTL
TTL key                            # seconds remaining (-1 no TTL, -2 missing)
PEXPIRE key 1500                   # ms precision

# ===== Atomic conditional set (locks, idempotency) =====
SET lock:o1 $token NX PX 5000      # set only if missing; auto-expire 5s
GETEX key EX 60                    # get + refresh TTL atomically (7+)
SETNX                              # legacy; SET NX is the modern way

# ===== Transactions and atomic scripts =====
MULTI / EXEC                       # queued + executed atomically
WATCH key                          # optimistic check; abort EXEC if changed
EVAL '...lua...' 1 KEY ARG         # single round trip, atomic across keys

# ===== Pub/Sub vs Streams =====
PUBLISH ch 'msg'  +  SUBSCRIBE ch  # fire-and-forget; no replay; no consumer groups
XADD events * field val            # durable; XREADGROUP for at-least-once with ACK
# Default to Streams for inter-service messaging; Pub/Sub for fan-out notifications.

# ===== Patterns by intent =====

# Cache (read-through)
#   GET key  -> if miss, fill from DB, SET key val EX 300

# Rate limit (fixed window)
#   INCR rl:ip:bucket  + EXPIRE 60   -> reject when count > N

# Rate limit (sliding)
#   ZADD slide:user now id; ZREMRANGEBYSCORE 0 now-window; ZCARD; PEXPIRE

# Leaderboard
#   ZADD lb:weekly score user; ZREVRANGE lb:weekly 0 9 WITHSCORES

# Distributed lock (single node)
#   SET lock:res token NX PX 5000; release with a Lua CAS

# Idempotency key
#   SET idem:$key '1' NX EX 86400 -> reject duplicate requests

# Session store
#   HSET sess:$id k v; EXPIRE sess:$id 1209600

# Job queue (light)
#   LPUSH q:work job; BRPOP q:work 0
#   (Use a real broker — Sidekiq, BullMQ, Resque — for retries / DLQs)

# ===== Persistence =====
# RDB    point-in-time snapshot      (save 900 1)
# AOF    append-only log of writes   (appendonly yes; appendfsync everysec)
# Both   recommended in production    (RDB for speed of restore, AOF for durability)

# ===== Memory hygiene =====
maxmemory 4gb
maxmemory-policy allkeys-lru        # evict the least recently used key
CONFIG SET maxmemory-policy allkeys-lru
MEMORY USAGE key
--bigkeys                           # find the largest keys at the CLI

# ===== Observability =====
INFO memory / replication / stats
SLOWLOG GET 10
LATENCY HISTORY event
CLIENT LIST
MONITOR    # NEVER in production for long — serialises traffic

# ===== Security =====
# - ACL: users with the minimum command surface (+@read +@write -flushall)
# - TLS for client + replication
# - bind to private IPs, no public exposure
# - rename-command CONFIG "" / FLUSHALL ""

# ===== Decision matrix =====
# cache?   -> Redis as cache, TTL on every key, ok to lose
# queue?   -> Streams (durable) or a real broker (Sidekiq/SQS) for big workloads
# store?   -> only if dataset fits in memory comfortably AND you accept the durability story
# lock?    -> SET NX PX + Lua release; Redlock only for multi-master setups

Why it matters

Default to "use Redis as a cache or coordinate ephemeral state; not as a database." The moment you persist business-critical data in Redis without a clear durability story (RDB cadence, AOF, replication, off-host backups), one accidental FLUSHALL or one OOM eviction policy mismatch ends an afternoon — and sometimes a quarter.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# String INCR | List PUSH POP | Hash HSET HGET | Set SADD SMEMBERS | ZSet ZADD ZRANGE | TTL EXPIRE
Try it Yourself »

Discussion

Loading…