Black Friday: 30% off every plan through November 30. See the prices
SysDesignPrep.com
System design interview question

Design an Online Chess Game

Live chess for 1 M games at once: rating-based pairing, server-kept clocks that stay fair through lag and reconnects, spectators, engine detection and ratings.

Last updated 2026-11-21. Difficulty: hard. Patterns: gaming, actors, fencing, ratings, anti-cheat. Reported at Meta.

Sit this question with an AI interviewer.

An AI mock is timed like the real round, out loud or typed, and ends with a debrief scored for your level. Practice with AI, in every pass, has no clock and the AI Mentor beside you. Or watch a sample interview first.

Or sit it in the style of Meta, run as that company’s round is reported to go.

The short answer

How to design an Online Chess Game in a system design interview, in five steps:

  1. Scope it. Seek a game and be paired in seconds, play a live game with every move checked by the server, clocks kept by the server, with increments, survive disconnects, watch any live game, ratings per time-control category, detect engine use, game history and PGN.
  2. Set the targets. Scale: 1 M live games · 50 M games/day; Move latency: server adds p99 < 50 ms; Clock fairness: server clock · capped lag credit; No lost moves: acked = durable · resume < 10 s.
  3. Do the numbers. Game starts per second: ~580 avg · ~1.7 k peak; Moves per second at peak: ~120 k/s; Sockets and gateways: ~3 M sockets · 30 gateways.
  4. Draw the design. Play gateway, Game servers, Live move log, Slot leases, Matchmaker, Spectator gateway, Game channels, Game events, Rating service.
  5. Go deep where it is hard.
    • A fair clock over an unfair network → Server clock with a capped, budgeted lag credit.
    • One owner per game, and losing it safely → One owner in memory, every move a conditional write to a replicated log under an epoch.
    • Spectators and broadcasts → Separate spectator gateways, one subscription per gateway per game, snapshots from log replicas.
    • Detecting engine use → Screen every rated game, aggregate per player against their rating band, deep-analyse outliers, humans decide.
    • Rating updates exactly once → Two independent per-player updates from the start-of-game snapshot, each idempotent on (player, game).
    • Storing every game ever played → Compact games by id plus a per-player index, PGN rendered on read.
The Online Chess Game design, as drawn at the end of the walkthrough: Player app, Game server (one owner per game), Live move log (write if next ply), Play gateway (WebSocket), Slot leases (etcd, epoch), Matchmaker (pool per time control), Ratings store (by player), Spectators, Spectator gateways, Game channels (pub/sub), Game events (Kafka), Rating service (Glicko-2), Game archive (compact moves), Fair-play screening (engine fleet), Game pages & PGN (CDN) and History API (PGN on read).
The design at a glance. The architecture the walkthrough ends on. Watch it built step by stepOpen full size

Functional requirements

  • Seek a game and be paired in seconds. Pick a time control (1+0 bullet, 3+2 blitz, 10+0 rapid and so on), rated or casual, and get an opponent of similar rating. Or challenge a friend by link.
  • Play a live game with every move checked by the server. The full rules: check, castling rights, en passant, promotion, threefold repetition, the 50-move rule, insufficient material. Draw offers, resignation, and an abort before both sides have moved.
  • Clocks kept by the server, with increments. Each side’s remaining time is the server’s number, not the browser’s. Running out loses, unless the opponent has no way to mate, which makes it a draw. Network delay must not cost a player their time.
  • Survive disconnects. Your clock keeps running while you are away, as it would over the board. Reconnect from any device and the game continues from the last move; if you do not come back, the opponent can claim the win after a short wait.
  • Watch any live game. From a link, a profile or a list of top games, with moves and clocks live. A prize final or a famous streamer can draw hundreds of thousands of viewers to one game.
  • Ratings per time-control category. Glicko-2 ratings for bullet, blitz and rapid, updated after every rated game, with the change shown on the result screen.
  • Detect engine use. Find players who take their moves from a chess engine, close their accounts after review, and give rating points back to the players they beat.
  • Game history and PGN. Every game kept for good: "my games" with filters, a shareable page per game, and PGN download, the standard text format for chess games.
  • Out of scope. Correspondence games (days per move), tournaments, puzzles and lessons, chat, the opening explorer, post-game engine review (it reuses the analysis fleet) and how the engine works. Real-time action games are a different problem: see Design a Multiplayer Game Backend. Pairing in depth: see Design a Matchmaking System.

Non-functional requirements

  • Scale (1 M live games · 50 M games/day). 2 M players in games and 1 M spectators connected at the evening peak. An average game lasts ~10 minutes and ~70 plies (half-moves).
  • Move latency (server adds p99 < 50 ms). From a move arriving to the opponent’s copy leaving the server. In a 1-minute bullet game a player makes ~30 moves, so every 100 ms of overhead shows on the clock.
  • Clock fairness (server clock · capped lag credit). This is the requirement that drives the hardest trade-off. Network delay should not cost a player time, but the server cannot tell real lag from a client pretending to lag, so credit for delay has to be measured, capped and budgeted per game.
  • No lost moves (acked = durable · resume < 10 s). A move a player saw accepted survives any one server failure, and a crashed server’s games resume elsewhere within seconds. Unlike a shooter, a chess game’s whole state is its move list, so keeping it is cheap.
  • Integrity (one live game per player · ratings once). The client checks legality only for instant feedback; the server decides. One result per game, never reported by a client, and each rating change applied exactly once however often the result is delivered.
  • Fair-play precision (humans decide every ban). Closing an honest strong player’s account is worse than catching a cheater a few games later: it is public, it drives strong players away, and it is hard to undo. Statistics rank cases; people decide.
  • Spectators never slow players (any audience size). A crowd of 500 k watching one game must cost the server running that game’s clock nothing extra, and must not share gateways with players.
  • History (kept forever · my games p99 < 200 ms). Finished games never change, so they can be cached anywhere forever. "My games" must open fast even for a player with 300 000 games.

