ZADD and ZRANGE
Wordcraft's leaderboard changes every few seconds as games finish, and every player's screen shows the top of it. Sorting all players by score on every page view would be slow. A sorted set keeps them in order all the time, so reading the top is instant.
The rule
ZADD gives each member a score; ZRANGE reads them lowest first.
A sorted set holds unique members, each with a number called its score. Redis keeps the members ordered by score at all times. (Its type name is zset, which is why every command starts with Z.)
127.0.0.1:6379> ZADD leaderboard 320 asha 150 ravi 410 meera 90 tom
(integer) 4
127.0.0.1:6379> ZRANGE leaderboard 0 -1
1) "tom"
2) "ravi"
3) "asha"
4) "meera"
127.0.0.1:6379> ZRANGE leaderboard 0 1 REV WITHSCORES
1) "meera"
2) "410"
3) "asha"
4) "320"ZADD key score member [score member ...]: note the score comes first. The reply counts members that were added; changing an existing member's score does not count.ZRANGE key start stopreturns members by position, lowest score first. Positions start at 0, both ends are included, and -1 means the last one, so0 -1is everything.REVflips the order to highest first, which is what a leaderboard wants.WITHSCORESputs each member's score after it, alternating member and score.
Two members with the same score are ordered alphabetically by member name.
ZADD also takes options: NX only adds new members, XX only updates existing ones, and GT or LT only update when the new score is greater or lower, perfect for "keep each player's best score".
The shortcut
Picture the set as a ladder sorted from lowest score at position 0 upward. ZRANGE reads rungs from the bottom; REV turns the ladder upside down first.
Build the ladder
Lowest to highest: tom 90 (0), ravi 150 (1), asha 320 (2), meera 410 (3).
The trap is forgetting REV and proudly showing the two lowest scorers as champions.
Drills
Answer fast — trust the rule.
What does ZADD leaderboard 500 ravi 60 priya reply, given ravi is already a member and priya is not?
With tom 90, ravi 150, asha 320, meera 410, what does ZRANGE leaderboard 0 0 return?
Which command returns the three highest-scoring players?
Asha's best score is 320. What does ZADD leaderboard GT 280 asha do?
Remember
- ZADD gives each member a score (score first); ZRANGE reads them lowest first.
- Picture a ladder from lowest at 0; REV flips it for a leaderboard.
- ZADD's reply counts new members only, never score updates.
