Lesson 5 of 15
35. Design a Leaderboard (Top-K)

35.4 What do we store?

3 min read+10 XP
teams (database: who picked whom; written before the match, then frozen) team_id, user_id, contest_id, players[11], captain, vice_captain, joined_at player_points (small: 22 players per match) match_id, player_id, points, as_of_event leaderboard (Redis sorted sets, one per contest, sharded by team) key: lb:{contest}:{shard} member: team_id score: composite(points, joined_at) (35.8) finals (database, written once at the end, audited) contest_id, team_id, final_points, final_rank, prize

Interviewer pushback:

  • "Why a sorted set?" → It keeps members ordered by score with logarithmic time for update (ZADD), rank (ZREVRANK) and range (ZREVRANGE), and counts by score range (ZCOUNT). That's exactly "update score", "my rank" and "top 100". A SQL ORDER BY points over 20 million rows on every refresh would be far too slow.

Memory code: "Teams in the database, ranks in a sorted set, prizes in an audited table."