0
0
Redisquery~5 mins

Leaderboard implementation in Redis

Choose your learning style9 modes available
Introduction

A leaderboard shows who is winning by ranking players or items by their scores. It helps track top performers easily.

You want to show top players in a game.
You want to rank salespeople by their sales numbers.
You want to display the most popular articles by views.
You want to track the highest scores in a quiz app.
You want to keep a list of best customers by points earned.
Syntax
Redis
ZADD leaderboard_name score member

ZADD adds or updates a member with a score in a sorted set.

The sorted set automatically keeps members ordered by score.

Examples
Adds player1 with score 1500 to the leaderboard.
Redis
ZADD game_leaderboard 1500 player1
Adds player2 with score 2000, who will rank higher than player1.
Redis
ZADD game_leaderboard 2000 player2
Gets top 3 players with their scores, sorted from lowest to highest.
Redis
ZRANGE game_leaderboard 0 2 WITHSCORES
Gets top 3 players with their scores, sorted from highest to lowest.
Redis
ZREVRANGE game_leaderboard 0 2 WITHSCORES
Sample Program

This adds three players with scores and then shows the top 3 players from highest to lowest score.

Redis
ZADD leaderboard 100 Alice
ZADD leaderboard 150 Bob
ZADD leaderboard 120 Carol
ZREVRANGE leaderboard 0 2 WITHSCORES
OutputSuccess
Important Notes

Scores can be any number, including decimals.

Members must be unique strings; adding the same member updates its score.

Use ZREVRANGE to get highest scores first, which is common for leaderboards.

Summary

Leaderboards use Redis sorted sets to store members with scores.

ZADD adds or updates scores.

ZREVRANGE fetches top members sorted by highest score.