AI Hints
Home›System Design Tutorial›Redis and Cache Layers
System Design · Lesson 61 of 120

Redis

The Swiss army cache.

⏱ 2 min read▶ Video at 1:12:37🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

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.

Redis
From the video: Redis
  • 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.

TypeGood for
Stringcached values, counters
Hashsessions, objects
Listsimple queues
Setunique items, online users
Sorted setleaderboards, 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.

leaderboard.pypython
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)
Output
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
Next up: Layers of Caching — from browser to database