Infrastructure · Design 31

Design Leaderboard

Design a real-time game leaderboard in a 45-minute interview: Redis sorted sets and their costs, top-k versus my rank, ties, monthly resets, sharding and approximate ranks.

IntermediateInterview priority: Medium55 min
On this page
  1. How to use this page
  2. 1. Clarify the requirements
  3. 2. Back-of-the-envelope estimates
  4. 3. API
  5. 4. Data model
  6. 5. High-level design
  7. 6. Deep dives
  8. 7. Bottlenecks, failures and monitoring
  9. 8. Follow-up questions
  10. Quiz

How to use this page

This page follows the order of a real system design interview. At each step there is a Your turn box: write your own answer first, then open ours and compare. A leaderboard is a small system with one sharp question, "what is my exact rank among 50 million?", and the interview is about choosing the data structure that answers it and then pushing that structure to its limits.

PhaseTime in a 45-min interviewWhat you produce
1. Clarify requirements5 minWhich boards, exact or approximate ranks, resets, who submits scores
2. Estimate3–5 minUpdates/s, reads/s, memory for one board
3. API3 minSubmit a result, top N, my rank and neighbours
4. Data model5 minSorted set, durable score events, totals
5. High-level design10 minWrite path and read path traced
6. Deep dives10–15 minRanking structure, ties, resets, sharding, friends boards
7. Wrap up2–3 minBottlenecks, failures, what you would monitor

When a player wins a match their score increases. Show the global top 100, a player’s own rank and score, and the players just above and below them. Leaderboards reset every month, and we keep past months. Also support friends-only leaderboards. Skip matchmaking, anti-cheat detail and in-game rewards.

1. Clarify the requirements

Your turn: scope it

The interviewer says: "Design a leaderboard for an online game." Write the questions you would ask, the functional and non-functional requirements with targets, and what you would leave out.

Compare with our answer

The questions that matter most: How many players? Does every player need an exact rank, or only the top? How quickly must a match show up? Do boards reset (daily, monthly, seasons)? Who reports scores: the game client or a game server? How are ties ordered?

A strong answer mentions: top 100 · my exact rank and neighbours · monthly reset with history · friends boards · latency under ~50 ms and freshness of a second or two · server-authoritative scores · matchmaking and anti-cheat out of scope.

Functional: what it must do

  • Update score after a match: Wins add points
  • Global top 100
  • My rank and score: Exact rank, even far down
  • Players around me: 5 above and 5 below
  • Monthly reset and history
  • Friends leaderboard: Rank among my friends

Out of scope

MatchmakingAnti-cheat detailRewards and prizes

Non-functional: how well it must work

QualityTargetWhy
Latency< 50 ms for top 100 and my rankPlayers check constantly
FreshnessRank reflects a match within a second or two
CorrectnessNo lost score updates; deterministic ties
Availability99.9%Not life-critical, but very visible
Scale50 M monthly players; ~3.5 K score updates/s at peakBursts when tournaments end

2. Back-of-the-envelope estimates

Your turn: the numbers

Assume 50 M monthly players, 20% playing on a given day, 10 matches each, a peak of 3× the average, and about 100 bytes per leaderboard entry. Work out peak score updates per second, rank reads per second (players check after most matches, twice each), and the memory for one month's board.

Compare with our answer
  • Daily players: 50 M × 20% = 10 M. Matches: 100 M a day ÷ 86,400 ≈ 1,160/s; ≈ 3,500/s at peak.
  • Reads: about twice that, ≈ 7,000/s at peak, plus top-100 views (cached).
  • Memory: 50 M × 100 bytes = 5 GB for one board, plus a replica.
  • Rank cost: a balanced ordered structure needs about log₂(50 M) ≈ 26 steps per update or rank query.

A strong answer mentions: updates/s with a peak factor · reads dominate but are cheap · one board fits comfortably in one machine's memory · O(log n) per operation · tournament-end bursts above the 3× average peak.

Assumptions: monthly players 50 M; daily players (%) 20; matches per player per day 10; peak vs average 3; bytes per leaderboard entry 100 B.

NumberEstimateWhy it matters
Score updates per second (peak)3.47 K / s≈ 3,500/s: easy for one in-memory sorted set.
Memory for one month’s leaderboard5 GB≈ 5 GB: one Redis instance (plus a replica) can hold it.
Rank reads per second6.94 K / sPlayers check after most matches.
  • A sorted set gives O(log n) updates and rank queries: log₂(50 M) ≈ 26 steps.
  • Durability: write each score change to a database too, so Redis can be rebuilt.

The numbers say one Redis node is enough for a board of this size: a Redis node handles ~100 K+ simple operations a second, and we need around 10 K. The hard parts are correctness (no lost or doubled points), the reset, and what happens when the game is 10× bigger.