Back-of-envelope estimates

  • Game starts per second: ~580 avg · ~1.7 k peak. 50 M games a day ÷ 86 400 s ≈ 580/s. At the peak, 1 M live games that last ~600 s means ~1.7 k/s starting, about 3× the average. On average ~350 k games are live at once (580 × 600).
  • Moves per second at peak: ~120 k/s. 1 M live games × 70 plies ÷ 600 s ≈ 117 k/s. The daily average is 3.5 B plies ÷ 86 400 ≈ 40 k/s. At ~100 B a move that is only ~12 MB/s: throughput is not the hard part; per-move latency and the clock are.
  • Sockets and gateways: ~3 M sockets · 30 gateways. 2 M players in games plus 1 M spectators. A chess socket is mostly idle (a move every ~9 s per game), so 100 k sockets per server is comfortable: 30 servers, 20 for players and 10 for spectators, kept apart so a crowd watching one game cannot slow anyone’s clock.
  • Live game state: ~2 GB. 1 M games × ~2 KB (position, move list, both clocks, two connection ids) = 2 GB. It would fit on one machine. Spreading it over ~20 game servers is about blast radius and failover time, not memory or CPU: a move validates in microseconds.
  • Rating updates: ~930/s avg · ~3 k/s peak. 40 M rated games a day × 2 players = 80 M updates ÷ 86 400 ≈ 930/s. Each is a single-row change on the player’s own shard, so the load is modest; the interesting part is applying each one exactly once.
  • Game archive growth: ~5.5 TB/yr (vs ~36 TB as PGN). A move stored as its index in the list of legal moves fits in 1 byte (no position has more than 218), plus 2 bytes of clock per ply and a ~100 B header: 70 × 3 + 100 ≈ 300 B a game. 50 M × 300 B = 15 GB a day, ~5.5 TB a year per copy. As PGN text with clock comments it is ~2 KB a game, ~36 TB a year.
  • Engine screening: ~500 cores. 40 M rated games × ~55 plies after the opening book = 2.2 B positions a day. At ~20 ms of one core per position (a fixed, shallow search) that is 44 M core-seconds ÷ 86 400 ≈ 510 cores busy. Screening every rated game is affordable; deep analysis is kept for the ~1 % the screen flags.
  • Fan-out for one top game: 10 copies per move. 500 k viewers of one game spread over the 10 spectator gateways is ~50 k each. The pub/sub sends each move once per subscribed gateway, 10 copies, and each gateway writes ~50 k × 150 B ≈ 7.5 MB to its sockets. The audience size lands on the gateways, never on the game server running the clock.

Components

  • Player app (web · iOS · Android): Draws the board and checks legality locally only so a move feels instant; the server decides. Sends each move with the ply it fills and how long the player took by its own clock, answers the gateway’s pings, and on reconnect asks for the game from the last ply it has. Its clocks tick locally but are reset from every server message.
  • Play gateway (WebSocket · 100 k sockets each): Terminates players’ sockets and sessions. Routes each frame by game id to the game server that owns the game’s slot, from a slot table it caches and corrects when a server answers "moved". Pings every socket every few seconds to measure its round trip, which bounds the lag credit. Holds nothing that matters: if one dies, its players reconnect to another.
  • Game servers (one owner per game · in memory): Every live game has exactly one owner, holding its position, moves and both clocks in memory and ordering everything that happens to it. The owner validates each move against the full rules, charges the clock from its own receive time minus a capped lag credit, appends the move to the log before anyone sees it, and runs a flag-fall timer. ~1 M games over ~20 servers in 1 024 slots.
  • Live move log (replicated KV · conditional writes): One partition per live game: a header (players, their ratings at the start, time control, colours, epoch, next ply) and one row per ply with the move, both clocks after it and the server time. A move is written only if the game’s next ply is the one it fills and the epoch is the writer’s, so the ply is the idempotency key and the epoch fences a stale owner. Also holds each player’s one active game.
  • Slot leases (etcd · lease + epoch per slot): Maps each of 1 024 slots (a hash of the game id) to the game server that owns it, under a lease of ~5 s renewed every second. A takeover is a compare-and-set that raises the slot’s epoch. Small, strongly consistent and off the move path: owners watch it, and gateways learn it from them.
  • Matchmaker (in-memory pool per time control): One pool per (time control, rated or casual), each a list of waiting players sorted by rating, owned by one process with a standby. Every 100 ms it pairs neighbours whose windows overlap; a window starts at ±50 and widens with waiting. Pools are global, not regional: a move every few seconds tolerates distance, and one deep pool gives better matches than ten shallow ones.
  • Spectator gateway (one subscription per game): A separate pool of socket servers for viewers, so 500 k people watching one game cannot slow a single player’s clock. A server subscribes to a game’s channel on its first viewer of that game, keeps the moves so far in memory for later joiners, and writes each move to its local sockets. Slow sockets get a fresh snapshot instead of a growing queue.
  • Game channels (pub/sub · channel per game): One channel per watched game. The owner publishes each move once, after the players have it; only spectator gateways with a viewer of that game are subscribed. Fire and forget: a gateway that sees a gap in ply numbers reads the missing moves from the move log, so nothing on the move path waits for this.
  • Game events (Kafka · key = game id): Durable log of finished games. Each game.ended record carries the whole game in its compact form (~300 B), so no consumer reads it back. Consumer groups: rating service, archive writer, fair-play screening, analytics, each with its own offsets and each idempotent on game id.
  • Rating service (Glicko-2 · per player): Applies each rated result to each player separately, using the opponent’s rating as it was when the game started (carried in the event), so neither update needs the other’s row and no transaction spans two shards. Idempotent on (player, game). Also applies rating refunds when a cheater is closed.
  • Ratings store (SQL · sharded by player id): Rating, deviation and volatility per player per category, a history row per rated game, and an applied-games table with a unique (player, game) key. The matchmaker reads current ratings from replicas; the rating service writes the primaries.
  • Fair-play pipeline (engine fleet · per-player stats): Screens every rated game with an engine at a fixed shallow budget, skipping book moves and looking positions up in an evaluation cache first. Per player per game: accuracy where it matters, agreement with the engine’s first choice when several moves are reasonable, and time used against difficulty. These add up per player against peers of the same rating; outliers get deep analysis and a human reviewer.
  • Game archive (wide-column · compact moves): Finished games by game id as one-byte move indexes plus clocks, ~300 B each, written once and never updated. A second table indexes each player’s games, partitioned by (player, year) and sorted by end time, so "my games" is one partition read newest first and a heavy player is never one huge partition.
  • History API (renders PGN on read): Serves game pages, "my games" and PGN downloads. Decodes a compact game by replaying its moves from the start position and renders PGN on demand, so the text format is never stored. Finished games are immutable, so responses carry long cache lifetimes.
  • CDN (finished games cached forever): Caches finished game pages and PGN files with no expiry, because a finished game never changes; a famous game shared a million times costs the archive one read. "My games" lists are cached for seconds per player.

