Design a global game leaderboard

    A real-time leaderboard ranks millions of players by score and answers both top-N and "what's my rank?" queries with low latency. The key insight is using a sorted data structure (Redis ZSET) instead of sorting a database on every read.

    Real-Time & Messaging, 10 components, about 30 min

    1. Scope

    In scope

    • • Submit scores
    • • Top-N query
    • • Arbitrary player rank
    • • Time-bounded boards (daily/weekly)

    Out of scope

    • • Matchmaking
    • • Anti-cheat ML deep-dive
    • • Social/friends leaderboards

    2. Functional requirements

    Must have

    • • Update a player's score
    • • Get top N players
    • • Get a specific player's rank
    • • Daily/weekly/all-time variants

    Nice to have

    • • Around-me view (±5 ranks)
    • • Regional boards
    • • Percentile

    3. Non-functional requirements

    Query latency< 50 ms
    ScaleMillions of players
    ConsistencyNear-real-time
    DurabilityScores persisted, not just cached

    4. Back-of-envelope estimation

    Assumptions

    • • 10M active players
    • • 50K score updates/sec peak
    • • Top-100 queries common
    • • Multiple time windows

    Derived numbers

    Update QPS~50K/s
    ZSET opsO(log n) per update/rank
    MemoryGBs per board— 10M members

    5. API design

    POST/api/scores

    Submit/update a player score

    GET/api/leaderboard?top=100

    Top-N players

    GET/api/rank/{player}

    A player's current rank

    6. High-level design

    What each box in the reference diagram is responsible for:

    Score API — Validates and writes scores.
    Anti-cheat — Server-side validation before accepting a score.
    ZSET shards — Per-region sorted sets (score → player).
    Merger — Aggregates regional top-K into global.
    Score Archive — Postgres durability for scores.
    Snapshot Job — Daily/weekly board snapshots.

    7. Data model

    Redis ZSET: board:{window} → (player → score)— O(log n) ops
    Postgres: scores(player, value, ts)— Durable archive

    8. Deep dives

    Why a sorted set

    A relational "ORDER BY score LIMIT 100" re-sorts millions of rows on every read. A Redis ZSET keeps members sorted by score continuously: ZADD is O(log n), ZREVRANGE for top-N is O(log n + N), and ZREVRANK for "my rank" is O(log n). This is exactly the data structure the problem needs.

    Sharding + global merge

    A single ZSET caps out. Shard by region: each region has its own ZSET, updates stay local. For a global board, periodically merge the top-K from each shard (the global top can only come from regional tops). "My global rank" is harder — approximate by summing counts above your score across shards.

    Durability + time windows

    Redis is the fast serving layer, but scores must survive restarts — write-through to Postgres. For daily/weekly boards, use separate ZSETs per window (board:daily:2024-05-28) and let them expire, or snapshot periodically for historical views.

    Anti-cheat

    Never trust client-submitted scores. Validate server-side (plausible deltas, replay/signature checks) before ZADD, so a tampered client can't inject impossible scores into the board.

    9. Bottlenecks

    • Single ZSET capacity → shard by region
    • Global rank across shards → approximate or periodic merge
    • Hot write key → batch updates, write-through async

    10. Trade-offs

    Redis sorted set or database index

    Choose: Redis ZSET per board (ZADD, ZREVRANK, ZREVRANGE are O(log n)), with scores persisted to a database for durability.

    Instead of: SQL ORDER BY with an index: exact and durable, but rank-of-user queries need COUNT(*) WHERE score > x, which is slow at 10M rows.

    Rank lookup is the core query; ZSET answers it in microseconds.

    Exact or approximate ranks at huge scale

    Choose: Exact for the top N and for boards up to tens of millions; approximate percentile buckets beyond that.

    Instead of: Exact global rank for 1B players: needs a sharded rank structure and cross-shard counting.

    Players care about exact rank near the top and a percentile elsewhere.

    Time-windowed boards

    Choose: Separate ZSET per window (daily:2026-11-16) with TTL, written alongside the all-time board.

    Instead of: Store timestamps and filter at read time: impossible with ZSET ranking.

    Writes double or triple, but every read stays O(log n).

    11. Failure modes

    Redis node lost

    Board missing until rebuilt.

    Mitigation: Replica with automatic failover; rebuild from the durable score table if both are lost.

    Cheaters submit impossible scores

    Top of the board is fake.

    Mitigation: Server-authoritative scoring or validation of game events, anomaly detection, and a shadow-ban that hides scores from others.

    One board becomes too large for one node

    Memory exhaustion.

    Mitigation: Shard by score range, keep per-shard counts, and compute global rank as the sum of counts in higher shards plus local rank.

    12. What interviewers probe

    Answer each one yourself before opening it.

    How do you break ties?Show a strong answer

    Encode the tie-breaker into the score, for example score × 2^32 + (MAX_TS − achieved_at), so earlier achievers rank higher. Redis scores are doubles, exact only up to 2^53, so this works for scores below about 2 million; beyond that, store the tie-breaker separately.

    Show me the friends leaderboard.Show a strong answer

    Fetch friend ids, ZMSCORE them from the global board, sort client-side; friend lists are small so no separate board is needed.

    How much memory for 10M players?Show a strong answer

    Roughly 100 bytes per member in a skip-list ZSET, so about 1 GB per board; windows multiply that.

    What happens at 50K updates/s?Show a strong answer

    A single Redis node handles that; batch with pipelining, and only update when the new score beats the old (ZADD GT).

    Sign in to track this guide in your curriculum progress.