All cheatsheets

Cheatsheets

Redis

Data types, TTL & eviction, caching patterns, locks, streams, and persistence.

Visualize

Redis — key expiry (TTL)

Keys set with EX expire when their countdown hits zero; a GET then returns nil.

clock: 0s
session:ab12
user=42
8s
cart:99
[3 items]
5s
otp:777
294117
3s
SET key val EX 30 live expiring

Each key has a TTL — press play to run the clock forward.

52 entries

Strings6

SET key value

Set a string value (overwrites, clears TTL unless KEEPTTL).

GET key

Read a string value (nil if missing).

SETEX key seconds value

Set a value with a TTL atomically.

INCR key / DECR key

Atomic +1 / -1 on an integer string.

APPEND key value

Append to a string, returns new length.

MSET k1 v1 k2 v2 / MGET k1 k2

Set/get multiple keys in one round trip.

Hashes3

HSET key field value [field value ...]

Set one or more fields of a hash.

HGET key field / HGETALL key

Read one field, or the whole hash as field/value pairs.

HINCRBY key field n

Atomically add to a numeric hash field.

Lists (queues)4

LPUSH / RPUSH key value [value ...]

Push onto the head (L) or tail (R) of a list.

LPOP / RPOP key [count]

Pop element(s) from the head/tail.

BRPOP key [key ...] timeout

Blocking pop — wait for an element instead of polling.

LRANGE key start stop / LTRIM key start stop

Read a slice / trim a list to a slice (capped list).

Sets & sorted sets6

SADD key member [member ...]

Add member(s) to an unordered set of unique strings.

SINTER / SUNION / SDIFF key [key ...]

Set algebra: intersection, union, difference.

ZADD key score member [score member ...]

Add member(s) to a sorted set, ranked by score.

ZRANGE / ZREVRANGE key start stop [WITHSCORES]

Read members by rank (position), low-to-high or high-to-low.

ZRANGEBYSCORE key min max

Read members whose score falls in a range.

ZRANK / ZREVRANK key member

Get the 0-based rank of a member (low/high first).

Streams, bitmaps, HLL & geo6

XADD stream * field value [field value ...]

Append an entry to a stream; '*' auto-generates an ID.

XREAD COUNT n BLOCK ms STREAMS key id

Read new entries after an ID; optionally block for new ones.

XGROUP CREATE + XREADGROUP + XACK

Consumer groups: distribute entries across workers with acks.

SETBIT key offset 0|1 / BITCOUNT key

Bitmap: set a single bit; count set bits.

PFADD key element [element ...] / PFCOUNT key

HyperLogLog: approximate unique-count in ~12 KB.

GEOADD key lon lat member / GEOSEARCH

Geospatial index: store points, query by radius/box.

Expiry & eviction6

EXPIRE key seconds / PEXPIRE key ms

Attach a TTL to an existing key (seconds / milliseconds).

TTL key / PTTL key

How long until a key expires (seconds / ms).

PERSIST key

Remove a key's TTL, making it permanent again.

How Redis expires keys: lazy + active

Expiry is not instantaneous — two mechanisms reclaim memory.

CONFIG SET maxmemory 2gb

Cap memory so Redis acts as a bounded cache.

maxmemory-policy: choosing an eviction policy

What Redis discards when memory is full — pick by workload.

Caching patterns5

Cache-aside (lazy loading / read-through)

App checks cache; on miss, loads from DB and backfills.

Write-through vs write-behind

When to update the cache on writes — sync vs async.

Cache invalidation (DEL / SET on write)

Keep the cache correct after the source of truth changes.

Cache stampede / thundering herd

Many clients miss the same key at once and all hit the DB.

Hot-key problem

One key gets so much traffic it saturates a single shard.

Concurrency & messaging6

SET key token NX PX 30000 (distributed lock)

Acquire a lock atomically: set only if absent, with a TTL.

Unlock via Lua (compare-and-delete)

Release a lock ONLY if you still own it — atomically.

MULTI / EXEC / WATCH (optimistic transaction)

Queue commands and run them atomically; WATCH aborts on conflict.

EVAL (Lua) vs pipelining — atomic vs throughput

Lua runs atomic server-side logic; pipelining just batches RTTs.

PUBLISH / SUBSCRIBE (Pub/Sub)

Fire-and-forget broadcast to currently-connected subscribers.

Pub/Sub vs Streams — which messaging primitive?

Ephemeral broadcast vs durable, replayable log with groups.

Persistence & durability4

RDB snapshots (SAVE / BGSAVE)

Point-in-time binary dumps of the whole dataset.

AOF (appendonly + appendfsync)

Append-only log of every write; replayed on restart.

Replication (replicaof)

Async copies of a primary for read scaling and failover.

Sentinel vs Cluster

HA failover (Sentinel) vs horizontal sharding (Cluster).

Observability & ops6

SCAN cursor MATCH pattern COUNT n (NEVER KEYS in prod)

Incrementally iterate keys without blocking the server.

INFO [section]

Server stats: memory, clients, persistence, replication, stats.

SLOWLOG GET [n] / SLOWLOG RESET

Log of commands that exceeded a latency threshold.

MONITOR (DANGER: kills throughput in prod)

Stream every command the server processes — debug only.

MEMORY USAGE key / OBJECT ENCODING key

Bytes used by a key, and its internal encoding.

Keyspace notifications (CONFIG notify-keyspace-events)

Get Pub/Sub events when keys change or expire.