Learning pathsPricingChecking sign-in…
Question Breakdowns

Online Chess

Design turn-based online chess with authoritative legal moves, clocks, reconnects, and game history.

Clarify this prompt before choosing components

Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.

Ask the interviewerWhy the answer changes the design
Real-time games, matchmaking or puzzles first?Authoritative moves and matchmaking need different owners.
Time controls, disconnect grace and draw/resignation rules?Clock and legal state transitions must be serialized.
Duplicate moves, reconnect and cheating policy?Sequence/version checks and a durable game history support recovery.

Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.

Online Chess: Understand the building blocks

Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.

Online Chess: Quick vocabulary

TermMeaning and role in this exercise
API: Application Programming InterfaceThe contract for requests, responses and errors between components. An API route does not itself enforce every business invariant.
PK: Primary KeyThe declared row identity in a database schema; it does not automatically enforce every cross-row business rule.

Online Chess: Forsyth–Edwards Notation (FEN) and ply

What it means: FEN is a compact notation for a chess position and selected state fields. A ply is one player’s move, so a full turn commonly contains two plies.

Why this problem needs it: Board representation and move order need precise meanings.

How to use it: Persist the game’s ordered move history and additional draw/clock state required by the chosen rules; use expected ply and move identity for submission.

Example in this design: A move from ply 12 advances to 13; a position snapshot does not replace all draw-history rules.

When it fits: Useful for snapshotting/displaying a position while a single game authority validates moves.

Alternative and limits: An explicit board structure can fit in-memory calculation. FEN alone is not full repetition history, transport identity or clock adjudication.

Online Chess: WebSocket

What it means: A protocol for bidirectional messages over a persistent connection after a handshake. It is a transport, not a durable message store.

Why this problem needs it: Players need quick move and clock updates.

How to use it: Authenticate the session, route incoming messages to their owner, and bound outgoing buffers. Reconnect using application message IDs and cursors.

Example in this design: The connection broadcasts an accepted move; the game authority validates it first.

When it fits: Useful when both sides send frequent low-latency updates.

Alternative and limits: Polling is simpler at low update rates; Server-Sent Events fit one-way server updates. A new connection does not restore missed messages by itself.

Mechanism reference

Online Chess: Idempotency key and stored operation result

What it means: Idempotency means replaying the same logical operation produces no additional business effect. A key identifies that operation under a defined scope.

Why this problem needs it: A lost move acknowledgement must not execute the move again.

How to use it: Atomically associate a request key and payload fingerprint with its effect and result. Return the stored result on replay; reject incompatible payload reuse.

Example in this design: Retry m7 returns its committed ply-13 result before rejecting the old expected ply.

When it fits: Needed when a timeout can hide a successful commit or a queue can redeliver.

Alternative and limits: Unique business identities can enforce selected effects. A cache of recent requests alone may expire too early or race; local keys cannot control an uncooperative external provider.

Online Chess: Lease, ownership epoch and fencing

What it means: A lease grants temporary work ownership. A fencing token or epoch identifies a newer owner so stale owners can be rejected at the mutation boundary.

Why this problem needs it: A failover must not create two competing clock/move authorities.

How to use it: Claim a job under an atomic authority, increment its attempt/epoch, and require that value on result publication. The protected resource must enforce the check.

Example in this design: The current game epoch fences the former owner’s publications.

When it fits: Useful when workers can pause, restart or overlap after a timeout.

Alternative and limits: A non-expiring lock risks blocking forever. Lease expiry alone cannot stop an old process that resumes; external effects need their own supported idempotency/reconciliation.

Interview scope and guarantees

Create a game, match players, accept legal moves, maintain clocks, reconnect and display spectators. The server decides move legality, turn order and result. Client animations may be optimistic; client clocks cannot determine the winner.

Capacity worksheet

Assume 100,000 concurrent games with a move every 5 seconds per game: 20,000 moves/s. At 200 bytes/move that is 4 MB/s raw. A famous match can have far more spectators than players, so separate authoritative game commands from spectator fanout.

Concrete API contract

Contract / pseudocode
POST /games {opponentId,timeControl}
POST /games/{id}/moves {clientMoveId,expectedPly,from,to,promotion?}
GET /games/{id}?afterPly=...
POST /games/{id}/resign

Data model and access paths

Contract / pseudocode
games(id PK,white_id,black_id,position,ply,state,owner_epoch,turn_started_at,remaining_times,version)
moves(game_id,ply,actor_id,client_move_id,request_hash,notation,accepted_at); UNIQUE(game_id,ply); UNIQUE(game_id,actor_id,client_move_id)
results(game_id UNIQUE,winner,reason,rating_version)

Evolve a solution and explain each change

Three architecture decisions for Online Chess, including the pressure each introduces.
Three architecture decisions for Online Chess, including the pressure each introduces.
Read the diagram

