Sorted sets and leaderboards
A sorted set keeps unique members ordered by a numeric score: a score update or rank lookup costs about log N, and a top-N read adds the N returned. A common fit for live leaderboards; strong answers name its limits.
What it is
A sorted set is a collection of unique members, each tagged with a numeric score, that stays ordered by score as members are added, removed or re-scored. In Redis the score is a 64-bit double, a member appears once, and members with the same score are ordered lexicographically by the member string. Because the order is maintained on write, a read of the top of the set does no sorting. Redis lists leaderboards, real-time analytics and job scheduling as typical uses.
The mechanism is two structures over the same members. Redis keeps a hash table from member to score, which finds one member directly, and a skip list that holds the members in score order. Adding or re-scoring a member (ZADD, ZINCRBY) is O(log N): when the member already exists, Redis updates its score and reinserts it at the position that keeps the order. Finding a member's position (ZRANK from the lowest score, ZREVRANK from the highest, both 0-based) is O(log N), and reading a range of M members by rank is O(log N + M).
| Leaderboard question | Redis command | Cost |
|---|---|---|
Player scored points |
| O(log N) |
Top 10 with scores |
| O(log N + 10) |
Where am I? |
| O(log N) |
Who is just above and below me? |
| O(log N + 5) |
How many players have 1000 points or more? |
| O(log N) |
Reverse reads are the leaderboard's bread and butter. ZREVRANGE returns a rank range ordered from the highest score down, with equal scores in descending string order; indexes are zero-based, and negative indexes count from the end, so -1 is the lowest-scored member. Since Redis 6.2.0 that command is deprecated and new code uses ZRANGE with the REV argument instead. ZCOUNT answers how many members fall in a score range in O(log N), because it works from the ranks of the two ends rather than walking the members between them.
Ties. The default tie order (by member string) is arbitrary from the product's point of view. If the player who reached a score first should rank higher, put that into the score itself: multiply the points by a large constant and add a term that shrinks as time passes, so an earlier arrival sorts above a later one at equal points. The score is a 64-bit IEEE 754 double, so a packed value that grows beyond what a double holds exactly loses precision in its low digits, which is where the time term lives. Our advice: work out the largest value the packing can produce before you ship it, and keep the packing in one place in the code so the rank page and the score page agree.
When to use it
Reach for a sorted set when scores change often and each view of the product needs both a top list and the viewer's own position. A game leaderboard, a sales contest board, trending posts by engagement score, a 'most active' list: each is a stream of small score updates and reads that want order. One key per board and per period (board:2026-w47) keeps weekly and all-time boards separate. A board limited to the viewer's friends can be built on request from the friends' scores while friend lists stay small; a very large social graph needs its own design.
The same shape fits anything ordered by a number that is not a score. With a timestamp as the score, a set is a time index: a sliding-window rate limiter adds each request at its time, drops members older than the window by score range and counts what remains. With a due time as the score, it is a delayed-job queue, which job scheduling and delayed work covers.
Scaling past one node. A sorted set is one key. Redis Cluster places a key into one of 16384 hash slots by CRC16 of the key, and commands that touch several keys work when all of them hash to the same slot; hash tags ({season3}:board) force keys into one slot. A whole leaderboard therefore lives on one node, which is fine until its memory or its write rate outgrows that node. Then split the board by a segment the product already has, such as league, region or score bracket, into separate keys. A global top N is the merge of each shard's top N. A global rank is the viewer's rank in their shard plus, for each other shard, the count of members ahead of them: ZCOUNT above their score, plus any members tied at that score that your tie rule puts first. Hot write keys are covered in hot keys and hot partitions.
When not to
A small or slow-moving board does not need a second store. A table with an index on the score column answers ORDER BY score DESC LIMIT 10 from the index, and one row's rank comes from a window function: PostgreSQL defines rank() as the position with gaps after ties, dense_rank() as the position without gaps, and row_number() as a plain count from 1. If the board is small and read rarely, that can run on request; otherwise run it in a nightly or hourly job and write the rank back to a column. If the board refreshes once a day anyway, the batch is the better design and the database stays the one system to operate.
A sorted set holds one ordering per key. 'Top players in region X at level Y, who joined this year' is a filtered query. You can model it with a key per filter combination, by intersecting sets at read time, or with a database whose indexes combine the filters; the more filters the product offers, the more the database option tends to win. If the ranking formula changes (weights, decay, penalties), a set stores results, not formulas: you recompute and rewrite scores for members, which is a full pass. When you need a historical board as of some date, or an audit of how a score was reached, that is the event history's job, not the set's.
At very large scale, when a precise global rank for a player deep in the long tail is not worth its cost, an approximate rank from a histogram of score buckets is an option: count members above the bucket, then position within the bucket. Approximate counting covers that trade. Our advice: keep exact ranks for the top of the board and approximate the tail.
Compared
| Approach | Top N | One player's rank | Pick it when |
|---|---|---|---|
Redis sorted set |
|
| Scores change constantly and each view shows rank; the board fits one node |
SQL table, index on score |
| A count of rows above the score, or | The board is small or changes slowly, rank is asked for rarely, and you want one store to run |
Batch-precomputed ranks | Read N rows from a rank table | Read one column | The board refreshes hourly or daily and a lag is acceptable |
Sharded sorted sets | Merge each shard's top N | Rank in own shard plus, per other shard, the count of members ahead ( | One node can't hold the set or absorb its writes |
Histogram of score buckets | Still from a sorted set of the top entries | Approximate: members above the bucket plus position within it | The board is far too large for exact ranks in the long tail to be worth their cost |
In a picture
Step 1 of 3
Write path
A match ends. The game service records the result in the database and bumps the player's score in the sorted set with one ZINCRBY.