Redis
The Swiss army cache.
Redis is the cache you'll meet most often. It's an in memory data store, shared by all your servers, and it's extremely fast. But it's more than a simple key value cache.

- In-memory, shared
- Extremely fast
- More than key-value
Redis data types
Redis has several data types, each useful for a different job. Strings hold cached values and counters. Hashes hold objects, like a session. Lists act as simple queues. Sets hold unique items, like online users. And sorted sets keep items in order by score, which is perfect for leaderboards and rankings.
| Type | Good for |
|---|---|
| String | cached values, counters |
| Hash | sessions, objects |
| List | simple queues |
| Set | unique items, online users |
| Sorted set | leaderboards, rankings |
A sorted set, by hand
Let's mimic a sorted set, the most famous Redis feature. Each product has a score, its sales today. Adding a sale updates the score, and the top three come back in order. Run it. In Redis, this is a couple of commands, z incr by and z rev range, and it stays fast with millions of items.
sales = {}
def zincrby(item, amount=1):
sales[item] = sales.get(item, 0) + amount
for item in ["mug", "pot", "mug", "towel", "mug", "pot", "lamp"]:
zincrby(item)
top3 = sorted(sales.items(), key=lambda kv: -kv[1])[:3]
for rank, (item, score) in enumerate(top3, 1):
print(rank, item, score)1 mug 3 2 pot 2 3 towel 1
Summary
Redis is a shared, in memory store with useful types, like hashes, sets, and sorted sets. It's a cache, a session store, a counter, and a leaderboard. Next, all the places a cache can sit.
Key takeaways- In memory, shared
- Many data types
- Sorted sets for rankings