Authoritative game state / Validate moves against the current board and player turn. / Two clients cannot both define the next legal state.; Order moves and clocks / Apply move identity, expected position version, and server clock rules together. / Client timestamps and duplicated packets can corrupt turn order.; Recover sessions / Replay committed moves after reconnect and separate spectators from players. / Socket presence is not proof that a player forfeited.

Open original
Online Chess · architecture decisions
Three architecture decisions for Online Chess, including the pressure each introduces.

Three architecture decisions for Online Chess, including the pressure each introduces.

Step 1: Authoritative game state

Validate moves against the current board and player turn. Two clients cannot both define the next legal state.

Step 2: Order moves and clocks

Apply move identity, expected position version, and server clock rules together. Client timestamps and duplicated packets can corrupt turn order.

Step 3: Recover sessions

Replay committed moves after reconnect and separate spectators from players. Socket presence is not proof that a player forfeited.

Responsibility overview

Connected responsibilities for Online Chess. Trace the authoritative and derived paths separately.
Connected responsibilities for Online Chess. Trace the authoritative and derived paths separately.
Read the diagram

White player to Game API: move and board version; Game API to Game authority: validate turn and clock; Black player to Game API: opponent move; Game authority to Move log: commit ordered move; Game authority to Session registry: locate active sessions; Game API to Move log: replay after version

Open original
Online Chess · connected architecture
Connected responsibilities for Online Chess. Trace the authoritative and derived paths separately.

Connected responsibilities for Online Chess. Trace the authoritative and derived paths separately.

Worked end-to-end scenario

White sends move e2-e4 at board version 12, then retries after a lost response. The authority validates legality, turn, version, and remaining time and records one move identity. The retry returns version 13 rather than consuming a second turn. Black reconnects and replays from version 12. Clock accounting uses a defined server admission instant and monotonic elapsed time, with a stated lag/timeout policy. A late move received after expiry cannot be accepted based solely on the player’s device clock. Spectator delivery can lag without changing the authoritative result.

Why these access paths matter

Store game ID, players, board version, clock state, outcome, and ordered moves. Use game as the serialization domain and actor/client move ID for retries. A board snapshot plus move suffix supports recovery; both need a consistent version boundary. Presence, chat, and spectator subscriptions are independent from legal move state.

Build the baseline first

Online Chess: baseline request paths.
Online Chess · working baseline
Read the diagram

Player move → game owner → legality and clock check; Atomic position update → durable move → opponent; Reconnect → position snapshot and move suffix

Open original
Online Chess · working baseline
Online Chess: baseline request paths.

Online Chess · working baseline

  1. Player move → game owner → legality and clock check.
  2. Atomic position update → durable move → opponent.
  3. Reconnect → position snapshot and move suffix.

Evolve the design under load

Online Chess: additional scaling and recovery paths.
Online Chess · scale and recovery paths
Read the diagram

Game-key routing → independent state owners; Spectator stream → regional gateways; Completed games → rating jobs and analysis queue

Open original
Online Chess · scale and recovery paths
Online Chess: additional scaling and recovery paths.

Online Chess · scale and recovery paths

  1. Game-key routing → independent state owners.
  2. Spectator stream → regional gateways.
  3. Completed games → rating jobs and analysis queue.

Defend the hardest decision

Validate expected ply, player identity, legal movement and remaining time in one authoritative transition. Persist the clock baseline rather than decrementing a database row every millisecond. A server process uses a monotonic clock for elapsed time within its lifetime; failover needs a documented persisted-time policy and synchronized server clocks. The chosen lag-compensation rule must be explicit and abuse-resistant.

Failure and recovery analysis

A move commits but its response is lost. A retry with the same clientMoveId returns the committed move. A different move for the old ply is rejected. An old game owner returning after failover must be fenced from committing moves. Spectator lag can grow without delaying the players, provided buffers are bounded.

Security and privacy boundary

Authorize player actions, protect matchmaking from abuse, and separate anti-cheat analysis from the low-latency move path.

Interview follow-ups with reasoning

Question: How do you resolve simultaneous resign and move?

Show answer and explanation

Answer: Serialize commands at the game owner.

Question: How do you rebuild a board?

Show answer and explanation

Answer: Replay validated moves from a versioned initial position.

Question: How do you update ratings safely?

Show answer and explanation

Answer: Deduplicate by completed game and rating algorithm version.

Operate and verify the design

Move latency, stale-ply rejections, clock anomalies and duplicate rating jobs.

Fail over the game owner during a move and verify one committed ply and a consistent clock baseline.

A second scenario to test transfer

White and Black both submit moves against version 40 due to a client bug. Only White is side to move. The game authority validates White’s move and commits version 41. Black’s stale command fails with current version and board. If White retries after losing the response, the same request ID returns the committed ply rather than applying another move.

White’s move request commits, but the response is lost. What happens when the client retries and Black submits against the old version?

Show answer and explanation

Answer: White retries with the same request ID and receives the already committed ply. Black’s command is checked against the authoritative side and version; it cannot overwrite White’s move. The next valid move uses the new version. This provides idempotent command handling and one game order.