3. API

Your turn: the API

Which calls do the game server and the player's app need? Which one must be idempotent, and who is allowed to call it?

Compare with our answer

A strong answer mentions: a score submission from the game server only, carrying a match id for idempotency · top N (cacheable, same for everyone) · my rank plus neighbours (personal, not cacheable) · friends board · a month parameter for history.

CallRequestResponseNotes
POST /v1/scores{ playerId, matchId, points }200 { score, rank }Called by the game server, never the client; (matchId, playerId) makes it idempotent
GET /v1/leaderboard/top?limit=100–{ entries[{ rank, playerId, score }] }Cached for a second or two
GET /v1/leaderboard/players/{id}–{ rank, score, around[] }My rank + neighbours
GET /v1/leaderboard/friends/{id}–{ entries[] }Friends only
GET /v1/leaderboard/top?month=2026-09–{ entries[] }Past months

POST /v1/scores is called only by trusted game servers, authenticated with service credentials. A phone that sends "I scored 30 points" can be modified to send "I scored 30 million". The (matchId, playerId) pair makes the call idempotent: a retry after a timeout is recognised and ignored, so points are never added twice. See duplicates and idempotency.

4. Data model

Your turn: the stores

Where does the ranking live, what is the source of truth, and how do you rebuild the ranking if it is lost?

Compare with our answer

A strong answer mentions: a sorted set per month in memory · a durable table of score events with a unique (match, player) key · a durable per-player monthly total · rebuilding the sorted set from the totals · friends lists from the social graph.

live leaderboard Redis sorted set (ZSET)

  • key: lb:2026-10
  • member: player_id
  • score: points (with tiebreak encoded)

Kept sorted in memory (skip list): ZADD … GT with the player’s new total (safe to replay, unlike ZINCRBY), ZREVRANK for rank, ZREVRANGE for top N.

score events Durable log / SQL

  • (match_id, player_id) unique, points, ts

Source of truth: every match result, so the sorted set can be rebuilt and disputes checked.

player totals SQL / key-value

  • player_id, month, score, updated_at

Durable copy of each player’s monthly score, written behind the sorted set.

friends Social graph service

  • player_id → friend_ids[]

Friends lists for friends-only boards.

A sorted set (Redis calls it a ZSET) is a collection of unique members, each with a numeric score, kept ordered by score. Internally Redis combines a hash table (member → score, for O(1) lookups) with a skip list: a linked list with extra "express lanes" of pointers that skip over many nodes, so searching it takes O(log n) steps, like a balanced tree. Each skip-list node also records how many nodes each pointer jumps over, which is what makes "what is my rank?" O(log n) instead of a count.

5. High-level design

Your turn: draw it

Sketch the write path from the end of a match to the sorted set, and the read path for "my rank" and for the top 100. Where is the durable copy?

Compare with our answer

Compare with the figure. The pieces people most often forget: the queue in front of the updater (tournament ends cause bursts), the durable store written before the sorted set, and caching the top 100, which is identical for every player.

The architecture, then a match result traced through it

  1. The architecture: trusted game servers send match results to a leaderboard API. A queue and updater apply them to an in-memory sorted set and record them durably. Reads hit replicas of the sorted set, with the top 100 cached, and friends boards combine the friends service with score lookups.
  2. The game server, not the player’s phone, reports the result with a match id. It’s queued. An updater records it durably and adds the points to the player’s monthly total, then writes that total into the sorted set, which moves the player to the right place in logarithmic time.
ComponentWhat it does
Leaderboard APIWrites from game servers only; reads for players
Score events queueBuffers bursts; enables replay
Score updaterIdempotent by (matchId, playerId); durable total first, then ZADD GT
Sorted set (Redis)One key per month; rank and range queries in O(log n)
ReplicasServe reads
Scores DB + archiveDurable source of truth; past months archived
Friends serviceFriend lists for friends-only boards

Trace the write:

  1. The game server reports +30 points, match 9812 for ana. The API puts it on a queue.
  2. The updater inserts the event into the scores table, where (match_id, player_id) is unique, and adds 30 to ana's monthly total in the same transaction. A duplicate insert fails, and the updater skips it.
  3. It writes the new total to Redis: ZADD lb:2026-10 GT 1530 ana, which moves ana to her new position in O(log n).
  4. Replicas receive the change asynchronously and serve reads.

Two reads: my rank with neighbours, and the cached top 100

  1. Asking for my rank is one sorted-set call, ZREVRANK, which counts how many players are above me in logarithmic time. A second call fetches the five players above and below.
  2. The top 100 is the same for everyone, so it’s fetched once with ZREVRANGE and cached for a second or two; thousands of players share that cached answer.

