Redis Tutorial
In-memory data with Redis — strings, hashes, lists, sets, and caching patterns.
Redis is an in-memory data store used for caching, sessions, queues, and real-time counters.
Strings and expiry
SET views:home 0
INCR views:home
EXPIRE views:home 3600 # cache for 1 hour
GET views:home
Hashes
HSET user:1 name "Ada" plan "pro"
HGET user:1 name
HGETALL user:1
Lists and sets
LPUSH tasks "send-email"
RPOP tasks # pop from the right
SADD online user:1 user:2
SCARD online # count of online users
Caching pattern
import redis, json
r = redis.Redis()
def get_user(uid):
key = f"user:{uid}"
cached = r.get(key)
if cached:
return json.loads(cached)
user = db_query(uid) # expensive
r.set(key, json.dumps(user), ex=300)
return user
| Structure | Best for |
|---|---|
| String | counters, cache values |
| Hash | object fields |
| List | queues, timelines |
| Set | unique membership, tags |
Set a sensible
EX(expiry) on caches so stale data eventually refreshes.