System Requirements
Functional requirements:
We’ll focus on the following requirements to design a chess game server. The system should have:
- Support for two online players to play a game of chess.
- A matching algorithm to match the peers
- A game engine where: a. Match requests with an interval of min and max rating for opponents. b. Game info is stored. c. One side is assigned white and the other black.
- A chat application.
- Move validation.
- Both players will play their moves one after the other. The white side plays the first move.
- Players can’t cancel or roll back moves.
- Log of all moves made by either player.
- A game termination state. The game can finish either in a checkmate from one side, forfeit or stalemate (a draw), or resignation.
- Checks for cheating by players (making the same moves as an engine).
Non-Functional requirements:
- Low Latency
- Low Bandwidth
- Fault-tolerant
- The system should be consistent
Capacity Estimation:
- How many users connect at a time? Let us assume 1M DAU(Daily Active Users) Active users/ min = 1M/(24*60) = 900 users/ min Let us assume that, on average, a game lasts for 5 mins. Then we can assume a load of 5000 connected users. In place of any event/ peak, we can consider this value equal to 20K connected users.
- Capacity to be computed by matching engine If we assume each request to have a size 1KB, we can have total memory be 20K * 1KB = 20MB We are using a Balanced BST to find O(logN) matches. That's 20K*log(20K) = 300K instructions.
Design Process :
- Matching Engine - a. Close-rated players should play each other. b. Matching engine service can have a cache of all challenge requests with max and min rating, maintained in a TreeSet or SortedSet. This data structure makes search requests fast. c. Store all the requests in a memory with an example for TTL(Time To Live) of 30 seconds. d. An SQL Database is used here to index time and rating ranges.
- Analysis Engine - a. Batch Processing of games, run with engines like Stockfish. b. Look at the "Workflow Management Platform" for more details.
- Game Engine - a. Bidirectional connection to accept the move and then make a note of it. For this For bi-directional connection, we use WebSockets.
Can we avoid the connection between client and server?
- We can’t do that because we use the game engine to validate moves.
- The client code or requests may be compromised. Hence it cannot be used as a source of truth.
- To validate the move, we store the state of the game and check if it's legal on the server.
Classes :
- Game Engine
- Matching Service
- Chat Service
Scaling :
- The system shards requests based on request IDs.
- The system caches user and game information.
APIs:
- makeMove(gameId, userId, Move)
- getGame(gameId, userId)
- createChallenge(userId, challenge)
- sendMessage(gameId, userId, message)
- getMessages(gameId, userId)
Architectural Design :
That's it for now!
You can check out more designs on our video course at InterviewReady.