Redis Basics

In-memory data store. Keys to strings, hashes, lists, sets, sorted sets. Durable to disk. Sub-ms latency. Swiss army knife for caching, queues, counters, locks.

1 credit

Data types (what you'll use)

7 items
String
`SET key value` / `GET key` / `INCR counter` — atomic counter
Hash
`HSET user:1 name Alice age 30` — tiny record, cheaper than JSON+SET
List
`LPUSH queue job` / `BRPOP queue 0` — blocking pop = simple queue
Set
`SADD tags ssd ram` / `SINTER` — unique members, set math
Sorted set (zset)
`ZADD lb 100 alice` / `ZRANGE lb 0 9 WITHSCORES` — leaderboards, time-ordered feeds
Stream
`XADD events * k v` / `XREAD` — append-only log, Kafka-lite
Pub/Sub
`PUBLISH ch msg` / `SUBSCRIBE ch` — fanout, no persistence

Caching pattern

text
GET cache:user:42
  MISS → SELECT * FROM users WHERE id = 42
         SET cache:user:42 <json> EX 300   (5-min TTL)
  HIT  → parse + return

Always set TTL on cache keys. "Cache forever" keys are how stale data ships.

Operational

5 items
Check memory
INFO memory
Biggest keys
redis-cli --bigkeys
Live commands
redis-cli MONITOR (don't do this in prod — blocks)
TTL on key
TTL key (seconds remaining; -1 no expiry; -2 gone)
Find keys matching
SCAN 0 MATCH user:* COUNT 1000 (NEVER use KEYS — blocks)

Pitfalls

  • Single-threaded — one slow command (big SORT, KEYS *) blocks everything.
  • Not a durable database. Use for cache / queue / ephemeral state; keep source of truth in Postgres.
  • Unbounded keys = OOM — set TTL or use `maxmemory-policy allkeys-lru`.
  • Replication + sentinel for HA — single-node Redis in prod = guaranteed outage eventually.

Further reading