Design an Online Chess Game
Run this for someone else. You hold the answers; they do not. Read the prompt, keep the clock, and use the probes below when an answer is thin. Do not show them this page.
Open with this
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. Take a couple of minutes on requirements, then we will do some numbers, then the design. I will interrupt to keep us moving.
The clock
- 4 min: functional requirements and scope
- 4 min: non-functional requirements, with numbers
- 5 min: back-of-envelope estimates
- 16 min: high-level design and one or two flows
- 16 min: deep dives and the close
Move them on out loud when a section overruns. The commonest failure is spending twenty minutes on requirements and never reaching a deep dive, and preventing that is your job as much as theirs.
Requirements · 8 min
Listen for: a scoped set of capabilities, an explicit out-of-scope list, and numeric targets rather than adjectives. Prompt with “what are you not building?” if they never scope, and “what number would make that requirement real?” if they say “fast” or “highly available”.
Functional (9)
- 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 (8)
- 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.
Estimates · 5 min
Ask for two or three numbers, not all of them. What matters is whether they state assumptions, round sensibly, and say what the number implies. Push once with “where did that come from?”
The numbers (8)
- 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.
High-level design · 16 min
Let them draw. Interrupt only to ask what backs a component or what a box actually does. Then pick one flow below and ask them to walk it end to end.
Components (15)
- 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.
Flows to ask them to walk (5)
- 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.
- The player asks for a rated 3+2 game, and the gateway forwards the seek to the 3+2 pool.
- The matcher reads the player’s current rating and deviation and inserts the seek into the sorted pool.
- Every 100 ms the matcher pairs neighbours in rating order whose windows overlap.
- The matcher asks the game service to create the game, keyed by the pairing id.
- The owner claims each player’s single active game, then writes the game header.
- Both players get game.start through their gateways.
- 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.
- Black plays Nf6 at ply 24; the client sends the move with the ply and its own measure of thinking time.
- The gateway forwards it to the owner of the game’s slot, with the socket’s measured round trip.
- The owner checks the ply is the next one and the move is legal in the current position.
- The owner charges black’s clock: time since the last move was sent, minus a capped credit for delay, plus the increment.
- The owner writes the move to the log, conditional on the next ply and its epoch.
- The owner sends the move to both players, which starts white’s clock.
- The owner re-arms the flag timer for white and publishes the move to the game’s channel.
- 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.
- A viewer opens the game; the load balancer picks a spectator gateway by load, not by game.
- On its first viewer of this game, the gateway subscribes to the game’s channel, then reads the moves so far from the log.
- Later viewers on that gateway get the snapshot from its memory.
- Each move is published once, copied to every subscribed gateway, and written to its viewers.
- A gateway stops queuing moves for a socket that cannot keep up and sends it a fresh snapshot once it drains.
- Because this is a prize game, the owner publishes each move late and no engine evaluation is ever sent.
- 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.
- White’s phone loses its connection; white’s clock keeps running and black is offered a claim.
- Game server 12 stops renewing its slot leases, and after ~5 s they expire.
- Other game servers take its ~50 slots, each with a compare-and-set that raises the slot’s epoch.
- For each game in a slot, the new owner raises the game’s epoch, loads its plies and restores both clocks.
- Gateways resend the moves they were holding, and white reconnects on a laptop and resyncs from the start.
- Server 12 was only paused; it wakes, tries to append a move, fails the epoch check and drops its slots.
- Had white not come back, the flag timer on the new owner would have ended the game on time.
- 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).
- Black resigns; the owner writes the result, clears both active games and publishes game.ended.
- The rating service applies the result to each player separately, from the rating snapshots in the event.
- The archive writer stores the compact game and adds a row to each player’s history index.
- The fair-play pipeline screens the game with an engine and folds the results into both players’ statistics.
- A player whose statistics stand out is reviewed by a person; once confirmed, their victims get their rating back.
- Later, anyone opens the game page or downloads its PGN, served from the CDN after the first read.
Deep dives · 16 min
Pick two. Ask the headline question, let them answer, then use the follow-ups. The follow-ups are where the level gets decided, so leave time for at least three of them.
A fair clock over an unfair network
Ask: 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?
Good answers name: Server clock with a capped, budgeted lag credit, Server clock with no compensation, Client clock: trust the time the client reports, A fixed delay per move for everyone.
Our pick: 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
Ask: Why put a live game in one server’s memory? What happens when that server dies, or only looks dead?
Good answers name: One owner in memory, every move a conditional write to a replicated log under an epoch, Stateless servers, each move a transaction on the game row, One owner in memory, persist only when the game ends, A primary and a hot standby per game, replicating synchronously.
Our pick: 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
Ask: 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?
Good answers name: Separate spectator gateways, one subscription per gateway per game, snapshots from log replicas, Spectators on the players’ gateways, the owner sending to each viewer, Game state as a small file on the CDN, polled by viewers, A relay tree that fans hot channels out through intermediate relays.
Our pick: 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
Ask: A player is taking moves from an engine in another tab. How do you catch them without banning strong honest players?
Good answers name: Screen every rated game, aggregate per player against their rating band, deep-analyse outliers, humans decide, Per-game rule: ban when accuracy passes a threshold, Client-side detection only (focus changes, extensions), A learned classifier over move and timing features.
Our pick: 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
Ask: Two players finish a rated game and their ratings live on different shards. How do you update both, exactly once, without a distributed transaction?
Good answers name: Two independent per-player updates from the start-of-game snapshot, each idempotent on (player, game), One transaction across both players’ shards, Rating periods: apply all of a day’s games together, as Glicko was first described.
Our pick: 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
Ask: Keep every game forever and serve "my games" and PGN downloads. Why not just store the PGN text?
Good answers name: Compact games by id plus a per-player index, PGN rendered on read, Store PGN text, One row per move in a relational table, Monthly PGN files per player in object storage.
Our pick: 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.
Close · 5 min
Ask what breaks first at ten times the load, and what they would build next. Then give them your read: one thing that was strong, one thing that was missing, one thing to practise. Be specific; “good job” helps nobody.