User flows

  1. Seek a blitz game and get paired. The way into every game. Pairing is easy at this size; what is not is creating exactly one game for two people who may have seeks open in several tabs, and taking the rating snapshot the result will be scored against.
    1. The player asks for a rated 3+2 game, and the gateway forwards the seek to the 3+2 pool. A pool per time control, not per rating band: every 3+2 seeker is in one sorted list, so the matcher can always find the nearest rating. There are a few dozen pools and the busiest sees about 1 k joins a second at the peak, so each fits in one process.
    2. The matcher reads the player’s current rating and deviation and inserts the seek into the sorted pool. Ratings come from a read replica: a value a second old is fine for pairing. The deviation matters as much as the rating: a new player with a deviation of 350 gets a wide window at once, because pairing them tightly against a number that is mostly a guess buys nothing.
    3. Every 100 ms the matcher pairs neighbours in rating order whose windows overlap. A window starts at ±50 and grows by ~25 points per second of waiting, capped at ±400; at the peak a 1 700 blitz player usually has a partner within ±30 at once. Pairing in a batch, greedily along the sorted list, gives better matches than pairing each newcomer with whoever is waiting, and skipping the last opponent avoids the same two players meeting again and again.
    4. The matcher asks the game service to create the game, keyed by the pairing id. Idempotent on pairing id, so a timeout and retry cannot make two games. The game id is random and hashes to one of 1 024 slots, which decides the owning game server. White goes to whichever player has had black more often recently.
    5. The owner claims each player’s single active game, then writes the game header. A conditional put on each player’s active-game key that succeeds only if it is empty. If one player already has a live game (a second tab whose seek was paired a moment earlier), creation fails, the first claim is released, and the other player goes back to the front of the pool. The header holds both rating snapshots, so the result is scored against the numbers both players saw.
    6. Both players get game.start through their gateways. The message carries the slot, so each gateway routes the game’s frames straight to the owner. Neither clock runs until each side has made a first move, and either player may abort before then, which removes the cost of being paired with someone who walked away.
  2. A move: validate, charge, persist, deliver. The hot path, ~120 k times a second at the peak. The order of the steps is the design: the clock is charged from the server’s receive time, the move is durable before anyone sees it, and the opponent’s clock starts when the move leaves the server.
    1. Black plays Nf6 at ply 24; the client sends the move with the ply and its own measure of thinking time. The ply says which half-move this fills. A resend after a dropped connection carries the same ply, so the server can tell a duplicate from a new move. The thinking time is only a claim: it lets the server separate thinking from network delay, within limits it sets.
    2. The gateway forwards it to the owner of the game’s slot, with the socket’s measured round trip. Slot = hash(game_id) mod 1 024, owner from the cached slot table. The gateway attaches the round trip it measures by pinging every few seconds (here 90 ms at p90), because the owner needs a bound on how much delay is plausible. If the server answers "moved", the gateway updates its table and resends.
    3. The owner checks the ply is the next one and the move is legal in the current position. A ply already applied is a duplicate: answer with the current state and apply nothing. A ply beyond the next cannot come from a correct client and is rejected. Legality is a move-generator check in microseconds, including the rules that need history: castling rights, en passant, threefold repetition and the 50-move rule.
    4. The owner charges black’s clock: time since the last move was sent, minus a capped credit for delay, plus the increment. Elapsed on the server is 3 240 ms and black claims 3 140 ms of thinking, so 100 ms of delay. Credit is the smallest of the claim, the measured round trip (90 ms), 1 s, and what is left of black’s lag allowance for this game: 90 ms. Black is charged 3 150 ms and gets the 2 000 ms increment, 160 000 → 158 850. A client that always claims lag runs its allowance dry within a few moves.
    5. The owner writes the move to the log, conditional on the next ply and its epoch. Replicated to a quorum in a few ms before anyone is told. If the owner crashes after this, the move survives; if before, the client resends the same ply to the next owner. A failed condition means another owner has taken the game, so this one stops serving it.
    6. The owner sends the move to both players, which starts white’s clock. White’s turn starts the moment the move leaves the owner, after it is durable, so the few ms of the write are charged to nobody. Every message carries both clocks as the server sees them, so the displays are corrected on every move and never drift.
    7. The owner re-arms the flag timer for white and publishes the move to the game’s channel. The timer is set for white’s remaining time plus the most lag credit white could still get, so a move already in flight is never flagged. Publishing comes after the players have their copy and is fire and forget; for a protected game the owner publishes each move a set delay later.
  3. A prize final with 500 k spectators. The scale-breaking case. The audience is huge but a move is tiny and comes every few seconds to minutes; the job is to keep that audience off the process the players’ clocks depend on, and to stop the broadcast from helping anyone cheat.
    1. A viewer opens the game; the load balancer picks a spectator gateway by load, not by game. Viewers of one game end up spread over all 10 spectator gateways, about 50 k each. Sending every viewer of a game to one gateway would make it the bottleneck for exactly the game people care most about.
    2. On its first viewer of this game, the gateway subscribes to the game’s channel, then reads the moves so far from the log. Subscribe first, then read: a move played in between arrives on the channel and is also in the snapshot, and the ply number makes the duplicate harmless. Snapshots come from the log’s replicas, never from the owner, so a burst of joins at the start of a famous game costs the owner nothing.
    3. Later viewers on that gateway get the snapshot from its memory. The gateway keeps the moves of every game it is subscribed to, a few KB each. So the ~50 k viewers of this game on one gateway cost one subscription and one snapshot read, not 50 k.
    4. Each move is published once, copied to every subscribed gateway, and written to its viewers. 10 copies leave the pub/sub, and each gateway writes ~50 k × 150 B ≈ 7.5 MB to its sockets, a few ms at 10 Gbps. The owner’s cost is the same for 500 k viewers as for none.
    5. A gateway stops queuing moves for a socket that cannot keep up and sends it a fresh snapshot once it drains. A phone on a weak connection must not grow a queue on the gateway. Past ~64 KB in a socket’s send buffer, the gateway marks it stale and skips individual moves; when the buffer drains, the socket gets the current position in one message. Spectators lose nothing they need, because the snapshot has every move.
    6. Because this is a prize game, the owner publishes each move late and no engine evaluation is ever sent. A live feed of a protected game is what an accomplice with an engine needs to signal the player, so the event sets a delay (minutes for a slow game) and the owner holds each move in a small queue until then. An evaluation bar on a live game is never shown to anyone, delayed or not: on a second screen it is an engine.
  4. Disconnects and a game server crash. A player’s phone drops, and then the game server holding ~50 k live games dies. The games must resume elsewhere with no accepted move lost, nobody flagged for our outage, and no chance of the old server and the new one both accepting moves.
    1. White’s phone loses its connection; white’s clock keeps running and black is offered a claim. Over the board a player who walks away loses time; online it must be the same, or disconnecting would be a free pause. The gateway tells the owner the socket closed, and the owner tells black, whose screen shows a countdown after which they may claim the win or a draw.
    2. Game server 12 stops renewing its slot leases, and after ~5 s they expire. Leases are renewed every second, so expiry means several missed renewals, not one slow one. The ~50 k games in its ~50 slots pause: moves fail to reach an owner, and the gateways hold them briefly and retry.
    3. Other game servers take its ~50 slots, each with a compare-and-set that raises the slot’s epoch. Spreading the slots over the remaining servers means none takes 50 k games at once. Every owner watches the slot keys, so it knows within a second who owns what, and answers "moved" to any gateway that asks the wrong server.
    4. For each game in a slot, the new owner raises the game’s epoch, loads its plies and restores both clocks. About 1 k games per slot at a few KB each load in well under a second. The clocks are as stored with the last ply; the side to move gets back the time since then, and its clock restarts on resume, because our outage should be charged to nobody. Flag timers are re-armed from the restored clocks.
    5. Gateways resend the moves they were holding, and white reconnects on a laptop and resyncs from the start. A move appended before the crash comes back as a duplicate ply and is answered with the current state; one that was not is applied now. A fresh device asks from ply 0 and gets every move and both clocks. Players see their clocks stop for a few seconds and carry on; their sockets never dropped, because gateways are separate from game servers.
    6. Server 12 was only paused; it wakes, tries to append a move, fails the epoch check and drops its slots. A long garbage-collection pause or a network partition looks like a crash from outside. The lease told server 12 how long it could assume it was the owner, by its own clock, which a paused process cannot trust; the epoch is checked by the store at write time. No move server 12 accepted after losing its lease reached a player, because players only see a move after the write succeeds.
    7. Had white not come back, the flag timer on the new owner would have ended the game on time. The timer fires at white’s remaining time plus white’s remaining lag allowance, so it never beats a move in flight. Then the owner checks whether black could still mate with what is left; against a lone king, say, a timeout is a draw. The result is written like a move, under the same condition, then published.
  5. Game over: rating, archive, fair play. Everything after the last move happens off the hot path, from one durable record. Each consumer must apply it exactly once, and the slowest (engine screening) must never delay the one players wait for (their new rating).
    1. Black resigns; the owner writes the result, clears both active games and publishes game.ended. The result row is the commit point and publishing comes after. If the owner dies in between, the next owner finds a finished game not marked published and publishes it again, so the log doubles as an outbox and every consumer dedupes on game id.
    2. The rating service applies the result to each player separately, from the rating snapshots in the event. For each player, one transaction on their own shard: insert (player, game) into the applied table, lock their rating row, compute Glicko-2 from their current values and the opponent’s values at the start, write the new rating and a history row. A redelivered event fails the insert and stops; no transaction ever spans two shards.
    3. The archive writer stores the compact game and adds a row to each player’s history index. Keyed by game id, so a replay writes identical bytes. The index rows go into (player, year) partitions sorted by end time, which keeps even a player with 300 000 games in bounded partitions. The live rows are kept for a week after the archive write, so an encoder bug can still be repaired from them.
    4. The fair-play pipeline screens the game with an engine and folds the results into both players’ statistics. Its own consumer group, so a backlog here (the fleet is sized for the daily average, not the peak) never delays ratings or the archive. Book moves are skipped, positions are looked up by hash in an evaluation cache first, and each player’s per-game features join a rolling window compared with players of the same rating.
    5. A player whose statistics stand out is reviewed by a person; once confirmed, their victims get their rating back. Refunds are new rating entries for each opponent who lost rated games to the cheater in the window, not a replay of history: recomputing everyone’s ratings since would change thousands of players’ numbers for a tiny gain in accuracy. The account closure itself goes to the account service, which is not drawn.
    6. Later, anyone opens the game page or downloads its PGN, served from the CDN after the first read. The history API replays the compact moves from the start position to rebuild the notation and renders PGN on the fly; a finished game never changes, so the response is cached with no expiry. "My games" reads one or two index partitions newest first and pages with a cursor of (ended_at, game_id).

