CodePark/ questions / Data types & commands
START PRACTICINGPRACTICE
Backend question · Redis & caching › Data types & commands

Design a game leaderboard with Redis. How do you add points, show the top 10 and show a player's rank?

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:

  • ZINCRBY adds points to a player. It is atomic, so two updates at the same time never overwrite each other.
  • ZADD sets an absolute score instead. ZADD ... GT only updates when the new score is higher. This is handy for best-score boards.
  • ZRANGE leaderboard 0 9 REV WITHSCORES returns the top 10. ZREVRANGE is the older command that does the same thing.
  • ZREVRANK gives a player's position from the top. It starts at 0, so the first player gets 0.
  • ZSCORE gives 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 ZINCRBY or ZADD to update scores atomically.
  • Use ZRANGE ... REV for the top N and ZREVRANK for 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.