Scrivio Interview library
CodingFoundations6 min read · updated 13 November 2026

Sorted sets order members by a floating-point score and break ties by comparing member names, which is rarely what a game wants when two players reach the same score.

Using ZADD options and a composite score, build a leaderboard where only a player's best score counts and, among equal scores, the player who reached it first ranks higher.

ZADD lb GT score player updates a member only when the new score is higher and still adds new players, so the board keeps each player's best score. To rank earlier achievers first among equal scores, we fold the time into the score: score x 10^7 + (9999999 - secondsSinceSeasonStart), which stays exact as long as the total is below 2^53, limiting the raw score to about 900 million and the season to about 115 days. We decode with integer division by 10^7 or keep the real score in a hash, read with ZRANGE ... REV WITHSCORES, ZREVRANK and ZSCORE, and choose this encoding only for best-score boards, because ZINCRBY would add the tie-break again on every increment.

Background to this question

Leaderboards are the textbook use of Redis sorted sets, and the basic version takes two commands. The interesting part, and the reason this is asked, is the details a real game needs: keep only the best score, and break ties fairly. Both can be done inside the sorted set without extra round trips if we understand how scores are stored. In this answer, we will recap how sorted sets order members, use ZADD GT for best scores, build the composite score and check its limits, and then cover reading the board and the trap with cumulative scores.

1A Quick Recap of Sorted-Set Ordering

A sorted set stores unique members, here player ids, each with a score. The score is a 64-bit floating-point number, a double. Members are kept in ascending score order, and when two members have the same score they are ordered by comparing the member strings byte by byte, so 'ana' comes before 'zoe'.

For a leaderboard read from the top down, that tie-break means that among players with equal scores, the one whose id sorts last appears first. It has nothing to do with who got there first, which is what players expect. So we need to put the time into the score itself.

2Keeping Only the Best Score With GT

Since Redis 6.2, ZADD accepts GT: update an existing member only if the new score is greater than its current score. GT does not stop new members from being added, so a first score always lands.

Java
ZADD lb GT 1500 ana -- (integer) 1: new member added
ZADD lb GT 1200 ana -- (integer) 0: 1200 < 1500, ignored
ZADD lb GT 1600 ana -- (integer) 0: score updated to 1600 (0 counts only new members)
ZSCORE lb ana -- "1600"

Notice that the reply counts only newly added members unless we also pass CH, so a 0 does not tell us whether the update happened. Without GT we would need to read the old score, compare it in Java and write, which is a race between two game servers; GT makes the comparison atomic on the server.

3Encoding the Tie-Break in the Score

We want higher scores first and, among equal scores, the earlier achievement first. Reading from the top, the larger composite value ranks higher, so the time part must be larger for earlier times. We take the seconds since the season started, subtract them from 9,999,999, and add that to the score shifted left by seven decimal digits.

Java
long secondsSinceSeasonStart = Duration.between(seasonStart, now).toSeconds(); // 86400 (day 2)
long raw = 1520;
double composite = raw * 10_000_000L + (9_999_999L - secondsSinceSeasonStart);
// 1520 * 10^7 + 9913599 = 15209913599.0
redis.opsForZSet().add("lb", "ana", composite); // plain ZADD; use GT through a script or raw command
// ana at day 2 -> 15209913599, bo with 1520 at day 3 -> 15209827199: ana ranks above bo
How the composite score orders players
PlayerRaw scoreReached at (s)CompositeRank
ana152086400152099135991
bo1520172800152098271992
cy14903600149099963993
Equal raw scores: the earlier time gives the larger composite.

Two limits follow from the encoding. The time part has seven digits, so it covers 9,999,999 seconds, about 115 days; seasons must be shorter, or we use minutes instead of seconds. And a double holds every integer exactly only up to 2^53, about 9.007 x 10^15. Dividing by 10^7 leaves about 900 million for the raw score. Above that, nearby composite values round to the same double and the ordering breaks.