Deep dives

A fair clock over an unfair network

Whose clock is right, the browser’s or the server’s? And how do you stop a player on a slow connection losing on time to their own ping?

In a 1-minute game each player makes ~30 moves. If the server simply charges from when it sent the opponent’s move to when the reply arrived, every move also costs a round trip: at 150 ms that is 4.5 s, almost a tenth of the game, and a player on mobile at 400 ms loses 12 s. Yet the browser’s own clock cannot be trusted, because anyone can change what a client reports.

The server sees elapsed = thinking + round trip. It can measure the round trip, but only roughly and only with the client’s cooperation: a client can delay its ping replies to look laggier than it is. So the answer is not to pick one clock. Let the client claim how much of the elapsed time was network, and bound that claim by what the server measured and by a budget per game that no client behaviour can raise.

  • Server clock with a capped, budgeted lag credit chosen
  • Server clock with no compensation rejected
  • Client clock: trust the time the client reports rejected
  • A fixed delay per move for everyone situational: as a time control players choose (a delay format), never as lag compensation, since it gives a 20 ms player the same as a 400 ms one

The answer: The owner charges each move elapsed − credit, where elapsed runs from the moment the opponent’s move left the server to the moment this move arrived. The client sends its own measure of thinking time, and the claimed lag is elapsed minus that. Credit = min(claimed lag, the socket’s round trip at p90 of recent pings, 1 s, what is left in the player’s allowance). The allowance starts at 3 s per game and refills 250 ms per move, so up to 250 ms of delay a move is credited for the whole game and bursts up to 3 s are absorbed. The flag timer is armed for remaining time plus remaining allowance, so a move in flight is never flagged. Every claim is logged next to its move, and a player whose claims sit at the cap while their pings are fast goes to fair play. Lichess, for one, publicly describes compensating lag only up to a quota; the numbers here are a starting point to tune on real round-trip data.