The two reads are very different in cost. Top 100 is identical for everyone, so one ZREVRANGE lb:2026-10 0 99 WITHSCORES every second or two, cached, serves every player. My rank is personal and can't be shared, but ZREVRANK is O(log n), and the neighbours are one ZREVRANGE around that rank (O(log n + 10)). In Redis 6.2 and later the same range is written ZRANGE … REV.

6. Deep dives

Your turn: the hard parts

Two or three sentences each: why not SELECT COUNT(*) WHERE score > mine? How are ties ordered? How does the monthly reset work? What do you do when the board no longer fits on one machine?

Compare with our answer

A strong answer mentions:

  • An ordered structure with rank counts (skip list or order-statistic tree) gives O(log n) rank; a SQL count is O(rows above you).
  • Deterministic ties encoded into the score (earlier achiever first), with the floating-point limit.
  • A new key per period; archive, then expire the old one.
  • Sharding by player hash (scatter-gather) or by score range (one lookup, but rebalancing), and approximate ranks for the long tail.

Exact rank: why a sorted set

A sorted set keeps players ordered, so rank and update both take about 26 steps

  1. Deep dive: ranking. A sorted set, built on a skip list, keeps players ordered by score, so both updates and “what’s my rank?” take about twenty-six steps for fifty million players.
OptionRank query costCatch
SQL SELECT COUNT(*) FROM scores WHERE score > :mineIndex range count: O(players above you)Player 4,512,307 counts 4.5 M index entries on every request
Recompute ranks in a batch job every hourO(1) readRanks an hour stale; players notice immediately after a match
Sorted set (skip list) in memory (chosen)O(log n) ≈ 26 stepsMust fit in memory; needs a durable copy behind it

The Redis commands and their costs, which interviewers like to hear:

CommandDoesCost
ZADD key score memberInsert or update a scoreO(log n)
ZINCRBY key delta memberAdd to a scoreO(log n)
ZSCORE key memberOne player's scoreO(1) (hash lookup)
ZREVRANK key memberRank from the top, 0-basedO(log n)
ZREVRANGE key start stopPlayers by rank rangeO(log n + m) for m results
ZCOUNT key min maxPlayers within a score rangeO(log n)

Remember that ZREVRANK is 0-based: the leader's rank is 0, so show rank + 1.

Ties: same score, who is higher?

When two players have exactly 1,500 points, Redis orders them by member name (byte order), so amy always beats zoe. That's deterministic but unfair. Two common rules:

  • Whoever got there first wins. Encode the time into the score so one number orders both: combined = points × 10⁷ + (10⁷ − 1 − seconds_since_month_start). Higher points always win; among equal points, the earlier time gives the larger value. A month is ~2.7 M seconds, so 10⁷ leaves room.
  • Shared rank. Both players are "5th". Compute rank as ZCOUNT key (my_score +inf plus one: the number of players with a strictly higher score, plus one. Also O(log n).

Monthly resets and history

"Reset at midnight on the 1st" sounds like deleting 50 M entries at once, a huge burst and the end of history. Instead, name the key by period: lb:2026-10, lb:2026-11. The updater writes to the key for the current month, so at midnight new scores simply land in the new, empty key; nothing is deleted. The old key is still readable for "last month's final standings". After the month closes, a job snapshots it (every player's final rank and score) into the database or warehouse, then sets EXPIRE on the old key.

The same trick gives daily and weekly boards: one score event updates lb:day:2026-10-14, lb:week:2026-W42 and lb:2026-10 in one pipelined call. Decide the reset's time zone up front (usually UTC), or players in one region see the board reset in the middle of their evening.

Friends leaderboards

A player has a few hundred friends at most. Fetch their ids from the friends service, look up all their scores in one call (ZMSCORE lb:2026-10 f1 f2 …, Redis 6.2+, or pipelined ZSCOREs), and sort the few hundred results in the application. That's a millisecond of work and needs no extra storage. Precomputing one sorted set per player's friends would mean updating hundreds of sets on every score change, so don't.

Too big for one machine: sharding and approximate ranks

The game grows to 500 M players: ~50 GB per board and many more writes. Still possible on one large node, but let's split it.

OptionHowCatch
Shard by player id (hash)Each shard is a sorted set for a slice of playersTop 100: take each shard's top 100 and merge (cheap). My rank: ZCOUNT above my score on every shard and sum, so one request fans out to all shards
Shard by score rangeEach shard holds one band of scores, with a cached count per shardOne shard lookup per rank, but players cross bands as scores grow, bands drift out of balance, and the top shard is hottest
Approximate ranks for the long tailA histogram of how many players have each score bucket"Top 12%" is cheap and stable; exact ranks only for, say, the top 100 K

Ranking across score-range shards, and where it breaks

With 10 hash shards, a rank query is 10 parallel ZCOUNTs, each O(log n): fine. With 1,000 shards, the fan-out dominates, and score-range sharding or approximation wins. Many large games combine them: an exact sorted set for the top players and a histogram for everyone else, where a player's rank is "players in all higher buckets + an estimate within their own". Players far down the board rarely care whether they are 4,512,307th or 4,512,310th.

Building the histogram

Keep a counter per score bucket (say 10,000 buckets of 10 points each) in Redis or in memory in the rank service. When a score changes from bucket a to bucket b, decrement a and increment b. A rank estimate is the sum of counts in all higher buckets, served from a prefix-sum array rebuilt every few seconds. It's O(1) per read, a few kilobytes of memory, and exact to within one bucket's population. See hot keys and hot partitions for spreading the counter writes if one bucket gets hot.

7. Bottlenecks, failures and monitoring

Scaling bottlenecks

BottleneckFix
Read loadReplicas; cache the top 100; cache “around me” briefly
Very large player countsScore-range sharding, or approximate ranks for the long tail
Bursty writes (tournament end)Queue in front of the updater
Friends boardsFetch friend ids, then ZSCORE each (pipelined), sort a few hundred in memory

When things fail

FailureWhat happens
Redis primary failsPromote a replica; replay recent score events from the queue/DB
Updater crashesEvents remain in the queue; idempotent by matchId
Corrupted leaderboardRebuild the sorted set from the durable scores table

What to monitor

Rank query latencyScore update lagQueue depthRedis memoryReplica lagSuspicious score jumps (anti-cheat)

8. Follow-up questions

Your turn: the interviewer pushes

Answer in order. 1) A tournament ends and 2 M results arrive in one minute. What happens? 2) Product wants regional and weekly boards as well as the global monthly one. What changes? 3) The game reaches 500 M players and the board no longer fits one node. What do you do?

