Why are Redis sorted sets a natural fit for building a leaderboard feature?
Short answer
A sorted set automatically keeps its members ordered by their associated score, meaning as you add or update a player's score, Redis automatically maintains the correct ranking order internally, letting you instantly retrieve the top players or a specific player's rank without…
Advertisement
AModel answer
A sorted set automatically keeps its members ordered by their associated score, meaning as you add or update a player's score, Redis automatically maintains the correct ranking order internally, letting you instantly retrieve the top players or a specific player's rank without needing to manually sort anything yourself.
Example
ZADD leaderboard 1500 'player1' ZADD leaderboard 2300 'player2' ZREVRANGE leaderboard 0 9 WITHSCORES
Real-world example
A mobile game maintains a global leaderboard using a sorted set, automatically keeping thousands of player scores properly ranked as they play and earn points throughout the day.
Likely follow-ups
- What happens if two players end up with the exact same score?
- How do you update a player's score without needing to remove and re-add them?
Related topics