A player always claims exactly 250 ms of lag while their pings are 30 ms. What do they get?

Credit is capped by the measured round trip, so on those moves they get 30 ms, not 250; the claim buys nothing. If they also delay their ping replies to inflate the round trip, the allowance is the hard ceiling: at most 3 s plus 250 ms a move. And the pattern itself, claims pinned at the cap and pings that slow down only when it is their move, is a feature for the fair-play pipeline, because honest lag is noisy.

What does the clock on the player’s screen show between server messages?

The client counts down locally from the last values the server sent, so the display is smooth, and every server message resets both clocks. Drift therefore never lasts more than one move. If the display reaches zero, the client shows zero but does not end the game: only the server’s flag does.

How do premoves interact with the clock?

A premove is queued on the client and sent the instant the opponent’s move arrives, so the claimed thinking time is near zero and the charge is roughly the round trip minus the credit, close to nothing. A floor of, say, 100 ms per move is a product choice that makes premove chains in bullet cost something; the owner would apply it like any other rule.

Sydney and London in one global pool: is that fair in bullet?

On the clock, roughly: each is charged about their thinking time as long as their delay fits the allowance, and a 300 ms round trip is credited 250 ms a move once the first 3 s are spent. What credit cannot fix is that the board updates later for the distant player, which matters for premove timing in 1-minute games. So for bullet the matcher prefers opponents in the same region when the pool is deep, and widens to global after a second or two.

How would you know the compensation is working?

Log elapsed, claim, credit and round trip for every move. Then chart losses on time per round-trip bucket for the same rating and time control: if compensation is fair the curve is flat. Add the share of moves where the claim hit a cap and allowance exhaustion by region; a spike in one region usually means a network problem there, not cheaters.

One owner per game, and losing it safely

Why put a live game in one server’s memory? What happens when that server dies, or only looks dead?

A move needs the current position, both clocks and the history that repetition and castling rights depend on, and two frames for one game can arrive at the same moment: a move and a resignation, a draw offer and a move. Reading and writing a database row per move works at 120 k moves a second, but it puts a read on the clock’s critical path, turns concurrent frames into write conflicts, and leaves the flag timer to some other service.

