🏆
Lesson 4 of 4 · Sorted Sets
Always-ranked data — for free
Redis keeps members sorted by score as you write them. Reads are always instant.
🔴 The problem at scale

You have 1 million players and need to show the top 100 by score. In a SQL database that's: SELECT * FROM players ORDER BY score DESC LIMIT 100. Sorting 1 million rows on every page load gets painfully slow as you grow.

Redis Sorted Sets maintain the order as you write each score. The top-100 read is always O(log N) — fast whether you have 100 or 100 million players.

Top 5 of 5 players
5 total members
#PlayerScore
🥇 carol
1,450
🥈 alice
1,200
🥉 eve
1,100
4 bob
980
5 dave
670
🧪 Add or update a score

Try submitting a name that already exists — Redis will update the score, not duplicate the entry. Then check where they appear in the ranking.

💻 The commands powering this leaderboard
redis> ZADD demo:leaderboard 1500 "alice"
→ 1 (added) or 0 (updated score)
Adds "alice" with score 1500. If alice already exists, her score is updated.
Redis re-sorts immediately — O(log N) insert.
redis> ZREVRANGE demo:leaderboard 0 9 WITHSCORES
→ ["carol","1450","alice","1200","eve","1100","bob","980","dave","670"]
Returns top 10 members, highest score first, with their scores.
REV = reversed (highest first). Range 0–9 = first 10 results.
redis> ZREVRANK demo:leaderboard "alice"
→ 1 ← alice is rank #2 (0-indexed from the top)
redis> ZCARD demo:leaderboard
→ 5 ← total number of members
💡 The key insight — sorted on write, not on read

Every time you call ZADD, Redis inserts the member into a skip list data structure that is always sorted. Reading the top-N is never a sort operation — it's just walking a pre-ordered list. The leaderboard stays fast forever.

🌍 Where you've seen this

Fortnite and Call of Duty real-time kill leaderboards. Duolingo weekly XP rankings that reset every Sunday. Hacker News story rankings (votes minus time decay = score). Any time you see a live "top N" list updating in real time, Redis is probably behind it.