{}DSA Atlas

Design a Real-Time Leaderboard

Rank hundreds of millions of players in real time — Redis sorted sets and their complexity, score updates and tie-breaking, top-N and "my rank ± neighbours" queries, time-windowed (daily/weekly) boards, sharding when one sorted set isn't enough (score-range partitioning, approximate ranks via histograms), friends leaderboards, durability and anti-cheat.

Intermediate → Advanced5 interview questions

1. Requirements

Functional

  • Update a player's score after each match (increment or set best score).
  • Top N (e.g., top 100) globally; player's own rank and the players around them.
  • Daily, weekly, all-time boards; friends leaderboard.

Non-functional

  • 50M DAU, 500M total players; 20k score updates/s peak, 100k rank reads/s.
  • Rank visible within ~1 s of a match ending.
  • Leaderboard reads p99 < 50 ms.

2. API

HTTP
POST /v1/scores            {"player_id": "p_7", "match_id": "m_9", "delta": 120}    (server-to-server, idempotent by match_id)
GET  /v1/leaderboards/global?period=weekly&top=100
GET  /v1/leaderboards/global/players/p_7?period=weekly&around=5
GET  /v1/leaderboards/friends/p_7?period=weekly

3. High-level design

game servers(match results) score servicevalidate · dedupe Kafka scores DB(source of truth) leaderboardupdater RedisZSETs perboard/period players leaderboard API+ profile hydrate top-100 cache(1 s TTL)
Durable score events feed a rebuildable in-memory ranking view.

4. Core operations

import time

PERIODS = lambda ts: [f"lb:daily:{time.strftime('%Y-%m-%d', time.gmtime(ts))}",
                      f"lb:weekly:{time.strftime('%G-W%V', time.gmtime(ts))}",
                      "lb:alltime"]

def record(r, player_id, match_id, delta, ts):
    if not r.set(f"seen:{match_id}", 1, nx=True, ex=7 * 86400):   # idempotent per match
        return
    with r.pipeline() as p:
        for key in PERIODS(ts):
            p.zincrby(key, delta, player_id)
        p.expire(PERIODS(ts)[0], 8 * 86400)
        p.expire(PERIODS(ts)[1], 35 * 86400)
        p.execute()

def top(r, key, n=100):
    return r.zrevrange(key, 0, n - 1, withscores=True)

def around(r, key, player_id, k=5):
    rank = r.zrevrank(key, player_id)               # 0-based
    if rank is None:
        return None, []
    start = max(0, rank - k)
    return rank + 1, r.zrevrange(key, start, rank + k, withscores=True)
ZINCRBY lb:weekly:2026-W41 120 p_7      O(log N)
ZREVRANGE lb:weekly:2026-W41 0 99 WITHSCORES
ZREVRANK lb:weekly:2026-W41 p_7         → 48211
ZREVRANGE lb:weekly:2026-W41 48206 48216 WITHSCORES

5. Deep dives

Scaling beyond one sorted set

shard Ascore ≥ 10,000 · 80k shard B2,000–9,999 · 4M shard C500–1,999 · 40M shard D< 500 · 450M rank(p in C) = |A| + |B| + local rank in C bottom shards can switch to histogram-based approximate rank
Range partitions keep global rank cheap: sum counts of higher bands, add the local rank.
ApproachTop-NMy rankNotes
Single ZSETO(log N + N)O(log N)up to ~tens of millions of players
Hash-sharded ZSETsmerge each shard's top-Nsum of ZCOUNT above my score on every shardsimple, O(shards) per rank query
Score-range shardstop shard onlycounts of higher shards + local rankrebalancing as distribution shifts
Top-K exact + histogramexact for toppercentile estimate for the restcheapest at huge scale

Friends leaderboard

Friends lists are small (≤ a few hundred): fetch friend IDs, ZMSCORE their scores from the period ZSET, sort in the app. Cache per user for a short time.

Rebuild and durability

Scores DB (or event log) is authoritative; on Redis loss, rebuild all-time from the DB (SELECT player_id, total) via pipelined ZADD in batches; rebuild period boards from events in the period.

6. Trade-offs

DecisionChoice
Ranking storeRedis sorted sets (exact, in memory)
Source of truthdurable score events / DB
Scale-outscore-range shards or exact top-K + approximate percentiles
Freshnessupdates via stream within ~1 s; top-N cached briefly
Integrityserver-authoritative scores, idempotent by match ID

Interview questions

0 / 5 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.