The deciding observation: a chess game is tiny, changes a few times a minute, and its whole state is its move list. So one process can own it in memory and order everything that happens to it, as long as every accepted move is durable before anyone sees it and a stale owner can be fenced off. This is where chess and a shooter part ways: a 30 Hz match is too costly to replicate and is lost when its server dies (see Design a Multiplayer Game Backend), while a chess game costs ~100 B a move to keep.

  • One owner in memory, every move a conditional write to a replicated log under an epoch chosen
  • Stateless servers, each move a transaction on the game row situational: correspondence games, where a move every few hours makes a read and a conditional write per move the simplest correct design
  • One owner in memory, persist only when the game ends rejected
  • A primary and a hot standby per game, replicating synchronously rejected

The answer: Games hash into 1 024 slots, and each slot is leased in etcd to one game server with a 5 s TTL and an epoch that rises on every takeover. The owner keeps each game in memory and makes one conditional write per move: it applies only if the game’s next ply is the one the move fills and the game’s epoch is the owner’s. The ply makes resends idempotent, and the epoch, checked by the store, fences a server that has lost its lease without knowing it. On takeover the new owner raises each game’s epoch first, so a late write from the old owner fails, then loads the plies, restores the clocks and re-arms the timers. Players see a move only after its write succeeds, so nothing they saw can be lost. Lichess’s open-source server also gives each live game one in-memory actor that handles its moves in order, though it writes a game in progress to its database after a delay rather than on every move.

The owner writes a move, then crashes before sending it to either player. What do the players see?

The move is in the log, so the new owner has it. The mover never got an acknowledgement, so after the pause its client resends the same ply; the new owner sees a duplicate and answers with the current state, which includes the move. The opponent gets it when it resyncs. Nobody sees a move disappear, and the mover was charged once, in the stored clocks.

Why 1 024 slots instead of hashing games straight onto servers?

Slots make ownership a small table that changes rarely: 1 024 entries, each with an owner and an epoch. Adding a server moves a few slots, and a takeover is one compare-and-set per slot. Hashing games straight onto a ring of servers works too, but every membership change reassigns games individually and the fencing has to be per game from the start.

How do you deploy a new game server build without pausing a million games?

Hand slots over instead of letting leases expire: the old server stops taking moves for one slot, releases the lease, and the new server takes it with epoch + 1, loads ~1 k games and resumes within a few hundred ms. Nothing needs flushing, because every move is already durable. Done slot by slot across the fleet, each game pauses for under a second once per deploy.

Why is the lease alone not enough to stop a stale owner?

A lease only tells the owner how long it may assume it owns the slot, measured on its own clock. A server that stalls for 10 s in garbage collection resumes believing the lease is still valid and writes. The epoch in the write condition is checked by the store, which does not depend on the stale server’s sense of time. The lease decides who should serve; the epoch decides whose writes count.

A server dies at the peak. How long are its players stuck, and how would you shorten it?

About 5 s for the lease to expire, under a second to take over and load, and a second or two for gateways to retry: 6 to 8 s. A shorter TTL cuts the first part but turns a brief network blip into an unneeded takeover. Better to keep the TTL and let the clock absorb it: the side to move is credited the outage, so the pause costs players patience but not time.

Spectators and broadcasts

500 k people are watching one game. How do they all see each move within a second, and why should the game server not even notice?

Most games have no spectators, but popular ones are extreme: a famous streamer or a prize final can draw hundreds of thousands at once, and they arrive together when the game starts. A move is ~150 B and comes every few seconds, so bandwidth is not the problem (500 k × 150 B is 75 MB per move, spread over many machines); connection count, join bursts and slow phones are.

Players and spectators want the same bytes with very different guarantees. Players need every move and their clocks within milliseconds, and the process running their game must never stall. Spectators can be a second late, can skip straight to the current position, and must never be able to slow the players. That argues for a separate tier fed by a one-way channel, so that the audience size never reaches the game’s owner.

  • Separate spectator gateways, one subscription per gateway per game, snapshots from log replicas chosen
  • Spectators on the players’ gateways, the owner sending to each viewer rejected
  • Game state as a small file on the CDN, polled by viewers situational: embeds on news sites and audiences in the millions, where a few seconds of delay are fine and holding a socket per viewer costs more than a cached poll
  • A relay tree that fans hot channels out through intermediate relays situational: a spectator fleet of hundreds of gateways, where one publish would otherwise fan out to hundreds of subscribers

The answer: Spectators connect to a separate pool of 10 gateways (100 k sockets each), chosen by load. A gateway subscribes to game:{id} on its first viewer of that game and unsubscribes after the last leaves; it subscribes first, then reads the moves so far from a replica of the live log, applying channel messages only for newer plies. It keeps each subscribed game’s moves in memory for later joiners, so ~50 k viewers on one gateway cost one subscription and one read. The owner publishes each move once, after the players have it; a gateway that sees a gap in plies reads the missing ones from the log. A socket whose send buffer passes ~64 KB stops getting individual moves and gets a fresh snapshot when it drains. Protected games publish late by the event’s delay, and no live game carries an engine evaluation.

The pub/sub node carrying a hot channel fails. What do viewers see?

The gateways’ subscriptions break, they resubscribe on another node and read from the log every ply after the last one they have. Viewers see a pause of a second or two and then the missed moves in one batch. Players see nothing, because the owner’s publish is fire and forget and nothing on the move path waits for it.