Notice that GT still behaves correctly with the composite: a later equal score produces a smaller composite and is ignored, so the earliest achievement of the best score is kept, and any higher score produces a larger composite and wins.

4Decoding and Reading the Board

For display we decode with integer division by 10^7: 15209913599 / 10^7 = 1520. Alternatively we keep the real score in a hash, HSET scores ana 1520, and use the sorted set only for ordering, which avoids any decoding in clients and keeps the raw value exact.

Java
ZRANGE lb 0 9 REV WITHSCORES -- top 10, highest first (Redis 6.2+; ZREVRANGE in older code)
ZREVRANK lb ana -- (integer) 0: ana is first (0-based rank)
ZSCORE lb ana -- "15209913599": decode to 1520
HGET scores ana -- "1520" if we keep raw scores separately

ZREVRANK is 0-based, so the display rank is the reply plus one. All of these are O(log N), plus the number of members returned for ZRANGE, so they stay fast for millions of players.

5The Trap: Cumulative Scores

This encoding fits a best-score board. If the game instead adds points over time with ZINCRBY, every increment would add our tie-break part again: two increments would add two time values to the score, and the composite would be meaningless. For a total-score board we would either recompute the full composite in a script on each update, reading the raw total from a hash, or accept member-name ordering for ties. So we decide whether the board ranks best score or total score before choosing the encoding.

6Follow-up questions

What happens to ordering if the composite value exceeds 2^53?

Beyond 2^53 a double cannot represent every integer; the gap between representable values becomes 2, then 4, and so on. Composite values that differ only in their last digits round to the same double, so the time tie-break is lost and players with equal scores fall back to member-name ordering, and for very large values even different raw scores can collide. Keep the raw score bounded, use fewer time digits, or rank by a separate structure.

Why not store the timestamp in the member name?

Because the member is the player's identity: if it included a time, each new best score would create a new member instead of updating the player, and the player would appear on the board several times.

Does GT work with ZINCRBY?

No. GT, LT, NX and XX are options of ZADD. ZADD with INCR and GT exists, but it increments only if the result would be greater, which suits different rules. For best-score boards, plain ZADD GT is the right tool.

7Conclusion

In this answer, we saw that ZADD GT keeps each player's best score atomically while still adding new players, and that a composite score of score x 10^7 plus (9999999 minus seconds since season start) makes earlier achievers rank higher among equal scores. The composite must stay below 2^53, which caps the raw score near 900 million and the season near 115 days. We decode by integer division or keep raw scores in a hash, read with ZRANGE REV WITHSCORES, ZREVRANK and ZSCORE, and avoid this encoding for cumulative boards built with ZINCRBY.

What to say in the interviewAbout 90 seconds aloud

Open with

For the best score I would use ZADD with GT, available since Redis 6.2. It only updates a member when the new score is greater, but it still adds new members, so each player keeps their best score, and the comparison is atomic on the server.

Then, if they want more

For ties, sorted sets order equal scores by member name, which is not fair, so I put the time into the score. The composite is score times ten to the seven, plus 9,999,999 minus the seconds since the season started.

An earlier achievement gives a larger time part, so in descending order the player who got there first ranks higher, and GT still works, because a later equal score is smaller and ignored.

Scores are doubles, so the composite must stay under 2 to the 53 to be exact, which limits the raw score to about 900 million, and seven digits of seconds limit the season to about 115 days. For display I divide by ten to the seven, or keep the raw score in a hash.

I read the top 10 with ZRANGE 0 9 REV WITHSCORES, a player's rank with ZREVRANK, which is 0-based, and the stored value with ZSCORE. If the board were cumulative with ZINCRBY, this encoding would break, because the time part would be added on every increment.

About this answer

Last updated
13 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 "Using ZADD options and a composite score, build a leaderboard where only a player's best...": https://scrivio-interview-library.netlify.app/databases/redis-patterns/b1dca5d422/