Skip to the workspace
Pebellslearn by building
Sorted Sets  ›  Capstone Project

ZINCRBY and a Live Leaderboard

ZINCRBY 12 minZINCRBY adds points to a member's score, creating the member if needed, and replies with the new score, which makes a sorted set a live leaderboard.

redis / ZINCRBY and a Live Leaderboard

Explore each scene at your own pace.

01 · The rule

The rule

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 key counts members: "4,812 players".
  • ZSCORE key member reads one score.
  • ZREMRANGEBYRANK key 0 -101 removes everyone except the top 100, keeping a bounded board.
  • ZPOPMAX key removes and returns the highest-scoring member.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.