#62 State Management/WebSockets
Online Chess Platform
Pair players by skill, relay moves in real time, enforce the rules and the clock on the server, and survive a dropped connection.
What is being asked
Design an online chess service: matchmaking, live games with clocks, spectators and game history. It is a clean example of server-authoritative real-time state.
Requirements
Functional
- Find an opponent of similar rating for a chosen time control.
- Play: validate moves, run clocks, detect checkmate, draw and timeout.
- Reconnect to a game in progress; watch games; store history and update ratings.
Non-functional
- Moves relayed in tens of milliseconds.
- Clocks fair despite network delay.
- Millions of concurrent games, each small.
Design
- A player joins a pool for a time control. The matchmaker pairs players whose ratings are close, widening the allowed gap the longer someone waits.
- A game is created and both players' connections are attached to it.
- A move goes to the game service, which loads the game, checks that it is that player's turn and that the move is legal, applies it, updates the clocks and saves the new state.
- The move is sent to the opponent and to spectators.
- When the game ends it is archived and both ratings are updated.
Key decisions and trade-offs
- The server is the authority. Clients never decide legality or time; this is what prevents cheating by a modified client.
- State is the move list. A game is a few hundred bytes. Keeping it in a fast store keyed by game id lets any server handle the next move, so a crashed server loses nothing.
- Clock fairness. The server measures thinking time between its own send and receive, with a small allowance for network delay.
- Reconnection. The client reconnects with the game id and the number of the last move it saw, and receives what it missed.
Follow-up questions
- How would you detect a player using a chess engine?
- How do you broadcast a world championship game to a million spectators?
- What happens if both players disconnect?
- How would you run a tournament of ten thousand players?