Compare alternatives

EventAuthoritative?Recovery
Board animationNoReplace with snapshot/event
Committed plyYesReplay by ply cursor
Displayed clockApproximationServer turn deadline
PresenceEphemeralReconnect and refresh

A design-changing exercise

Both clients say their clocks had time remaining. Which timestamp decides the result?

Show answer and explanation

Answer: Use the defined authoritative server admission and clock policy. Client clocks are not trustworthy enough to own the game outcome.

Design workshop: moves, clocks, and owner recovery

Requirements, APIs, and scale assumptions

Core scope is standard chess, skill-based matchmaking, timed games, reconnect, and bounded spectator fanout. Variants and anti-cheat model training are extensions. A client submits a move proposal; a tested rules library decides legality on the server. This service baseline admits moves at server receipt time with no latency compensation. Client animation and displayed clocks are estimates, never authority. One active ticket per player, one committed move per stable request identity, one result per game, and one rating update per game/player are hard invariants.

POST /matchmaking-tickets includes region, rating, time control, and an idempotency key. DELETE /matchmaking-tickets/{id} cancels only a waiting ticket. POST /games/{id}/moves includes clientMoveId, expectedPly, and the move; GET /games/{id} returns a versioned snapshot and server clock values; an event stream resumes with afterPly, returning a snapshot plus cursor when retained history has expired. POST /games/{id}/resign and /draw are versioned commands. GET /leaderboard reads an asynchronously projected ranking. Never use a client timestamp to decide whose clock ran.

MatchTicket(player, region, rating, base_ms, increment_ms, created_at), Game(id, version, position, side_to_move, clock_anchor, remaining_ms, owner_epoch), Move(game_id, ply unique, actor, client_move_id unique, fingerprint), Result(game_id unique, reason, winner), and RatingUpdate(game_id, player_id unique, version) separate queue state, authoritative game state, event history, result, and derived rank. Store full legal-position state (FEN-like board plus castling, en-passant, half-move, and repetition evidence), not piece locations alone. The reference model injects the rules adapter and deliberately does not pretend to implement chess legality.

For an illustrative load, assume 100,000 active games, each averaging 0.1 committed moves/s: 10,000 events/s. At 300 encoded bytes/event that is 3 MB/s, about 259 GB/day, or 1.81 TB for seven days before indexes and replication. This informs game/event partitioning and retention. A hot game with 50,000 spectators at the same move rate emits 5,000 fanout deliveries/s (about 1.5 MB/s at 300 bytes each), so spectator gateways need their own bounded queues and capacity; they must not share the game authority's command path.

Claim two compatible tickets exactly once. Player A to Match queue: Create a ticket with stable request identity; Match queue to Atomic ticket store: Select compatible region, time control, and rating window; Atomic ticket store to Atomic ticket store: Claim both waiting tickets in one transaction; Atomic ticket store to Game authority: Create one game and mark both tickets matched; Game authority to Player A: Return game ID and player color
Claim two compatible tickets exactly once.
Read the diagram

Create a ticket with stable request identity; Select compatible region, time control, and rating window; Claim both waiting tickets in one transaction; Create one game and mark both tickets matched; Return game ID and player color

Open original
Claim two compatible tickets exactly once
Claim two compatible tickets exactly once. Player A to Match queue: Create a ticket with stable request identity; Match queue to Atomic ticket store: Select compatible region, time control, and rating window; Atomic ticket store to Atomic ticket store: Claim both waiting tickets in one transaction; Atomic ticket store to Game authority: Create one game and mark both tickets matched; Game authority to Player A: Return game ID and player color

Claim two compatible tickets exactly once.

Matchmaking uses region and time control as hard predicates, then expands the rating window according to both players' shared waiting time. The atomic pair claim prevents the same player from entering two games. A ticket retry returns its existing state; a matched ticket cannot be canceled.

Store FEN-like board state plus move history, castling rights, en-passant state, side to move, half-move counter and repetition evidence. Piece locations alone cannot reconstruct all legal state. Validate check, promotion, castling and en-passant under the selected rules; distinguish claimable and automatic draws using documented rules. Do not turn every repeated board diagram into a draw without comparing legal-position state.

The move identity is unique(game,actor,client_move_id) with fingerprint. Before rejecting expectedPly, check whether that exact command already committed and return its original ply. Then lock game state, validate actor/turn/version/owner epoch/time/legality and atomically append the move with updated board and clock. A retry cannot consume a second turn.

Lost response returns the already committed move. White to Game authority: e2-e4 request m7 at expected ply 12; Game authority to Move log: Commit m7 as ply 13 with updated clock; Game authority to White: Response lost; Black to Game authority: Move using stale expected ply 12; Game authority to Black: Conflict; return current ply 13; White to Game authority: Retry m7; request lookup returns original ply 13
Lost response returns the already committed move.
Read the diagram