Compare with our answer

A strong answer mentions:

  1. ~33 K updates/s: the queue absorbs the burst; updaters batch writes to the database and pipeline ZADDs; ranks lag by seconds, which is acceptable; the top-100 cache shields reads.
  2. One sorted set per (scope, period); each event updates several keys in one pipelined call; memory multiplies by the number of boards, so expire short-period boards quickly.
  3. Shard by player hash with scatter-gather for rank, or score-range shards with cached counts, or exact ranks only near the top plus a histogram for the long tail; say which you pick and why.
How would you show regional leaderboards?

One sorted set per region (and per month); a score update writes to the global and regional keys.

How do you keep history?

At month end, snapshot the sorted set (top N + every player’s final rank) into the database / data warehouse.

Can you do this without Redis?

Yes: a skip list or order-statistic tree in your own service, or a database with window functions for small boards.

Leaderboard on one page
  • Numbers: 50 M players ≈ 5 GB per board; ~3.5 K updates/s and ~7 K rank reads/s at peak; log₂(50 M) ≈ 26 steps.
  • Structure: Redis sorted set (hash + skip list with span counts). ZADD/ZINCRBY/ZREVRANK O(log n), ZSCORE O(1), ranges O(log n + m).
  • Top 100 is shared: one ZREVRANGE, cached 1–2 s. My rank is personal: ZREVRANK (0-based) + neighbours.
  • Writes: game server only; idempotent by (matchId, playerId); durable total first, then ZADD … GT total.
  • Ties: encode "first to reach it" into the score; stay within 2⁵³; or shared ranks via ZCOUNT.
  • Resets: one key per period; archive the final standings; EXPIRE the old key.
  • Friends: fetch ids, ZMSCORE, sort a few hundred in the app.
  • Scale out: hash shards + scatter-gather, score-range shards + cached counts, or a histogram for the long tail.
Mock interviewPractise it as a mock interview: scope, size and the big decisionsOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. Player 4,512,307 opens the leaderboard, and the service runs SELECT COUNT(*) FROM scores WHERE score > :mine on an indexed column. Why is this slow at scale?

2. A score event is delivered twice after an updater crash. Which write to Redis makes the replay harmless?

3. Two players both have 1,500 points, and product wants whoever reached it first to rank higher. You encode points × 10¹³ − unix_time_ms as the score. What goes wrong?

4. How should the monthly reset at midnight on the 1st be done?

5. The board is sharded by player-id hash across 10 Redis nodes. How do you get one player's exact rank?

6. A friends board must show a player's 300 friends ranked by score. What is the cheapest correct approach?

7. Why is the top 100 cached for a second or two while "my rank" is computed per request?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.