Building a Resilient Multiplayer Chess Backend
System DesignModel answerLast updated
Architect a real-time chess platform where each game has one authoritative owner, exactly-once move application, server-driven clocks, fast crash recovery, and low-latency spectator streaming.
Scenario
You are building the backend for an online chess platform. At peak it must host a large number of simultaneous matches (start from thousands, then reason about what changes at roughly 100k). Players connect over persistent sockets, and a match must stay correct even when machines die, networks split, or players drop off mid-game.
Behavior the system must provide
- Rule enforcement: each submitted move is checked against the current position and against whose turn it is.
- Authoritative time: the server owns the clocks. Clients only display what they are told. If a player's connection drops, their clock keeps running.
- Durable history: every game is recorded as an append-only sequence of events that can be audited later.
- Rejoining: a player who loses connection can come back and resume the same game without confusion.
Quality attributes
- Crash recovery: if the process running a game dies, the game must be back in service within a few seconds, with no state lost.
- Safe retries: if a client resends a move after a timeout, it must never be applied twice.
- Agreement: both players must observe the identical sequence of moves regardless of differing network latencies.
What to deliver
- An overall architecture covering real-time connection handling and where durable game state lives.
- The structure of the move log, showing how it guarantees ordering and duplicate protection.
- A walkthrough of what happens when the server that owns a game crashes, including how you prevent two servers from acting on the same game.
- A strategy for letting a large audience watch games live with low delay.
State your assumptions about scale and latency up front, and call out the trade-offs behind your choices.
Hints
Hint 1
Give each game exactly one active owner at a time, and have that owner process events for the game one by one. Think about how a lease with a monotonically increasing number (an epoch) lets the storage layer reject a stale owner.
Hint 2
Let the database enforce correctness: a composite key on (game, move number) makes it impossible for two writers to both commit the same move, and a uniqueness rule on a client-supplied request id turns retries into lookups.
Hint 3
Do not store a ticking counter for the clock. Store the remaining time at the start of the current turn plus the timestamp, and derive the live value; this makes recovery after a crash and behavior during disconnects trivial.
Hint 4
Separate players from spectators: spectators should read from a broadcast channel fed by the committed log, not from the owner process, so audience size never slows down the game itself.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Pin down scale and invariants
Assumptions: 100k concurrent games, about 200k players plus spectators (a few games with 10k+ viewers). A blitz game produces a move every 5-10 seconds, so the cluster handles roughly 10-20k moves per second. That is a modest write load; correctness matters far more than raw throughput.
Targets: move round trip under 100 ms in-region, spectator lag under about 1 s, game back online within about 5 s of a crash.
Invariants to protect:
- At most one authoritative writer per game at any moment.
- Each move number is applied exactly once.
- Both players see the same ordered sequence.
2. Architecture
Clients --WS--> Gateway tier (stateless, owns sockets)
| route by game_id
v
Match servers (stateful, one actor per game)
| |
lease + epoch conditional append
v v
Coordination store Move log DB (sharded by game_id)
(etcd / ZooKeeper) | change stream
v
Pub/Sub --> Spectator fan-out tier
- Gateways hold the WebSocket connections and know nothing about chess. They look up which match server owns a game and forward frames. If a match server dies, client sockets survive; only the routing target changes.
- Match servers hold one in-memory actor per game (board, clocks, timer). Each actor drains a mailbox serially, which removes in-process races.
- Coordination store hands out leases (per game or per shard) carrying a monotonically increasing epoch used as a fencing token.
3. Protocol essentials
Client messages: JOIN {game_id, token, last_seen_ply}, MOVE {game_id, ply, move, request_id}, resign, draw offer. Server messages: STATE (position, ply, clocks, turn), MOVE_APPLIED, REJECTED, GAME_OVER.
ply is an optimistic-concurrency claim ("this is move N"). request_id is a client-generated UUID for deduplication.
4. Move log schema
game_moves
game_id, ply PRIMARY KEY (game_id, ply)
move, player
request_id UNIQUE (game_id, request_id)
accepted_at server timestamp
clock_white_ms, clock_black_ms (remaining, after this move)
owner_epoch fencing token of the writer
A games table stores players, time control, status, result and the current epoch.
The primary key makes duplicate or out-of-order commits impossible at the storage layer. The unique request id lets a retry find the original outcome. Because each row stores post-move clocks, the full state is rebuildable: the board is a replay of moves, and live clocks are the last stored value minus time elapsed since accepted_at for the side to move.
Use a strongly consistent store (sharded Postgres, CockroachDB, Spanner). Eventually consistent stores are a poor fit for the fencing check.
5. Move handling
- Dedup: if
request_idwas already applied, resend the earlier result and stop. - Turn/ply check: reject if the ply is not current + 1 or it is not that player's turn, returning current state.
- Legality: validate with the rules engine on the in-memory board.
- Clock update: subtract elapsed time from the mover, add any increment; if it hits zero, the game ends on time.
- Fenced durable write: insert in a transaction that also verifies the game's epoch equals the actor's epoch. A key conflict or epoch mismatch means "I am no longer the owner", and the actor stops.
- Only after commit: update memory, send
MOVE_APPLIEDto both players, publish to spectators.
Writing before acknowledging means no player ever sees a move that could be lost. Both players get the same stream keyed by ply; a client that sees a gap asks for a resync, so latency differences cannot cause divergence.
6. Clocks
The clock is derived, never a stored counter: remaining = value_at_turn_start - (now - turn_started_at). Each actor arms a timeout for the side to move (a hashed timer wheel makes 100k timers cheap). If it fires first, the actor appends a terminal timeout event. Disconnects are irrelevant because the timer lives on the server. Optionally add an abandonment rule, such as aborting if a player never made a first move.
7. Failover
- Owners hold leases with a ~3 s TTL, renewed about every second.
- On crash the lease lapses; the coordinator reassigns the shard to a healthy server and bumps the epoch.
- The new owner loads each game by replaying its log (about 80 moves replay in microseconds; add periodic snapshots for very long games) and recomputes clocks from persisted timestamps.
- Timers are re-armed. Decide and document the policy for time lost during the outage: charge it, or refund it.
- Gateways watch ownership changes, reroute, and clients receive a fresh
STATE. Reconnecting clients sendlast_seen_plyand get only the missing moves.
Split brain: a partitioned old owner may still think it holds the lease. Its writes carry the old epoch, so the conditional write fails and it shuts itself down. Safety therefore rests on the storage fence, not on timing assumptions.
8. Spectators
Spectators never touch the match server. Committed moves flow through a change stream into a pub/sub system (Kafka or Redis Streams), and a separate fan-out tier pushes them over sockets. Key points:
- New viewers fetch a snapshot (position + ply) and then follow the stream from that ply.
- Popular games are served by many fan-out nodes, each subscribed once, so viewer count does not load the game owner.
- Optionally add a deliberate delay of some seconds for anti-cheating.
- Cache recent games in memory; archive finished games from the log.
9. Trade-offs and common mistakes
- Lease TTL: shorter means faster failover but more false takeovers under GC pauses; fencing makes false takeovers safe.
- Per-game versus per-shard leases: per-shard reduces coordination traffic at the cost of coarser reassignment.
- Mistake: trusting client timestamps or running a ticking counter on the client.
- Mistake: acknowledging a move before it is durable.
- Mistake: relying on the lease alone without a storage-level fence.
- Mistake: serving spectators from the game owner, letting a popular match slow the players.
- Mistake: ignoring idempotency, so a retried move after a timeout is rejected as illegal or applied twice.