e2-e4 request m7 at expected ply 12; Commit m7 as ply 13 with updated clock; Response lost; Move using stale expected ply 12; Conflict; return current ply 13; Retry m7; request lookup returns original ply 13

Open original
Lost response returns the already committed move
Lost response returns the already committed move. White to Game authority: e2-e4 request m7 at expected ply 12; Game authority to Move log: Commit m7 as ply 13 with updated clock; Game authority to White: Response lost; Black to Game authority: Move using stale expected ply 12; Game authority to Black: Conflict; return current ply 13; White to Game authority: Retry m7; request lookup returns original ply 13

Lost response returns the already committed move.

With 60 seconds remaining, White starts at monotonic t=100 and the server admits a legal move at t=104. Charge four seconds and add a two-second increment, leaving 58 seconds. The increment applies only after an accepted legal move. A rejected illegal request does not pause the clock. If a move arrives after the declared remaining time expires, reject under the selected policy; claimed device send time cannot override it.

Use server receipt time as the clock boundary. White client to Game authority: Begin turn from persisted clock anchor at t=100; White client to Game authority: Submit legal move; server receives it at t=104; Game authority to Game authority: Charge four seconds, add two-second increment, switch side; Game authority to Durable game state: Commit move, new clock anchor, ply, and clock values atomically; Durable game state to White client: Publish accepted ply and updated display estimates
Use server receipt time as the clock boundary.
Read the diagram

Begin turn from persisted clock anchor at t=100; Submit legal move; server receives it at t=104; Charge four seconds, add two-second increment, switch side; Commit move, new clock anchor, ply, and clock values atomically; Publish accepted ply and updated display estimates

Open original
Use server receipt time as the clock boundary
Use server receipt time as the clock boundary. White client to Game authority: Begin turn from persisted clock anchor at t=100; White client to Game authority: Submit legal move; server receives it at t=104; Game authority to Game authority: Charge four seconds, add two-second increment, switch side; Game authority to Durable game state: Commit move, new clock anchor, ply, and clock values atomically; Durable game state to White client: Publish accepted ply and updated display estimates

Use server receipt time as the clock boundary.

The reference recovery policy persists clock heartbeats and an owner lease. On failover, charge the active player through the last lease expiry using the persisted clock anchor, record the recovery pause interval, fence the old owner with a higher epoch, and resume from the recovery timestamp. This bounds uncertainty to the heartbeat/lease contract and exposes paused time for audit; it does not claim submillisecond recovery precision. Use a calibrated service-time source for persisted receipt/lease timestamps. A production alternative is a trusted durable deadline with bounded skew; never subtract one machine's monotonic timestamp from another's.

Matchmaking stores region/rating/time-control queues and uses an atomic pair claim to prevent one player entering two games. A declared expanding rating band reduces long waits. Ratings update once under unique(game,rating_version). An illustrative Elo update uses expected score E=1/(1+10^((opponent−player)/400)), then R_new=R+K(S−E); equal ratings with K=20 and a win gain 10. This is a chosen teaching policy, not a claim about a chess platform's real rating algorithm.

Commit one result and project each rating once. Game authority to Result and rating ledger: Write unique game result and both player rating updates; Result and rating ledger to Rating outbox: Commit stable event IDs in the same transaction; Rating outbox to Leaderboard projection: Deliver each player/version update at least once; Leaderboard projection to Leaderboard projection: Apply only a newer per-player rating version; Leaderboard projection to Game authority: Expose updated ranking after projection catches up
Commit one result and project each rating once.
Read the diagram

Write unique game result and both player rating updates; Commit stable event IDs in the same transaction; Deliver each player/version update at least once; Apply only a newer per-player rating version; Expose updated ranking after projection catches up

Open original
Commit one result and project each rating once
Commit one result and project each rating once. Game authority to Result and rating ledger: Write unique game result and both player rating updates; Result and rating ledger to Rating outbox: Commit stable event IDs in the same transaction; Rating outbox to Leaderboard projection: Deliver each player/version update at least once; Leaderboard projection to Leaderboard projection: Apply only a newer per-player rating version; Leaderboard projection to Game authority: Expose updated ranking after projection catches up

Commit one result and project each rating once.

The result transaction is unique by game; the rating ledger is unique by (game_id, player_id) and serializes each player's versions. A leaderboard relay can retry delivery, and an older projection message cannot roll a player's displayed rating backward. Do not update rankings from uncommitted game state.

Spectator gateways consume committed ply events separately from player commands. A reconnect supplies afterPly; return suffix or board snapshot+cursor when history no longer supports it. Bound spectator buffers and never let a million watchers exhaust move authority. Privacy/authorization still applies to private games.

Final topology: isolate authority from fanout. Matchmaker / Atomic compatible-ticket pair claim / One waiting ticket per player; bounded rating expansion; Game owner / Legal move, server clock, version, result / Per-game fencing epoch; leased ownership; Move log and snapshot / Committed ply replay and reconnect / Retention floor; snapshot plus cursor on expiry; Rating ledger and relay / Unique result and per-player rating version / Once per game/player; monotonic projection; Spectator gateways / Read-only event fanout / Per-game and per-client queue caps
Final topology: isolate authority from fanout.
Read the diagram

