AlgoViz

Design a Multiplayer Game Leaderboard

easy 45 min

Keep 250 million players in order while results arrive all the time, and tell any of them their place in milliseconds.

See it run

Follow a result to the board, a top list from the edge, one player's place, a friends board and a place from bands.

Operations

A result arrives

Stored first, then ordered.

Step 1 of 7

The match ends

Our systemGame serverResult intakeResult logScore workerPostgreSQLbest scoresRedissorted setLive gateway

score

48,500

The game server sends the result with its signature, match, player, mode and time.

Step 1: The match ends

def worker(result):    row = db.keep_best(result.board, result.player, result.score)    redis.zadd(result.board, {result.player: pack(row)}, gt=True)    live.send(result.player, places(result))
Time
2 to 5 s to the board
Steps or calls
one append

Accepted means it is in the log. Everything after that can be done again.

In the real world

The same design a multiplayer game leaderboard doing real jobs. Pick one and step through it.

Results wait. The top list stays.

Step 1 of 4

The primary dies

Our systemGame serverResult intakeResult logScore workerPostgreSQLbest scoresRedissorted setLive gateway

The last writes may be missing on the replica, because replication is asynchronous.

Step 1: The primary dies

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A rank column

    critical

    One score changes the rank of everybody it passes.

    Wrong
    UPDATE players SET rank = rank + 1WHERE rank BETWEEN 1520 AND 1649
    Right
    i = redis.zrevrank(board, me)
  • Believing the device

    critical

    A changed app can send any number.

    Wrong
    score = request.json["score"]   # from the app
    Right
    result = verify(game_server_signature, body)
  • Clearing the board at midnight

    major

    Late results land in the wrong week and the delete blocks others.

    Wrong
    redis.delete("board:weekly")
    Right
    board = f"board:{week(ended_at)}"
  • Milliseconds in the packed score

    major

    They spill into the score or lose digits above 2^53.

    Wrong
    packed = score * 10**10 + (MAX_MS - now_ms)
    Right
    packed = (score << 20) + (LOW - seconds_of_week)
  • Pushing every move

    major

    2.3 million messages a second that almost nobody reads.

    Wrong
    for p in passed_players: push(p)
    Right
    push(result.player)

Interview tips

  • Split the reads

    • Top lists are shared: CDN, 10 s.
    • Places are personal: sorted set.
    • Say both numbers.
  • Own the score elsewhere

    • Log, then PostgreSQL, then Redis.
    • Rebuild time is part of the answer.
    • Repeats change nothing.
  • Be exact where it matters

    • Top million: exact.
    • Long tail: percentile.
    • Prizes: frozen copy.
  • Ask about the score

    • Best, sum or rating?
    • Who sends it?
    • How are ties ordered?