← Upstart

Upstart System DesignDesignFree previewFree

Online Chess Platform

Last asked

onsiteSWE

Problem

Design a real-time online chess platform using PostgreSQL, Redis Pub/Sub, and WebSockets.

Users can create games, join through invite links or matchmaking, play timed chess, reconnect, and review game history. The server validates moves, enforces turns and clocks, and handles checkmate, draws, resignations, and timeouts.

Use PostgreSQL as the source of truth with exactly these tables:

TablePurpose
accountsUser accounts and player identity.
gamesGame ID, participants, settings, invite token/link, status, and current_version.
game_metadataImmutable full game snapshots, uniquely keyed by (game_id, version).

  • Full snapshots: Persist and send complete game snapshots rather than deltas. Include the board, side to move, clocks and timing reference, outcome, and rule/history information needed to resume and validate play.
  • Version as nonce: Maintain a monotonically increasing version per game. Clients submit their observed version as expected_version, acting as a concurrency nonce. Each accepted state change increments the version. Reject stale or duplicate actions without reapplying them and return the latest snapshot.
  • Atomic updates: In one PostgreSQL transaction, lock the games row with SELECT … FOR UPDATE, verify the expected version, validate the action, insert the next snapshot into game_metadata, and update games.current_version and any changed status. Snapshot insertion and current-version advancement must succeed or roll back together. Moves, resignations, and timeouts use the same locking path.
  • Client communication: Use authenticated WebSockets for actions and updates. Publish committed updates through Redis Pub/Sub to WebSocket servers, which broadcast full snapshots to players. Redis supports caching and ephemeral coordination; PostgreSQL remains authoritative.
  • Recovery: Clients apply only newer snapshots and fetch the latest committed snapshot when reconnecting. Handle missed Pub/Sub messages, crashes between commit and publication, duplicate requests, and server failures. Keep clocks authoritative across disconnects.

Discussion

Explain the core services, APIs and WebSocket messages, move-processing flow, matchmaking, and scaling across concurrent games. State capacity assumptions and key consistency tradeoffs.