Quick revision
The short answer
Ranking 30 million rows with RANK() on every request is an O(n log n) sort per request, so I would stop computing global ranks at read time. A single player's rank can be COUNT(*) WHERE score > :myScore on an indexed score column, which is cheaper but still scans as many index entries as the player's rank; for real-time ranks I would use a Redis sorted set (ZADD, ZREVRANK) with O(log n) updates and lookups and the database as the source of truth. Precomputed ranks or score histograms give approximate ranks cheaply, and the product should decide where exactness is really needed, typically only the top 100.
What to remember
In this answer, we saw that RANK() over 30 million players on every request sorts the whole table each time, which explains the CPU. Counting players with a higher score through an index is exact and cheap for top players but costs time proportional to the rank, while a Redis sorted set gives real-time ranks with O(log n) updates and lookups, with the database as the source of truth. Precomputed ranks and score histograms serve approximate or slightly stale ranks cheaply, and the product's real requirements, usually exact only for the top 100, decide which technique serves each screen.
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.
Ranking 30 million rows with RANK() on every request is an O(n log n) sort per request, so I would stop computing global ranks at read time. A single player's rank can be COUNT(*) WHERE score > :myScore on an indexed score column, which is cheaper but still scans as many index entries as the player's rank; for real-time ranks I would use a Redis sorted set (ZADD, ZREVRANK) with O(log n) updates and lookups and the database as the source of truth. Precomputed ranks or score histograms give approximate ranks cheaply, and the product should decide where exactness is really needed, typically only the top 100.
Why this question is asked
Leaderboards look simple and are a classic way to melt a database. The query is one line, RANK() OVER (ORDER BY score DESC), and it works perfectly in development with a thousand players. With 30 million players and thousands of requests a second, each request sorts the whole table. Interviewers ask this scenario because the fix combines several skills: estimating the cost of a query, choosing the right data structure, and asking the product what level of accuracy is really needed. In this answer, we will see why the current query is so expensive, make a single player's rank cheaper in SQL, move real-time ranking to a Redis sorted set, use precomputation and histograms for scale, and shape the design around product requirements.
1Why RANK() on Every Request Burns the CPU
The current endpoint probably runs something like this to show one player's rank and the players around them.
To give one player a rank, the database ranks all 30 million, because a rank is defined relative to everyone else. Sorting n rows costs on the order of n log n comparisons, and the filter on player_id comes after the window, so it cannot reduce the work. An index on score lets the database read rows already in order instead of sorting, but it still walks all 30 million entries. Multiply by the request rate and the CPU at 90 percent is no surprise.
2A Cheaper SQL Query for One Player's Rank
A player's competition rank is one more than the number of players with a strictly higher score. With an index on score, the database can count those from the index alone.
This matches RANK() exactly, including ties, and it is a big improvement for players near the top. But notice the cost: it is proportional to the player's rank, because the index has to count every entry above them. A B-tree does not store how many entries sit below each node, so it cannot answer 'how many are greater than x' in logarithmic time. For a median player that is still millions of entries per request. We need a data structure that can.
3Real-Time Ranks With a Redis Sorted Set
A Redis sorted set keeps members ordered by score in a skip list, a structure that, unlike a plain B-tree, tracks how many elements each link spans. That lets it compute a member's position in O(log n). Updating a score is also O(log n), and reading a range of positions, such as the top 100, costs O(log n + m) for m results.
5 messages in order. Play them, or step through them one at a time.
The database stays the source of truth; Redis answers rank queries in O(log n).
ZREVRANK gives the position, and among equal scores Redis orders members lexicographically, so two tied players get different positions. If the product wants tied players to share a rank, as RANK() does, ZCOUNT with an exclusive lower bound (the parenthesis) counts strictly higher scores, also in O(log n), and adding 1 gives the competition rank. Thirty million members fit in a few gigabytes of memory, which a single Redis primary with a replica handles comfortably.
The database remains the source of truth for scores. The game service writes the score to PostgreSQL and then updates Redis; to avoid losing updates when Redis is briefly unavailable, it writes an event to an outbox table in the same transaction, and a relay applies it to Redis. If Redis is lost entirely, we rebuild the sorted set from the players table, which takes minutes for 30 million rows.
4Precomputed Ranks and Histograms for Scale
Not every leaderboard needs to be live. For a global board that is viewed far more often than it changes meaningfully, a job can compute ranks every five minutes into a table, ranked_players(player_id, rnk), with one RANK() pass over the 30 million rows, about the cost of a single request today, and requests then read their rank by primary key. The board is up to five minutes old, which players rarely notice outside the top positions.
For approximate ranks at very large scale, a histogram works well. We keep a small table of how many players fall into each score bucket, for example 1,000 buckets, updated when scores change. A player's approximate rank is the sum of counts of all higher buckets plus an estimate of their position inside their own bucket. That is a sum over at most 1,000 small rows, and it can be cached.
The answer is exact to within the size of the player's bucket, which is fine for a message such as 'top 3 percent'.
5Shaping the Design Around Product Requirements
Before building, I would ask the product owner what each screen really needs, because exactness is expensive and rarely needed everywhere. A typical answer is that the top 100 must be exact and real time, because that is where competition happens; players should see their own rank within a few seconds; and players far down the board care about 'roughly where am I', not 'exactly 14,512,377th'.
That leads to a layered design: Redis for the top of the board and for the player's own position, a precomputed or histogram-based rank for display far down the list, and the database used for writes and as the source of truth, not for ranking reads. CPU on the database drops to the cost of writes plus a periodic batch.
| Need | Technique | Cost per request |
|---|---|---|
| Exact top 100, live | Redis ZREVRANGE 0 99 | O(log n + 100) |
| My exact rank, within seconds | Redis ZCOUNT or ZREVRANK | O(log n) |
| My approximate rank far down | Score histogram | Sum over about 1,000 rows |
| Rank in a nightly report | One RANK() pass in SQL | One sort per day |
| Every request today | RANK() over 30M rows | O(n log n): the problem |
6Follow-up questions
How would you handle weekly or regional leaderboards?
One sorted set per board, for example leaderboard:2025-W23 and leaderboard:region:eu, each updated on every score change, with an expiry on old weekly sets. Memory grows with the number of boards times players on each, so very fine-grained boards, such as per city, may use precomputation instead.
What if Redis and the database disagree after a failure?
The database wins. A periodic reconciliation compares a sample of players' scores in Redis with the database and fixes differences, and a full rebuild from the players table is the fallback. Because the outbox relay replays events in order, most disagreements are short delays rather than lost updates.
Why not use a materialised view in PostgreSQL?
A materialised view with the ranks is a fine way to implement the precomputed table: REFRESH MATERIALIZED VIEW CONCURRENTLY ranked_players every few minutes, which needs a unique index on the view and lets reads continue during the refresh. It solves the global board, but not live ranks after each score change.
7Conclusion
In this answer, we saw that RANK() over 30 million players on every request sorts the whole table each time, which explains the CPU. Counting players with a higher score through an index is exact and cheap for top players but costs time proportional to the rank, while a Redis sorted set gives real-time ranks with O(log n) updates and lookups, with the database as the source of truth. Precomputed ranks and score histograms serve approximate or slightly stale ranks cheaply, and the product's real requirements, usually exact only for the top 100, decide which technique serves each screen.
Open with
The query ranks all 30 million players on every request, which is a full sort or a full index walk each time, so it's O(n log n) per request and that's where the CPU goes.
Then, if they want more
Step one is to stop ranking at read time. For one player's rank in SQL, COUNT star of players with a higher score, plus one, with an index on score, gives the exact competition rank, but it reads as many index entries as the player's rank, so it's great for the top and still slow for a median player.
For real-time ranks I'd use a Redis sorted set: ZADD on every score change, ZREVRANK or ZCOUNT with an exclusive bound for a player's rank, and ZREVRANGE for the top 100, all O(log n). The database stays the source of truth, with an outbox so Redis updates are not lost, and we can rebuild the set from the table.
For the global view, I'd precompute ranks every few minutes, and for players far down the list a score histogram gives an approximate rank from a thousand small rows. And I'd agree requirements with product first: usually only the top 100 needs to be exact and live, and everyone else is happy with 'top 3 percent'.
About this answer
- Last updated
- 12 November 2026
- 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
- PostgreSQL documentation, The SQL Language
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 "A leaderboard for 30 million players uses RANK() OVER (ORDER BY score DESC) on every...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/bc8bdd98ed/