ZINCRBY leaderboard 50 "player:42"
ZRANGE leaderboard 0 9 REV WITHSCORES
ZREVRANK leaderboard "player:42"
ZSCORE leaderboard "player:42"
Use a sorted set. A sorted set stores unique members, and each member has a number called a score. Redis keeps the members ordered by score. Here, each member is a player ID and the score is the player's points. Because the order is always kept, ranking queries are cheap.
The commands:
ZINCRBYadds points to a player. It is atomic, so two updates at the same time never overwrite each other.ZADDsets an absolute score instead.ZADD ... GTonly updates when the new score is higher. This is handy for best-score boards.ZRANGE leaderboard 0 9 REV WITHSCORESreturns the top 10.ZREVRANGEis the older command that does the same thing.ZREVRANKgives a player's position from the top. It starts at 0, so the first player gets 0.ZSCOREgives a player's points.
Updates and rank lookups are O(log N). Reading a range is O(log N + M), where M is the number of items returned. When two players have the same score, Redis orders them by member name in lexicographic (dictionary) order.
For daily or weekly boards, use one key per period and give it a TTL (time to live: an expiry time). Use ZUNIONSTORE to combine several periods into one board.
- Use a sorted set, with the player as the member and the points as the score.
- Use
ZINCRBYorZADDto update scores atomically. - Use
ZRANGE ... REVfor the top N andZREVRANKfor a player's rank. - Updates and rank lookups are O(log N).
- For daily or weekly boards, use one key per period with a TTL.