Component / Authoritative responsibility / Bound or freshness contract; Matchmaker / Atomic compatible-ticket pair claim / One waiting ticket per player; bounded rating expansion; Game owner / Legal move, server clock, version, result / Per-game fencing epoch; leased ownership; Move log and snapshot / Committed ply replay and reconnect / Retention floor; snapshot plus cursor on expiry; Rating ledger and relay / Unique result and per-player rating version / Once per game/player; monotonic projection; Spectator gateways / Read-only event fanout / Per-game and per-client queue caps

Open original
Final topology: isolate authority from fanout
Final topology: isolate authority from fanout. Matchmaker / Atomic compatible-ticket pair claim / One waiting ticket per player; bounded rating expansion; Game owner / Legal move, server clock, version, result / Per-game fencing epoch; leased ownership; Move log and snapshot / Committed ply replay and reconnect / Retention floor; snapshot plus cursor on expiry; Rating ledger and relay / Unique result and per-player rating version / Once per game/player; monotonic projection; Spectator gateways / Read-only event fanout / Per-game and per-client queue caps

Final topology: isolate authority from fanout.

Fail over at a lease boundary and replay one result. White to Old game owner: Send move with stable clientMoveId; owner commits ply 13; Old game owner to Durable move/result log: Response is lost; identical retry finds original ply before stale-ply validation; Old game owner to Durable move/result log: Owner lease expires; next owner charges clock to lease boundary and records pause; Durable move/result log to Durable move/result log: New epoch fences old owner; result command commits one game result; New game owner to Durable move/result log: A stale owner result replay is rejected; duplicate result key returns prior outcome
Fail over at a lease boundary and replay one result.
Read the diagram

Send move with stable clientMoveId; owner commits ply 13; Response is lost; identical retry finds original ply before stale-ply validation; Owner lease expires; next owner charges clock to lease boundary and records pause; New epoch fences old owner; result command commits one game result; A stale owner result replay is rejected; duplicate result key returns prior outcome

Open original
Fail over at a lease boundary and replay one result
Fail over at a lease boundary and replay one result. White to Old game owner: Send move with stable clientMoveId; owner commits ply 13; Old game owner to Durable move/result log: Response is lost; identical retry finds original ply before stale-ply validation; Old game owner to Durable move/result log: Owner lease expires; next owner charges clock to lease boundary and records pause; Durable move/result log to Durable move/result log: New epoch fences old owner; result command commits one game result; New game owner to Durable move/result log: A stale owner result replay is rejected; duplicate result key returns prior outcome

Fail over at a lease boundary and replay one result.

The same cursor handles player reconnect and spectator replay, but their authorization and queue budgets differ. Move authority processes one game serially; spectator delivery is asynchronous and may lag. When the player resumes after a disconnect, fetch a snapshot and event suffix before sending commands against its current ply.

Operations and practice

SLIs: matchmaking wait percentiles and unmatched queue age; legal-move commit latency; rejected stale-ply/duplicate/conflict rate; owner lease expiry and failover pause duration; game event-to-client lag; result-to-rating projection delay; and spectator queue drops. Overload controls: bound ticket scans, open games per owner, per-game spectator fanout, event history, and reconnect snapshot size. Shed or delay spectator updates before move authority. Recovery: acquire a higher owner epoch, reconstruct board and clock from the latest committed snapshot plus move suffix, charge time through the last trusted lease boundary, record pause, and resume only after state validation. Access: only two participants may issue game commands; spectator tokens are read-only and private-game authorization is checked at snapshot and stream subscription. Dominant costs: move/event retention and spectator fanout, which scales with watchers times move rate.

Practice prompt: Design a rated 60-second-plus-increment chess service with 100,000 concurrent games and one 50,000-watcher match. Follow-up: the owner commits a move at time expiry, loses the response, then fails over while a duplicate result is replayed. Rubric: derive move and spectator traffic; atomically claim tickets; delegate legality to a tested engine; use expected ply and command idempotency; charge authoritative receipt time; persist clocks and fence owners; recover without silently granting time; apply result/rating once and version leaderboard projections; show bounded stream replay and spectator isolation. Invariant: a game has one canonical move sequence and result, with clock and rating effects applied at most once per accepted transition.

Exercise: White's request committed ply 13 but response was lost. Its retry carries expectedPly=12. Reject as stale or replay?

Show answer and explanation

Answer: Look up the stable actor/request identity first and return committed ply 13. Only an unseen command with old expectedPly conflicts. This ordering is part of the API contract, not just a uniqueness constraint.

FIDE Laws of Chess inform over-the-board legality and draw distinctions; the server-receipt clock, latency, and recovery policies above are separate online-service choices.

Requirement trace and verification

