Advertisement
Intermediate Redis, Leaderboards with Sorted Sets

How do you atomically increase a player's score on a leaderboard, such as after they earn additional points during gameplay?

Short answer

You use the ZINCRBY command, specifying the leaderboard key, the amount to add, and the player's name, which atomically increases that player's existing score by the specified amount, automatically re-adjusting their position in the ranking as needed without any risk of a race…

Save Redis mock interview
Advertisement
AModel answer
You use the ZINCRBY command, specifying the leaderboard key, the amount to add, and the player's name, which atomically increases that player's existing score by the specified amount, automatically re-adjusting their position in the ranking as needed without any risk of a race condition from multiple simultaneous score updates.
Example

ZINCRBY leaderboard 50 'player1'

Real-world example
A game safely increases a player's score by fifty points immediately after they complete a level, using ZINCRBY to atomically update their score even if many players are earning points at the exact same moment.
Likely follow-ups
  • What happens if you call ZINCRBY on a player who is not yet on the leaderboard?
  • Can ZINCRBY be used with a negative value to decrease a score?
Related topics