CSE Roadmap

Common tier · about 4 hours · 8 parts

Part 3 of 8 · 2 min read

First design

Game service and leaderboard service.

Two services. The game service runs matches and checks that a win is real. The leaderboard service keeps scores and answers ranking questions.

Flow.

  1. A player wins a match. The client tells the game service.
  2. The game service checks that the win is valid.
  3. It calls the leaderboard service to add a point.
  4. The leaderboard service updates the leaderboard store.
  5. A player asks the leaderboard service directly for the top 10 or their rank.

Why the game service sets the score and not the client. If the client sent the score, a cheater could run a proxy and change it. So only the game servers may call the update API. For a game where the server already runs the whole match, such as online poker, the server knows when it ends and can set the score by itself.

Is a queue needed between the services? Only if the same score events feed other consumers such as analytics, push notifications or turn-based alerts. Then a log such as Kafka lets each read the stream (page 1 of this level). This case has no such need, so the design leaves it out.

First try: a relational table. One table per month with user id and score. A win adds a point, or inserts a first row. The rank of a player needs the table sorted by score, then a count of players ahead.

The trouble: ranking needs the whole table in order. With millions of rows and constant changes, this takes tens of seconds. A cache does not help, since the data changes all the time. An index and a LIMIT make the top 10 faster, but a player in the middle still needs a scan.

A worked example (made up). The table has 25 million rows. To find the rank of one player, the database counts rows with a higher score. Even at an optimistic 5 million rows per second, a scan takes 5 seconds, far too slow for 50 reads per second, each taking a full table's work.

Common mistake

Trusting the client to report its own score. Anything the client sends can be forged, so the server must decide.

Check yourself: 1. Why does the game service call the leaderboard service, and not the client? 2. When would a queue be justified? 3. Why does the relational rank query not scale?