RequirementImplementing design blockVerification link
R1 — Complete the primary user journey within the stated scope.P01–P04; P09–P10.V1 — Exercise the successful journey and the excluded/boundary case stated in the scope.
R2 — Preserve the problem's authoritative data invariant under concurrency.P05–P06; P11–P12; DD1.V2 — Run the race/replay case below and assert the invariant at the durable authority.
R3 — Meet the declared scale and API behavior without unbounded work.P05–P08; P13–P14; relevant overload deep dives.V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity.
R4 — Recover from the named failure without losing or duplicating the user-visible outcome.P15–P16; deep dives; Operations contract.V4 — Duplicate a move, disconnect at time expiry, fail the game owner, and replay results; one outcome and one rating update survive.

Operational contract

AreaDecision and signals
SLIsMove-ack latency; game-owner recovery time; clock drift; reconnect replay lag; rating projection delay.
Overload limitsCap matchmaking queue age, concurrent games per worker, spectators per hot game, and event retention.
RecoveryRecover from versioned move log and server timestamps; fence old game owners; apply rating once by game/player key.
Access controlsAuthorize participants/spectators per game and protect account/anti-cheat signals.
Dominant costPersistent move/event storage and hot-match spectator fanout.

Senior-level interviewer follow-ups

Question: A player disconnects during their turn. Does their clock stop?

Show answer and explanation

Answer: The product policy must be explicit. Persist the authoritative turn start/deadline and reconnect token; if disconnect pauses the clock, record a fenced pause event rather than trusting client time.

Question: A stale client submits a legal move for the previous board position. Why reject it?

Show answer and explanation

Answer: Legality is evaluated against the current authoritative ply and version. Use the command identity for retry dedupe, then compare expected version before applying the move.

A 60-second design answer

I would route each game to an authoritative game owner that validates moves against the current position and ply, deduplicates client commands, and appends a durable move event. The server owns clock deadlines; reconnect sends a versioned snapshot and events after the cursor. I would monitor move conflicts, clock skew, reconnect lag, illegal commands, and adjudication delay.

Real-time Updates Dealing with Contention

Technical references

PostgreSQL transaction isolation and concurrent updates.

Resolve a retried move before rejecting its old ply

Move m7 by White commits at resulting ply 13, but its response is lost. Its retry carries expected ply 12. First look up the same game/player/move identity: return the original ply-13 outcome. Treating it as a fresh stale-ply request would misreport an already successful move. Black's different move against ply 12 remains a conflict and must refresh.

Contract / pseudocode
m7 expected 12 -> legal adapter -> committed ply 13
retry m7 expected 12 -> original result ply 13
new opponent move expected 12 -> conflict
m7 expected 12 -> legal adapter -> committed ply 13; retry m7 expected 12 -> original result ply 13; new opponent move expected 12 -> conflict
Resolve a retried move before rejecting its old ply
Read the diagram

m7 expected 12 -> legal adapter -> committed ply 13; retry m7 expected 12 -> original result ply 13; new opponent move expected 12 -> conflict

Open original
Resolve a retried move before rejecting its old ply
m7 expected 12 -> legal adapter -> committed ply 13; retry m7 expected 12 -> original result ply 13; new opponent move expected 12 -> conflict

Resolve a retried move before rejecting its old ply

Legality comes from a tested rules adapter, not a handwritten shortcut for every chess rule. Use server-authoritative clock/increment and declared arrival/expiry rules. A game owner lease is fenced at move/result storage; paused owners cannot independently declare a winner. Reconnect snapshots overwrite uncommitted local animation, while spectators use an isolated bounded path. Unique terminal results feed ordered rating updates.

Show answer and explanation

Answer: Operation dedupe and version checks must have a declared order. A timeout cannot be treated as proof the clock/move failed, and client wall time does not decide a server result.

Decision review: Online Chess

Online Chess: What it is

A chess service owns legal game transitions, move identity and the declared server-time clock rule.

Online Chess: Why it is needed

A locally animated move is not an accepted move; replay and clock expiry can race the same state transition.

Online Chess: When to use it

Use a per-game authority when legal turns, clocks and terminal outcomes must have a deterministic order.

Online Chess: How to use it

Deduplicate the move ID before rejecting its old expected ply. Validate current turn and legal move at the owner, apply the clock policy and commit the resulting position/ply together.

Online Chess: Compare an alternative

Client-side validation improves responsiveness but cannot be the final authority in a competitive game. Different lag-compensation policies must be explicitly agreed and bounded.

Online Chess: Worked decision exercise

The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.

Move m7 commits from ply 12 to 13 but its reply is lost. The client retries m7 with expected ply 12. Returning the committed m7 result before a stale-ply error preserves useful retry semantics; a different move ID with ply 12 conflicts.

Online Chess: Move m7 advances ply 12 to 13; Reply is lost; retry still names m7 and ply 12; Dedup returns committed result at ply 13; Another move ID with old ply conflicts
Online Chess: a concrete state and recovery trace under the exercise assumptions.
Read the diagram

