Ch.70: Online Chess System Design: Who Ran Out of Time?
Outline
- 0:00 Two screens, one game
- 1:06 The game and its audience
- 1:53 What players can do
- 3:01 How much shared state?
- 4:09 Two waiting players become one game
- 5:22 What a move carries
- 6:30 The move that survives a lost reply
- 7:24 Follow both clocks through the write
- 8:42 Rejected moves and competing timers
- 10:07 Reconnect without rewinding
- 11:09 The reply the owner never got
- 12:31 Recover a board, not a guessed clock
- 13:40 Scaling the games and the crowd
- 15:00 The ending arrives before the ratings
- 16:03 Settle the disputed move
Transcript
0:00 In online chess, two distant players take turns on a shared board. Only the active player's clock runs. We'll build its backend to settle whether a move counted, from matching players to reconnecting them and recording the result. Suppose your clock shows half a second. You move. The piece lands, the connection stalls, and the app says you lost on time. Did your move count? Your opponent might still see the old position. Either display can be wrong about what the server accepted; we need a decision both players can recover.
0:31 I think trusting the phone feels convincing because it saw my finger. But a dishonest app could claim whatever time it wanted. Yes, and your opponent has a phone too. Neither gets to declare the official result. We'll use accepted server state, with an explicit clock policy. We aren't building a chess-playing computer. A tested rules library checks permitted moves. The backend still has to keep those two people in the same game. Then show me the full route from your connection to the recorded answer.
1:02 Where does that decision live in the service? Let's trace your move on our complete architecture map. A gateway holds your connection and routes commands to the game owner, which commits position, clocks and result together. The matchmaker got you an opponent. Committed changes now feed reconnect history, ratings and a separate delivery path for spectators watching your game. The public Lichess socket project's README shows connection handling separated from its application. That's a useful example of the split, not evidence for our proposed storage design.
1:35 So the crowd watches the same board, but doesn't get the same path. Could those viewers consume the time left on my clock? They could if we shared every queue. We'll protect the players' decisions from audience delivery. A celebrity joining shouldn't become a clock penalty for their opponent. Before the disputed move, our functional requirements get these people into a game: sign in, find or invite an opponent, make legal moves and read their clocks. If one resigns, finish the game. If both agree, record a draw, meaning neither wins.
2:07 The rules library also detects endings forced by the position. But suppose the library approves a move chosen with outside computer help. Does that make the game cheat-free? No. A correct exam answer doesn't prove who solved it. The library checks whether your move is permitted, not where the idea came from. Right, and my phone still needs an answer about that piece. We can't leave it spinning while investigating how the move was chosen. Right. Keep outside-assistance detection, tournaments and analysis out of this first version, while the normal game still reaches a recoverable ending.
2:41 Spectators follow accepted play, and completed games reach history and skill ratings. On reconnect, I need to find that ending, even if the last reply vanished. Each game stores its rule version and clock settings, including starting time and any move bonus. Later policy changes can't quietly become new rules for a game underway. Those actions lead to our non-functional requirements: responsive play, limits on waiting and one durable history. An interruption must be visible, rather than a fabricated winner.
3:11 Assume 100,000 concurrent games, with 1 combined move every 3 seconds per game. That's roughly 33,000 move decisions per second across the service. So no single board gets that traffic. Our half-second move belongs to one quiet game; spread matches across writers, but keep that game's decisions together. Let's set a fictional objective: most accepted moves reach the opponent within 200 milliseconds in the assigned region. It's a target to test, not a vendor benchmark. Players far apart may miss that objective.
3:43 Pair nearby opponents when practical and show connection quality; a two-way WebSocket connection can't erase distance. And that link can disappear after the database saved your move. Reconnect by retrieving that saved decision. Opening another socket can't establish what happened to the first request. So the half-second dispute needs durable state as well as fast transport. We'll build the decision first, then make delivery recoverable. First create the pairing. The matchmaker groups searches by rules, clock settings and a widening skill range, then claims two waiting players atomically.
4:17 Imagine one of them taps Find Game on a phone and a laptop. Removing a queue message isn't enough; check that player's active search or game record. Otherwise they get two opponents and one very confusing afternoon. One transaction creates the game and changes both players from waiting to assigned. Yeah, I'd hate to be either opponent. A retry with the same search identity returns that assignment. If cancellation races it, whichever changes the waiting record first wins. The reply reports that committed outcome.
4:48 Now assign an owner, the service process responsible for ordering this game's decisions. Many games share each process; we aren't buying a machine for every board. Fine, but your reconnect could hit another gateway. How does that connection find the process already running your game? A game directory maps its identity to the owner and ownership generation. That's a changing ownership number, checked by storage before accepting a write. So changing gateways changes the route to your game, rather than creating another match.
5:18 The connection can move without moving the decision authority. Once assigned, your move follows that route with a game identity, command identity, expected game version and proposed move. Authentication separately establishes who's sending it. Our phone chose its move at version 20. The old tab still has 18; its next choice needs a refreshed position. Version checks a new intention against current state. Command identity instead retrieves an earlier decision when its reply goes missing. We're validating a new choice or recovering an old outcome.
5:50 Like a receipt number versus a menu edition. One retrieves an old order; the other identifies the current choices. But what establishes which side I'm allowed to move? Check the authenticated participant against the game record and active player. Then the same rules library validates the move against the full position and relevant rule state. The browser can check too, to respond quickly. Its animation stays provisional. Our disputed piece landing isn't an acceptance just because the app was confident.
6:19 Right. So the accepted game carries position, active player, durations, version and outcome. Rule-relevant history travels with it, beyond the pieces' current squares. Next, accept that move durably. Look for its recorded command outcome first. Otherwise use a short per-game transaction to check ownership, player, expected version and legality. Commit the position, clocks, command result and an event awaiting delivery together. Acknowledge afterward. PostgreSQL's row-locking docs explain how conflicting updates wait until a transaction ends. Suppose the database commits your move, but the gateway dies before the reply arrives.
6:52 You reconnect and retry the original command. Does the old version now make it fail? No. Retrieve its saved outcome before rejecting the old expected version. It already succeeded; we're returning that decision, rather than asking permission to make it again. A different move from your other tab has no saved outcome. Its stale version does fail. We won't reinterpret it against a position you hadn't seen. That retry should recover my time as well as my move. What clock reading did we actually save for this command?
7:23 Now for the clock reading saved with our move. Suppose processing starts with 4/10 of a second left. A 2-second increment, the accepted-move bonus, leaves 2.4 seconds. Oh, the reply can vanish after the bonus is already mine. But what measures how much thinking time I used? A monotonic clock measures intervals without system-clock adjustments. Store both remaining durations and which side is active. Use only differences between readings on that live owner. An adjustable wall clock tells you an appointment time.
7:54 A stopwatch tells you how long you thought. We're charging a short interval, so we need the stopwatch behavior. Yeah. Python's time docs make that distinction: only differences between monotonic readings have meaning. A replacement machine can't subtract our old raw reading. Walk me through both players' clocks. Where does my charging stop, and when does my opponent start? For this timely accepted move, sample your clock as the request leaves the owner's queue, before any database-lock wait. Your charge is fixed at that reading.
8:27 So while storage is still working, neither player's clock is spending that wait? Under this policy, yes. Your opponent starts only after the healthy owner receives confirmation. An unknown storage outcome can't authorize a new turn. But suppose the rules reject that attempt. Could I restart my dwindling clock just by sending another move? You get no bonus or turn switch, and we don't reset the start of your timed turn. Your clock keeps running toward its original deadline. Then expiry uses the same decision path.
8:58 The timeout scheduler asks the game owner to decide, rather than independently marking the database finished. Suppose your move commits before an old timer is processed. It names the previous version, player and deadline. Re-checking those makes the obsolete timer harmless. If no timely legal move committed, record the rules-defined timeout result. The rules library selects the ending allowed by that position. We don't replace that with a generic timer. And at the exact deadline, which request gets priority?
9:28 Neither gets a special exemption. A move processed at or after the deadline is late. Both move and timer apply that test in the same ordered decision path. Wait, half a second on my phone might already be gone by processing time. Waiting inside our service can cost me the game too. Yes. Bound that queue, measure its age and stop admitting more work into an overloaded owner. This first policy doesn't promise fairness based on when you pressed Send. Chess.com's help gives a real reason those displays can change: limited lag compensation and clocks gaining time after correction.
10:03 That describes its product, without promising fairness for our policy. First take a connection failure with a healthy owner that still knows the active clock's start. Play continues; losing that route doesn't pause the game. Like entering through another door while the same referee holds both clocks. We've lost a route to the game, not its decision authority. On reconnect, send your command identity and the last version seen. Retrieve any recorded answer alongside current state, using accepted updates or a snapshot of position, clocks, version and result.
10:34 My phone last saw 20, but our move committed 21. What if my opponent moves while that snapshot travels back? First register the connection to hold incoming updates, then read retained changes after that snapshot version. Send the replay before draining that same queue as live updates, dropping repeats. If history is gone, a version is missing or the queue fills, fetch a fresh snapshot before applying more. So I can receive the opponent's later move without treating my own retry as another turn or adding an extra bonus.
11:08 But suppose the missing reply is the database's confirmation to the owner. The write may have committed, yet the owner doesn't know it. What happens to those clocks? The phone can lose an answer the referee knows was recorded. Here the referee is uncertain too, so stop new turns and don't start the opponent's clock. So if either player reopens now, do they see a loss or a stopped game? Show checking: we're still confirming the outcome. If interruption is confirmed, keep whatever position reached storage, with both clocks stopped and no rated winner. That wait still leaves our timing problem. A player could say, 'Your queue ate my last half-second.' Could monitoring catch service-caused delays before they decide the game? I'd have the owner regularly read its interval clock.
11:55 A long gap between those checks, or a lengthy storage wait, is reason to attempt interruption. I'm not sure that covers it, actually. The owner computes a timeout, sees no excessive gap yet, then freezes before saving. Can that write still finish? It can, unfortunately. The player could lose during that freeze if the write beats recovery. Checking once doesn't cover everything that happens before saving. That's unsettling. The unsaved timeout is still racing recovery. If storage accepts the valid timeout first, we can recover one answer that was still unfairly timed.
12:30 Now handle owner loss or missing database confirmation without reconstructing a live clock on a replacement. Recovery attempts interruption while preserving whatever state actually committed. So the committed position remains, but play stops without a rated winner if interruption wins. How does recovery stop that old timeout from finishing? Once storage can write, check that the game is still live, then save interruption and the next ownership generation in one transaction. The old referee's pass says seven; recovery records eight. The scorekeeper now accepts eight. Storage is the scorekeeper checking that pass.
13:05 A directory can route me to the old process, but can't renew its permission to write with seven. And the version and live-state checks still apply. If a valid timeout committed before recovery instead, it stays finished. Interruption can't rewrite that ending. So both reopened phones recover the saved board and stopped clocks if interruption won. If timeout committed first, that ending is what comes back. Yes. We can recover the ending, but not prove that lost time was fair. We won't restart clocks whose live interval we no longer know.
13:39 Now distribute independent games across owners and database partitions, storage groups holding different games. Keep each game's position and history together, so one move stays within a single partition. Chess.com's February 2023 update described overloaded databases returning errors and an overloaded live server dropping connections. Their distributed service tested guest games and most games without skill rating changes first. Yeah, I'd want that recovery test before ratings were at stake: commit this move, drop its reply and process the old timer.
14:07 Both phones must recover that stored position, without the stale timer turning it into a loss. A huge crowd can watch through a separate spectator tier. A scoreboard can replace a whole backlog with 1 current position. The referee still decides individual moves from our two players. Right, the crowd can jump to our latest board, but your opponent still needs the outcome of that particular move. I think one broadcast loop looks simpler. But if a celebrity's audience falls behind, what keeps its backlog off the players' clocks?
14:39 Bound the spectator queue and discard intermediate views when it fills; recover a recent snapshot instead. The protected player queue keeps its own limit. Measure decision latency separately from audience delay. If your move is stuck in a transaction, another audience server won't help. If only viewers are behind, moving the game owner creates risk without fixing their feed. Once the game ends, resignation, draw agreement, rule-defined board endings and timeout converge on one transaction. It records the ending and an outgoing result event together.
15:10 Suppose your last move and the opponent's resignation race. Once a valid ending commits, the other command can't replace it with a preferred result. For example, both reopen after the timeout. That ending can appear while ratings still say pending. What prevents a worker from changing only one participant's rating? For a finished rated game, commit both rating changes and the processed result identity in one transaction. Repeated delivery must find that completed effect rather than apply the ratings again.
15:40 Right, one screen can lag even though the update is complete for both players. A late move cannot change that ending. For players still waiting at checking, what should we measure? Track how long they see checking while the game owner lacks database confirmation. Then compare that duration with its queue age and storage wait, because a working login page won't settle their game. Finally, put your piece back on our complete architecture map. It crossed a gateway to one game owner, whose transaction joined the accepted position, clock decision and version.
16:12 If your move was timely and committed but its reply was lost, retrieve the saved answer. The piece really did move. Your phone was missing the outcome. If processing began at the deadline, our policy rejects the attempt. Half a second on the local display couldn't reserve that time while the command waited in our queue. If recovery committed generation eight first, the old seven can't finish the interrupted game. A valid result stored earlier remains final. Those outcomes don't erase the policy's fairness limits.
16:42 Spectators and downstream records follow those decisions; they can catch up without choosing another winner. The public references are linked in the description. I like that we can explain the ending and still admit where the clock policy fails. Recovering one answer doesn't make every possible loss fair. Thanks for listening to Learning Podcasts.