2 · REDIS · LEADERBOARD
← Lesson 1: Leaderboard
▶ Run: P6
▶ SQL Comparison: P7
Leaderboard on a sorted set
ZADD leaderboard:season:7 1500 player:1042
ZINCRBY leaderboard:season:7 25 player:1042
Atomic, but a repeat is +25 more
ZRANGE leaderboard:season:7 0 9 REV WITHSCORES
Top 10: limits are inclusive; N=0 — empty in the code
ZREVRANK leaderboard:season:7 player:1042
Starting from zero; `nil` — no player
Compare against the index, not the sorted order.
PostgreSQL’s B-tree is updated incrementally; a top-10 index query is efficient. An exact rank may be more expensive—measure it (P7).
Redis: insert and rank are O(log N), range is O(log N + M). The cost is memory, synchronization, and recovery.
TRAP
"EARLIER — HIGHER"
REMEMBER
Tie: member bytes
Not a note in the score
This is derived data
Equal score → sorted by member bytes; with REV, the order is reversed. Not by nickname or time.
SQL: rating DESC, achieved_at ASC, player_id ASC. The double data type won't be precise enough.
source of truth—matches in PostgreSQL. Loss—recalculation and catching up with new matches.
First check for nil, then check for rank + 1. The ZINCRBY iteration is not idempotent: you need to deduplicate by match ID or absolute rating with version. Runs on P6 and P7.
▶ P12: SET NX