Why is an engine evaluation on a live game dangerous even behind a delay?

The delay protects moves, not positions: the player knows the current position, and if any page evaluates a recent one, a second device or a friend turns the site itself into the engine. For relays of over-the-board events the organiser decides the delay and whether an evaluation is shown; for games played on the site, live games show none, and analysis opens only after the game ends.

How do you choose which games appear on a "top games" list?

A small job ranks live games every few seconds by the players’ ratings and titles and the spectator counts the gateways report per game, and writes the top few hundred to a cached list. It is a read model and never touches the owners. Featuring a game moves its audience, so the list changes slowly, with hysteresis, rather than sending 100 k people from game to game.

Where does a 15-minute broadcast delay live, and what if the owner fails?

In a small queue on the owner of moves waiting to be published, a few KB per protected game. Each ply in the log has its server time, so a new owner rebuilds the queue from the log. Snapshots served to joiners are filtered the same way, leaving out plies newer than now minus the delay.

How would you measure the spectator experience?

Per gateway: time from a move’s server timestamp to the write on the socket, at p50 and p99, the share of sockets marked stale, and time from join to first move. Alert on the p99 move-to-socket delay for featured games, because that is where a lag is most visible and most talked about.

Detecting engine use

A player is taking moves from an engine in another tab. How do you catch them without banning strong honest players?

Nothing on the server can see the other tab. Client signals, such as the tab losing focus while it is your move, are cheap hints that a determined cheater suppresses or defeats with a second device. So detection is statistical: does this player play more like an engine than humans of their rating, consistently, across many games? One game proves almost nothing: strong players have brilliant games, and short or forced games are naturally accurate.

The compute is affordable: screening every rated game at a shallow fixed budget is ~2.2 B positions a day, ~500 cores. The binding constraint is precision. A false ban of an honest titled player is public and damaging, while a missed cheater can be caught a few games later. So the pipeline ranks suspects for human review, and automatic action is kept for blatant, repeated cases.

  • Screen every rated game, aggregate per player against their rating band, deep-analyse outliers, humans decide chosen
  • Per-game rule: ban when accuracy passes a threshold rejected
  • Client-side detection only (focus changes, extensions) rejected
  • A learned classifier over move and timing features situational: once review has produced thousands of confirmed cases per rating band to train and calibrate on; until then, hand-built statistics are easier for reviewers to explain

The answer: Every rated game is screened from game.ended: skip the first ~8 moves (book), look each later position up by hash in an evaluation cache, and otherwise search it at a fixed node budget, ~20 ms of a core. Per player per game, three features: average loss against the engine’s best move on positions where it matters (not forced, not already decided), agreement with the engine’s first choice where several moves are reasonable, and time used against how hard the position was, since engine users take similar time on easy and hard moves. These roll up into a window per player and category, compared with players of the same rating band as z-scores. Players beyond a threshold over enough games, or flagged in prize events, get deep multi-line analysis and join a review queue ordered by evidence and stakes. Reviewers close accounts and refunds follow. Thresholds are set to keep confirmed precision on the reviewed sample very high, and rechecked whenever a feature changes.

A cheater uses the engine for only two or three critical moves a game. Does this catch them?

Not from one game, and not quickly. The features that help weigh critical positions: where the evaluation swings and several moves look plausible, does the player find the only move far more often than peers, and do they spend unusual time just before? Over 50 games that pattern stands out even when overall accuracy looks human. It is the hardest case, and it costs more games and more reviewer time.

How do you test the detector without real cheaters?

Plant known material: engine moves injected into real games at set rates, and games by engines at various strengths. Measure the share caught and how many games it took at each rate. Then run the detector over players you are confident are honest, such as titled players in supervised events, to estimate false positives per rating band.

Why give rating points back rather than recompute everyone’s rating?

Ratings form a chain: every game since depends on the ones before, so a recomputation changes thousands of players’ numbers, including people who never met the cheater. A refund is a local, explainable correction for exactly the people harmed, recorded as a new entry with a reason. It is slightly imperfect mathematically and much better for trust.

At ten times the games, what breaks first?

Not the engine fleet: it grows linearly to ~5 000 cores, and the evaluation cache gets better with volume because openings and common positions repeat. Reviewers do not scale. So the investment goes into ordering the queue well, by strength of evidence and stakes, and into automatic action for the blatant cases, keeping people for the borderline ones.

Can the screen run during the game instead of after?

For prize events, yes: screening moves as they are played lets the event pause a game or hold a payout. For ordinary games, after is better: it batches, it can lag at the peak, and acting mid-game on one game’s statistics would be the per-game threshold we rejected.

Rating updates exactly once

Two players finish a rated game and their ratings live on different shards. How do you update both, exactly once, without a distributed transaction?

Glicko-2 updates a player’s rating, deviation and volatility from the result and the opponent’s rating and deviation. The obvious update reads both players, computes both new ratings and writes both rows in one transaction; with ratings sharded by player id that is a cross-shard transaction for every rated game, ~930 a second on average. And results are delivered at least once, so the update must also survive a replay or a consumer crashing halfway.

The way out is to look at what each player’s update actually needs: their own current values, which are on their own shard, and the opponent’s values as they were when the game started, which are already in the game header because both players saw them before the first move. With that snapshot, the two updates are independent single-shard changes.

  • Two independent per-player updates from the start-of-game snapshot, each idempotent on (player, game) chosen
  • One transaction across both players’ shards rejected
  • Rating periods: apply all of a day’s games together, as Glicko was first described situational: correspondence leagues or official lists published on a schedule

