Quick revision
The short answer
We keep one sorted set per period, such as leaderboard:2026-11, with player ids as members and scores as scores. ZADD with GT records a score only if it beats the stored one (Redis 6.2 or later), or ZINCRBY adds to a running total; ZRANGE key 0 9 REV WITHSCORES returns the top 10; and ZREVRANK plus 1 gives a player's rank. In Spring Data Redis these are opsForZSet().add(), reverseRangeWithScores(key, 0, 9) and reverseRank(), and we set an expiry on old periods.
What to remember
In this answer, we built a leaderboard on a Redis sorted set with one key per period. ZADD with GT keeps a best score and ZINCRBY keeps a total, ZRANGE 0 9 REV WITHSCORES returns the top 10, and ZREVRANK plus 1 gives a rank, mapped in Spring Data Redis to opsForZSet() add or incrementScore, reverseRangeWithScores and reverseRank. We saw that ties are ordered by member name unless we encode a tie breaker in the score, that old periods should expire, and that a very popular board is a hot key in a cluster.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We keep one sorted set per period, such as leaderboard:2026-11, with player ids as members and scores as scores. ZADD with GT records a score only if it beats the stored one (Redis 6.2 or later), or ZINCRBY adds to a running total; ZRANGE key 0 9 REV WITHSCORES returns the top 10; and ZREVRANK plus 1 gives a player's rank. In Spring Data Redis these are opsForZSet().add(), reverseRangeWithScores(key, 0, 9) and reverseRank(), and we set an expiry on old periods.
Why this question is asked
A leaderboard is the textbook use of Redis sorted sets, and it is a good interview question because it is small enough to code in a few minutes yet hides real details: which score wins, how ties are ordered, how to keep the data from growing forever, and what happens when one key becomes very hot. In this answer, we will recap how sorted sets work, write the Redis commands for the three operations, implement them in a Spring Boot service with Spring Data Redis, deal with ties, and then look at periods, expiry and hot keys.
1A Quick Recap of Sorted Sets
A sorted set is a Redis key holding unique members, each with a numeric score, always kept ordered by score. Internally it combines a hash table, to find a member's score in O(1), with a skip list, a layered linked structure that keeps members in order and finds positions in O(log n). So adding a score, reading a range by position and finding a member's rank are all fast even with millions of players.
Redis orders by ascending score. A leaderboard wants the highest score first, so we read it in reverse: the REV option of ZRANGE, or the older ZREVRANGE and ZREVRANK commands, which count positions from the top.
2The Redis Commands
Here are the three operations on the November 2026 board. We decide first what a score means. If the board shows each player's best game, we keep the higher score with GT. If it shows total points over the month, we add with ZINCRBY.
Notice that ZADD returns the number of new members added, not the number changed, which is why the third call returns 0 even though it raised the score. Adding the CH flag makes it count changed members instead. And ZREVRANK is 0-based, so we add 1 before showing it to a person; it returns nil when the player has no score yet.
3The Spring Data Redis Service
In Spring Boot, StringRedisTemplate gives us a ZSetOperations object through opsForZSet(). Its methods map closely to the commands.
8 messages in order. Play them, or step through them one at a time.
Notice the note on recordBest(). The simple add() call is a plain ZADD, which overwrites the score even if it is lower. To get GT behaviour, recent Spring Data Redis versions accept ZAddArgs at the connection level, or we can run a tiny Lua script that compares and sets atomically. Check your version for the exact API. What we must not do is read the score in Java, compare, and then write, because two games finishing together could race.
4Breaking Ties
When two players have the same score, Redis orders them by member name, lexicographically, and with REV that order is reversed too. So player:zoe would appear above player:adam with the same score, which looks arbitrary to players. If the rule is that whoever reached the score first ranks higher, we encode that into the score itself.
The earlier player gets the larger low part, so the higher combined score. A double holds integers exactly up to about 9 x 10^15, so this works while points stay below roughly 900 million. When displaying, we divide by 10,000,000 and drop the fraction to get the points back.
5Periods, Expiry and Hot Keys
Using one key per period, such as leaderboard:2026-11, gives us monthly resets for free and keeps each key a manageable size. Once a month is over and its results are archived, we set an expiry on the old key so Redis removes it, for example EXPIRE leaderboard:2026-10 7776000 to keep it for 90 days.
But there is a catch at large scale. All reads and writes for the current board hit one key, and in a Redis Cluster one key lives on one shard. A popular game can turn that key into a hot key that overloads a single node while others idle. Common answers are caching the top 10 in the application for a second or two, since every viewer asks for the same thing, and for very large boards splitting players into regional or bracket boards.
6Follow-up questions
How would you show the players ranked just above and below a given player?
First get the player's 0-based position with ZREVRANK, say 41. Then read a window around it with ZRANGE leaderboard:2026-11 39 43 REV WITHSCORES, which returns the two players above, the player, and the two below. In Spring that is reverseRank() followed by reverseRangeWithScores(key, Math.max(0, r - 2), r + 2). It takes two O(log n) calls.
What if we need the top 10 among a player's friends?
We can keep a set of friend ids per player and intersect it with the leaderboard into a temporary sorted set with ZINTERSTORE using weights, then read its top 10 and let the temporary key expire. For large friend lists, it is often cheaper to fetch the friends' scores with ZMSCORE and sort them in the application.
Does the leaderboard need persistence?
If Redis is the only place the scores live, yes: AOF and replicas, because losing the board would be visible to players. Often the game service also records scores in a database, and Redis holds a rebuildable view, which lets us rebuild a board after a loss.
7Conclusion
In this answer, we built a leaderboard on a Redis sorted set with one key per period. ZADD with GT keeps a best score and ZINCRBY keeps a total, ZRANGE 0 9 REV WITHSCORES returns the top 10, and ZREVRANK plus 1 gives a rank, mapped in Spring Data Redis to opsForZSet() add or incrementScore, reverseRangeWithScores and reverseRank. We saw that ties are ordered by member name unless we encode a tie breaker in the score, that old periods should expire, and that a very popular board is a hot key in a cluster.
Open with
I would use a Redis sorted set per period, for example leaderboard:2026-11, with the player id as the member and the score as the score. To record a best score I use ZADD with the GT option, which only updates if the new score is higher and needs Redis 6.2 or later; for a cumulative board I use ZINCRBY.
Then, if they want more
The top 10 is ZRANGE leaderboard:2026-11 0 9 REV WITHSCORES, or ZREVRANGE on older versions, and a player's rank is ZREVRANK plus one, because it is zero-based, and it returns nil if the player has no score.
In Spring Data Redis I use opsForZSet(): add or incrementScore to record, reverseRangeWithScores(key, 0, 9) for the top 10, and reverseRank for the rank. For GT from Java I would use the ZAddArgs support or a small Lua script, never read-compare-write in Java. All of these are O(log n), so they scale to millions of players.
Ties are ordered lexicographically by member, so if earlier achievement should win I encode a tie breaker into the score. I set an expiry on old periods after archiving, and for a very popular game I watch for the hot key problem in a cluster, caching the top 10 briefly in the application.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Redis 6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Redis documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Implement a game leaderboard in Redis from a Spring Boot service: record a score, show...": https://scrivio-interview-library.netlify.app/databases/redis/9e3d976c63/