Move m7 advances ply 12 to 13; Reply is lost; retry still names m7 and ply 12; Dedup returns committed result at ply 13; Another move ID with old ply conflicts

Open original
Online Chess: worked example
Online Chess: Move m7 advances ply 12 to 13; Reply is lost; retry still names m7 and ply 12; Dedup returns committed result at ply 13; Another move ID with old ply conflicts

Online Chess: a concrete state and recovery trace under the exercise assumptions.

What decides a move arriving around flag expiration?

Show answer and explanation

Answer: The declared owner-time admission/clock policy, applied atomically with game state. Do not allow separate clock and move workers to both announce incompatible terminal results. On reconnect, reconcile the client animation against the authoritative position.

Online Chess: Check the design

Test move replay, legal-turn rejection, clock/commit race and reconnect after an unacknowledged animation. Track unresolved game-owner handoff and state-version gaps.

Chess extension: keep time and result in the accepted history

Start with the existing legal-move and reconnect baseline. This workshop extends server decision-time arithmetic, expiry generations, draw/resign ordering and an explicit service-outage recovery policy. Player disconnect, owner failure and terminal result remain separate facts.

Deep dive: one move, one clock decision and one final result

The baseline establishes legal moves and durable history. This workshop makes clock policy, terminal-command ordering and owner recovery explicit. Use an original casual-game policy: server-authority decision time, no client timestamp credit, a fixed increment, player disconnects that do not pause clocks, and a separately declared service-outage pause. These choices are not a claim of tournament compliance or another platform's internals.

Put rules, identity and clock state in one transition

Persist game ID, players, rules-engine version, starting position, ordered moves, side to move, ply, command version, owner epoch, remaining milliseconds, clock baseline and terminal result. Ply counts accepted moves; command version also advances for draw offers, pauses and other commands. They cannot substitute for one another. Store enough legal history for repetition, castling, en passant and draw adjudication; a board image or FEN alone is insufficient for all history-dependent outcomes.

Submit a move with authenticated actor, scoped client move ID, exact move/promotion and expected ply. Bind its receipt to the payload. Under the current owner epoch, read the saved receipt before treating an old expected ply as a fresh conflict. A compatible retry returns its accepted ply and clock result even after another move or game completion; current access still gates disclosure. Same-key changed moves conflict. A genuinely new stale-ply request gets current authorized state without changing either clock baseline or board.

For a fresh current-ply player command, one serialized decision samples trusted monotonic time, evaluates expiry and legality, commits the legal position/clock/result/receipt and publishes through durable intent. In this exercise processing/queue time counts; the client and gateway receive timestamps do not decide eligibility. Sample within the authoritative serialized decision, not on an untrusted connection and not once at enqueue then again independently during a timer race. Invalid moves do not switch turns, earn increment or restart the clock. If time expired first, the rules engine determines the permitted timeout result, including any relevant draw exception.

A legal White move stores 4000 milliseconds once and advances the clock generation; the old expiry timer cannot flag the new turn
Online Chess: recovery decision
Read the diagram

White starts with 5000 ms at time 100000 → Legal move commits at time 103000 → Increment stores 4000 ms and advances ply → Old White expiry timer fires at 105000 → Current clock generation rejects stale timer

Open original
Online Chess: recovery decision
A legal White move stores 4000 milliseconds once and advances the clock generation; the old expiry timer cannot flag the new turn

Online Chess: recovery decision

Calculate the deadline and invalidate the old timer

White has 5,000 ms at monotonic baseline 100,000 ms and a 2,000 ms increment. A legal decision at 103,000 consumes 3,000 ms, leaving 2,000; add the increment to store 4,000 ms. Black's turn starts from that accepted decision instant. Return remaining times, active side, server time reference and ply so clients can animate estimates. The next authoritative decision corrects those displays.

White's old expiry was 105,000. Its timer carries (game, owner epoch, clock generation, expected ply, side). After the move advances ply and clock generation, that old callback cannot flag Black or end the game. A valid timer still checks current remaining time; delayed timer execution does not extend eligibility for a fresh move. At exactly 105,000 with no prior move, remaining is zero and expiry wins under this exercise policy. An earlier gateway arrival processed at 105,001 is late; advertise the queue-time policy and measure its fairness cost.

If the opponent cannot win by any legal sequence under the selected rules, do not assume timeout always awards a win. The versioned rules engine must supply terminal classification. Likewise checkmate, stalemate, draw claims and automatic draws need their own rule predicates. The contract fixtures use a small legality/result oracle to test atomic orchestration; they do not implement a chess engine or establish complete chess correctness.

Order resignations, draw offers and downstream effects

Resign, draw-offer/accept and legal moves share the game authority. A resignation committing first makes a later new move terminal-rejected. A checkmating move committing first freezes that result; a later resignation cannot replace it. A nonterminal move first may still be followed by a valid resignation. An accepted move retry returns its receipt and never creates another ply or increment. Always bind result publication to a unique game result identity.