The answer: game.ended carries both players’ (rating, deviation, volatility) at the start. For each player in turn, the rating service runs one transaction on that player’s shard: insert (player_id, game_id) into applied_games under a unique key, lock the player’s row for the category, compute Glicko-2 from their current values and the opponent’s snapshot, update the row and insert a rating_history row with the game id. A replay fails the insert and stops; a crash before commit leaves nothing. The game owner runs the same formula on the same inputs to show "+8" on the result screen at once; the service’s number is the one that counts. Deviation grows with inactivity, computed at read time from the last game date, so idle players need no nightly job. Players with a high deviation are shown as provisional and get wider pairing windows.

The opponent finished another game a second before this one started, so their snapshot is stale. Does it matter?

By a few points at most, and rarely: each player has one live game at a time, and in the usual case the previous result has been applied before the next pairing reads ratings. It is also the number both players were shown, so it is the fairest one to score against. Using the opponent’s live rating instead would make a result depend on update timing.

A shard of the ratings store is down for ten minutes. What happens?

Updates for players on that shard wait in the consumer, which retries with backoff, and the result screen still shows the predicted change. Players on other shards are unaffected, because nothing couples the two updates. The matchmaker keeps pairing from replicas, or with wider windows if those are down too.

How do separate bullet, blitz and rapid ratings work?

The category is part of the key: one row per (player, category). A time control maps to a category by its estimated length, the base time plus 40 times the increment: 3+2 is 180 + 80 = 260 s, so blitz. Each category has its own deviation, so a strong blitz player starting bullet is provisional there and moves quickly.

Ratings slowly inflate or deflate over years. How would you notice?

Track the mean and percentiles of active players per category month by month, and the average change for players returning after a long break: if returners consistently gain or lose, the pool has drifted. New players’ starting rating, refunds after bans and departures all move the pool, so the starting value is the main lever, tuned on this data.

Storing every game ever played

Keep every game forever and serve "my games" and PGN downloads. Why not just store the PGN text?

At 50 M games a day the archive grows by ~18 B games a year. PGN with clock comments is ~2 KB a game, ~36 TB a year per copy, and it is the wrong shape for most reads: listing a player’s games needs dates, opponents and results, not moves, and analysis needs positions, not text. Meanwhile the live log is built for fast conditional appends and has no reason to exist once a game ends.

Two observations shape the answer. A move only has to say which of the legal moves was played, and no position has more than 218, so a byte is enough if the reader replays the game to know the legal moves. And a finished game never changes, so it can be written once, cached forever, and rendered to whatever text format a reader wants.

  • Compact games by id plus a per-player index, PGN rendered on read chosen
  • Store PGN text rejected
  • One row per move in a relational table rejected
  • Monthly PGN files per player in object storage situational: bulk export and public dumps, generated from the archive rather than used as the primary store

The answer: games: key game_id, header columns (players, ratings at the start, time control, result, reason, timestamps) and the moves as a byte string of legal-move indexes with clocks as 16-bit deltas, ~300 B. player_games: partition (player_id, year), sorted by ended_at descending, with opponent, result, time control and colour for filtering, so "my games" is one partition read newest first with a cursor of (ended_at, game_id). Both live in a wide-column store such as Cassandra or Scylla with three replicas, ~16 TB a year of games. The history API renders PGN by replaying the moves and the CDN caches it with an immutable lifetime. Live rows are kept a week after archiving, and a daily job decodes a sample of archived games and compares them with the live rows. Bulk monthly PGN files are generated from the archive into object storage; Lichess publishes its rated games as monthly PGN files in the same spirit.

A player with 300 000 games opens "my games" filtered to blitz losses. How fast is that?

The (player, year) partition keeps each read bounded: even a very heavy player has tens of thousands of games in a year. Filtering by category and result scans that partition newest first and stops when a page is full. If cross-year filtered views became common, add a second index partitioned by (player, category); the rows are small, so a second copy is cheap.

How would you find every game that reached a given position?

Not from the archive directly. A batch job replays games and writes (position hash, game id) pairs into a separate index sharded by hash, and the opening explorer reads aggregates from it. It is a derived read model; the archive stays the source of truth and can rebuild it.

The encoder mishandled under-promotions for three days. What now?

That is why live rows are kept for a week and a daily job round-trips a sample: the bug is caught within a day, while the original moves still exist. Re-encode the affected games from the live rows, rewrite their archive rows, and purge their pages from the CDN by game id. Without the retained rows, the corrupted games could not be repaired.

Why not gzip the PGN and call it done?

Gzip gets maybe 3 to 4×, and it is a fine bulk format. But every read still pays the parse, and header text is still mixed with moves. The index encoding is smaller, faster to decode for analysis, and PGN, gzipped or not, can still be produced at the edge for downloads.

The theory behind it

  • Matchmaking and skill rating: How online games and other two-sided systems pair people: skill ratings with Elo, Glicko and TrueSkill, matchmaking pools and widening search windows, the trade-off between match quality and wait time, regions and latency, parties, and scaling the matchmaker.
  • Multiplayer game servers: How real-time multiplayer games keep players in sync: authoritative servers, tick rates and snapshots, client prediction and reconciliation, lag compensation, UDP networking, interest management, server allocation and fleets, persistence, cheating and scaling to large worlds.
  • Presence and managing millions of connections: Holding millions of persistent WebSocket connections and showing who is online: connection gateways, routing messages to the right server, heartbeats, presence with TTLs, fan-out of status changes, typing indicators, reconnect storms and deploys.

Related

Sit this question with an AI interviewerOr watch a sample interviewStart an AI mockPractice with AI