ZINCRBY and a Live Leaderboard
A round of Wordcraft ends and Asha earns 100 points. Hundreds of rounds end every minute, some of them Asha's, and each must add to the right total without losing any. The leaderboard must be correct the instant the points land.
The rule
ZINCRBY adds to a score and re-sorts; a new member starts from zero.
ZINCRBY key increment member adds increment to the member's score and replies with the new score as a string. If the member is not in the set, it is added with a score of 0 first, so the reply is just the increment. A negative increment subtracts.
The leaderboard holds tom 90, ravi 150, asha 320 and meera 410.
127.0.0.1:6379> ZINCRBY leaderboard 100 asha
"420"
127.0.0.1:6379> ZINCRBY leaderboard 50 priya
"50"
127.0.0.1:6379> ZREVRANK leaderboard asha
(integer) 0
127.0.0.1:6379> ZCARD leaderboard
(integer) 5
127.0.0.1:6379> ZRANGE leaderboard 0 2 REV WITHSCORES
1) "asha"
2) "420"
3) "meera"
4) "410"
5) "ravi"
6) "150"Asha's 420 overtook Meera's 410, and her rank moved to 0 at once: the order is maintained on every write, never recomputed on read.
Like INCR, ZINCRBY is atomic: the read, add and write happen inside Redis as one command, so two rounds finishing together both count. Reading with ZSCORE and writing back with ZADD leaves a gap in which one of the two can be lost.
A few more commands complete a real leaderboard:
ZCARD keycounts members: "4,812 players".ZSCORE key memberreads one score.ZREMRANGEBYRANK key 0 -101removes everyone except the top 100, keeping a bounded board.ZPOPMAX keyremoves and returns the highest-scoring member.
The shortcut
For a series of ZINCRBY commands, keep a running score per member (0 if missing); each reply is that member's new total. Then re-rank only if a total crossed someone else's.
Start
ravi 150, meera 410.
Scores are floating-point numbers, so a sorted set can rank by points, by time or by rating. Many games use a timestamp as the score to keep "most recent" order, or combine several numbers into one score. Just remember the reply is a string: convert it to a number in your app before doing maths with it.
Drills
Answer fast — trust the rule.
leaderboard has no member called zoe. What does ZINCRBY leaderboard 40 zoe reply?
Tom has 90. What does ZINCRBY leaderboard -30 tom reply?
Why is ZINCRBY safer than ZSCORE then ZADD for awarding points?
A leaderboard has 250 members. How many remain after ZREMRANGEBYRANK leaderboard 0 -101?
Remember
- ZINCRBY adds to a score and re-sorts; a new member starts from zero.
- Keep a running score per member; each reply is the new total.
- Award points with ZINCRBY, never with read-then-ZADD.