A draw offer has proposer, offer ID and offer generation/command version. Only the opposing player can accept the current live offer while the game is active. Define expiration explicitly: this exercise expires the offer on the next accepted move, replacement offer or terminal transition. A delayed accept cannot refer merely to 'some offer existed'. A production product may choose different offer lifetimes, but must enforce the selected policy in the same serialized decision.

Post-game rating uses a stable (game, rating policy version) effect identity. If ratings for both players share one database boundary, update both and the applied-game receipt atomically; otherwise specify pending/compensation semantics. Independent per-player jobs can leave asymmetric results. Anti-cheat findings may create a separately audited adjudication/rating correction revision. They do not rewrite the historical move log or silently rerun the same rating application. Keep private analysis, reports and moderation access out of spectator events.

Recover an owner without inventing elapsed time

A monotonic timestamp from process A is not comparable with process B's local monotonic epoch. Fence A at the durable mutation authority before B can publish. Recover a verified complete move/clock prefix, receipts and terminal state; the highest seen ply without matching clock/result evidence is insufficient. An acknowledged move must satisfy the declared durable replication policy before failover may claim it preserved that promise.

For this casual exercise, service failure enters a visible paused/recovering state. Recover the last durable remaining times, waive the uncertain unrecorded interval, and establish a fresh monotonic baseline only on explicit resume under the new owner epoch. This can return thinking time, so disclose the fairness tradeoff and protect outage controls from player manipulation. Persisted checkpoints can narrow that interval. If an accepted terminal state already exists, resume is forbidden. A player disconnect is different: while the service is healthy, its clock continues and reconnect cannot reset the baseline.

An alternative strict wall-clock continuation requires durable deadlines, bounded trustworthy time and an explicit uncertainty/adjudication policy. Never subtract unrelated process-local monotonic readings. Reconnect returns an authorized snapshot at ply P plus complete suffix and current clock generation; optimistic unacknowledged moves reconcile by their original identity. Bound replay and use snapshot resync below the retention floor. Separate delayed spectator fanout from player command admission.

Budget latency, spectators and recovery

At 100,000 simultaneous games and one move every five seconds per game, accept 20,000 moves/s. Two player deliveries per move produce 40,000 events/s; at 300 bytes/event this is 12 MB/s before transport overhead. A single popular game with 200,000 spectators and one move every two seconds adds 100,000 spectator events/s, or 30 MB/s at the same size. Separate finite spectator buffers, fanout quotas and delayed public clocks from game locks.

If a serialized game decision costs 2 ms, one game has a theoretical 500 decisions/s ceiling before overhead; total system throughput comes from independent game shards. Do not allocate thousands of spectator writes inside that critical section. A recovered shard with 60,000 queued replay events, 5,000/s recovery capacity and 2,000/s fresh events needs at least twenty seconds to catch up; prioritizing active player recovery may delay spectators honestly.

Measure decision queue age, move commit latency, expiry-boundary disputes, clock regressions, stale epoch/timer rejection and rating reconciliation age. Keep finite per-game command and per-session byte limits. Test equality at expiry, lost replies, stale timers, repeated draw acceptance, owner pause/resume and result-versus-resign ordering. Review FIDE's online regulations for competition requirements: player disconnection and event-specific rules need explicit treatment. The service-outage waiver here remains an exercise policy.

Chess assessment: defend the clock and result evidence

Question: White's legal move commits at 103,000 with 5,000 ms from baseline 100,000 and a 2,000 increment. The reply is lost; the old 105,000 timer later fires. What changes on retry?

Show answer and explanation

Answer: Store 4,000 ms for White once, advance ply/clock generation and begin Black's turn. The matching retry returns that receipt without another increment. The timer has the old side/ply/generation and cannot terminate the new turn.

Question: A gateway saw a move before expiry, but authority processing occurs at expiry equality. Can the client clock save it?

Show answer and explanation

Answer: Under the declared decision-time policy, no: zero remaining is expired. The rules engine determines the correct timeout result rather than assuming every flag is a win. A different lag-compensation policy needs trusted measurements, abuse bounds and its own tests.

Question: The owner dies after an acknowledged move and the replacement has a different monotonic origin. Can it keep subtracting the old timestamp?

Show answer and explanation

Answer: No. Recover the complete durable state and fence the old epoch. This exercise visibly pauses, preserves durable remaining time and resumes with a new baseline; it discloses the uncertain-time waiver. Player disconnect alone never invokes that service-outage policy, and terminal games cannot resume.

Score one point each for scoped move receipts and legal-history state; exact clock/increment arithmetic; stale timer and terminal/draw ordering; fenced complete-state recovery with an explicit time policy; bounded fanout and once-only rating effects. Restarting the clock on duplicate moves or comparing unrelated monotonic origins is a critical failure. Repair the transition, then retest with a draw accept after an intervening move and a terminal result committed just before owner loss.

Your study notes