Design a Multiplayer Game Leaderboard
easy 45 minKeep 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
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
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
criticalOne score changes the rank of everybody it passes.
WrongUPDATE players SET rank = rank + 1WHERE rank BETWEEN 1520 AND 1649Righti = redis.zrevrank(board, me)Believing the device
criticalA changed app can send any number.
Wrongscore = request.json["score"] # from the appRightresult = verify(game_server_signature, body)Clearing the board at midnight
majorLate results land in the wrong week and the delete blocks others.
Wrongredis.delete("board:weekly")Rightboard = f"board:{week(ended_at)}"Milliseconds in the packed score
majorThey spill into the score or lose digits above 2^53.
Wrongpacked = score * 10**10 + (MAX_MS - now_ms)Rightpacked = (score << 20) + (LOW - seconds_of_week)Pushing every move
major2.3 million messages a second that almost nobody reads.
Wrongfor p in passed_players: push(p)Rightpush(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?