Video in progress

Strong Middle 🏗️ System design

How do you build a real-time leaderboard with millions of players?

A Redis sorted set (ZADD, ZINCRBY, ZREVRANGE, ZREVRANK) is almost ready-made for this: adding points and finding a rank is O(log N). The source of truth stays in the DB, and Redis serves fast reads; at very large volume you split the leaderboard into pieces or give ranks approximately.

📖 Answer

Requirements: score updates at tens of thousands per second, and "top 100" and "my rank" must come back fast. In SQL, ORDER BY score DESC and COUNT(*) WHERE score > ? for the rank — scanning an index on every request over 10 million rows; a load like that can't be carried at peak.

With a sorted set:

ZINCRBY lb:2026-11 50 user:42          # add 50 points
ZREVRANGE lb:2026-11 0 99 WITHSCORES   # top 100
ZREVRANK lb:2026-11 user:42            # zero-based rank
ZREVRANGE lb:2026-11 1200 1210         # the players around me

All of it is O(log N), milliseconds even with 10 million members.

Practical issues:

  • Ties. A sorted set orders equal scores lexicographically by member name — which is unfair. If whoever reached the score first must rank higher, make the score composite: score * 1e10 + (MAX_TS - timestamp). Mind double precision (53 bits).
  • Periods. A weekly/monthly leaderboard is a separate key, with a TTL on the old one. Starting a new period = a new key, nothing gets cleaned up.
  • Reliability. The score is also written to the DB (or an event log). If Redis is lost, the leaderboard is rebuilt.
  • Very large volume. Hundreds of millions of members won't fit in one Redis's memory, and one key lives on one node. Keep the top 1000 exact and, for the rest, use a histogram by score range to say "you're ahead of 87% of players" — many games do this.
  • A regional/friends leaderboard — separate small sets, or take the friends' scores with ZMSCORE and sort them in the application.