Design an Online Chess Game – Frontend System Design

We’ll walk through the frontend system design for a live chess client like Chess.com or Lichess: a board you can drag, legal-move dots on pointerdown, two clocks that must not lie, and a reconnect that snaps to the correct ply. You’ll see why the browser generates legal moves and why that generation is never the source of truth, why a DOM board beats a canvas here, and how an animation may trail a server ply by one slide and no more.
This is not a chess-engine question. You are not asked to write alpha-beta. It is also not a chat app. Chat can drop a message and survive. A chess client that applies the wrong ply, or that flags a player the server has not flagged, has a broken game.
Problem Statement
Design the frontend for a real-time online chess game.
Requirements:
- Play rated and casual games at bullet, blitz, and rapid time controls
- Show legal-move hints and last-move highlights as soon as the pointer goes down
- Keep both clocks honest across lag, tab backgrounding, and reconnect
- Support premoves, draw offers, resign, and a spectator view
- Survive a dropped socket mid-game without inventing a result
- Animate pieces without letting the animation own the position
Describe the board, the move protocol, the clocks, and how a refresh mid-game restores the seat.
Interviewers are checking three things. Do you keep legality and the flag on the server? Can you explain why the client still runs a move generator? And do you know that a CSS transition and a numbered ply are two different clocks?
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Standard chess only, or variants? | Standard chess on day one. Chess960 can reuse the same ply protocol later. No bughouse, no crazyhouse. |
| 2 | Who is the authority for a move and a flag? | The server. The client may hint and interpolate. It never ends a rated game on its own. |
| 3 | Time controls? | Fischer clocks: initial time plus increment on each completed move. Bullet (1+0), blitz (3+2), rapid (10+0). Delay clocks are out of scope. |
| 4 | Premoves? | Yes. One armed premove, shown as a ghost. A queue of premoves is a later upgrade. |
| 5 | Spectators and broadcast delay? | Yes. Rated games feed spectators on a delay so a second device cannot coach. Casual games can be live. |
| 6 | Takebacks, analysis board, puzzles? | No. One live game, two seats, spectators. Analysis is a different product. |
| 7 | Auth and devices? | Signed-in players. One active seat per game. A second tab of the same user is a spectator of their own board, or it steals the seat after a confirm. |
| 8 | Browsers? | Evergreen desktop and mobile web. Pointer events, not hover-only UI. |
Question 2 splits the architecture. Question 3 tells you the clock is a server timestamp plus remaining milliseconds, not a setInterval(1000) in the tab. Question 5 is why a spectator client is the same renderer on a delayed ply cursor, not a second game object. Question 7 is how you avoid two tabs both sending a move for the same seat.
Requirements
Functional
- An 8×8 board that flips for Black, with coordinates, last-move highlight, check highlight, and a promotion picker.
- Legal-move dots on pointer down or square click. Illegal drops snap the piece home with no network call if the local engine already rejects them.
- A move that the local engine likes still goes to the server with the expected ply and a client move id.
- Two clocks, increment applied after a server-accepted ply. Low time shows tenths.
- Draw offer, decline, accept, and resign as their own messages, not fake moves.
- One premove the client holds and sends when a ply makes it your turn.
- Spectators see the same board read-only. Rated games may trail by a configured delay.
- A refresh or a dropped socket restores FEN, ply, clocks, and any open draw offer.
Non-Functional
- A local highlight appears on the same frame as pointerdown. A server round trip is too late for that.
- The board stays at 60fps while a piece slides. The model updates on the event, not on
transitionend. - Clock interpolation uses wall time. A background tab must not freeze a rated clock.
- A double-sent move with the same
clientMoveIdcreates one ply. - Reconnect from a snapshot in one round trip, then resume the socket from that ply. Do not replay the whole PGN as animation.
- The game is playable with a keyboard and a screen reader. Each square is a real control.
Architecture
Four client jobs, three server jobs. Keep them in different modules.
The board view is 64 squares and a layer of piece elements. It knows how to flip, drag, and announce. It does not know FIDE.
The legal-move engine is a small, well-tested library (think chess.js or a WASM port of the same rules). You feed it the current FEN. It returns the legal squares for a piece and whether a UCI string is legal in that position. It exists so the UI can reject a drag before the network, and so a premove can be dropped if the opponent’s ply made it illegal. It does not sign anything.
The game view-model is the store: ply, fen, clocks, status, your color, pending UCI, open draw offer. Every socket event is a reducer input. The board and the clocks are functions of this store plus a short animation queue.
The socket client holds lastPly, reconnects with backoff, and on a new process asks for a snapshot first. It is the only module that talks to the gateway.
On the server, the game engine validates UCI against the stored FEN and the seat. The clock authority subtracts elapsed server time from the ticking side and adds increment after an accepted ply. The match store appends the ply and fans it out. A spectator delay is a cursor, not a fork of the game.
A helper that “just applies the move locally because the engine said it was legal” is how you desync. A clock that flags in the browser is how you steal a win on a lag spike.
Data Model
The server owns the game. The client owns a premove and a pending drag.
type Color = "white" | "black";
type Uci = string; // e2e4, e7e8q
type GameStatus = "matching" | "playing" | "ended";
type EndReason =
| "checkmate"
| "stalemate"
| "resign"
| "flag"
| "agree"
| "repetition"
| "fifty"
| "insufficient"
| "abort";
interface Game {
id: string;
whiteId: string;
blackId: string;
rated: boolean;
time: { initialMs: number; incrementMs: number };
fen: string;
ply: number;
status: GameStatus;
result?: "1-0" | "0-1" | "1/2-1/2";
endReason?: EndReason;
}
interface Move {
gameId: string;
ply: number;
uci: Uci;
san: string;
fenAfter: string;
by: Color;
clientMoveId?: string;
clocks: ClockPair;
serverTs: number;
}
interface ClockPair {
whiteMs: number;
blackMs: number;
ticking: Color | "none";
serverNow: number;
}
Rules that keep this from rotting:
- Ply is the sequence number. White’s first move is ply 1. A client at ply 12 ignores a replay of 12 and buffers 14 until 13 lands. You do not merge FENs.
- UCI on the wire, SAN on the move list. UCI is from-square, to-square, optional promotion. SAN is for humans and the live region (“Knight to f3, check”).
- FEN is a snapshot, not a log. Reconnect is one read. After a snapshot you do not replay 40 plies to paint the board.
- Clocks travel with the ply. The client interpolates from the last
ClockPair. It does not keep its own remaining as source. - A premove is not a ply. It lives in the tab. Key it by
gameIdand drop it whenarmedAtPlyis stale. One open draw offer at a time; that rule lives on the server.
Board Rendering: DOM, Not Canvas
Chess has 64 squares and at most 32 pieces. That is a DOM-sized scene. A canvas is the wrong default, and saying “we’ll use canvas because games use canvas” is a junior tell. For a comparison with a real canvas product, see Design a Drawing Tool. Drawing tools have unbounded ink. A chessboard does not.
| Aspect | DOM (64 buttons + pieces) | Canvas / WebGL |
|---|---|---|
| Hit testing | Free. The square under the pointer is the event target. | You write it. Every promotion picker click is math. |
| Accessibility | Each square is a gridcell or a button. Keyboard just works. |
You rebuild a parallel a11y tree. Most teams never finish it. |
| Animation | CSS transform on one piece. The rest of the board does not repaint. | You redraw the frame. Fine at 32 sprites, wasted work. |
| Piece sets | SVG or PNG as <img> / CSS mask. Users can swap sets with CSS. |
A texture atlas and your own scaling. |
| When it wins | The product you are shipping. | A 3D board, or a lobby that paints a thousand mini-boards. |
The layout is a CSS grid. Pieces sit on a layer above, keyed by a stable piece id, not by square. A knight from e2 to f3 changes transform. Destroying the e2 node and creating an f3 node is how you lose the animation and confuse the accessibility tree.
Use pointer events, not HTML5 drag-and-drop. DnD is desktop-only and fights mobile scroll. On pointerdown you capture, lift the piece, and highlight. On pointerup you hit-test the square (the piece is pointer-events: none while dragging). Legal goes pending; illegal snaps home. Promotion is a chooser on the target file, shown before you send. e7e8 without a piece letter is not a move.
Flip is a class on the board. Pieces keep their orientation so a knight does not stand on its head. Do not rebuild 64 nodes. Black’s first paint is already flipped. Canvas is for a 3D skin or a thousand lobby thumbnails. If you start there you owe hit testing and a live region from scratch. Pick DOM.
Legal Moves Are a Hint
The local engine answers three UI questions: which squares light up, is this drop legal enough to send, and is the armed premove still legal after the opponent’s ply. That is the whole job.
Highlighting is one call into the engine: given the current FEN and the square the user picked up, list the legal moves from that square and keep their target squares. The board renders those as dots and rings. It is pure and fast enough to run on every pointerdown with no caching.
You still send. The server may reject because your FEN is a ply behind, the engine missed a pin, or the other tab stole the seat. The piece sits dimmed on the target until a PLY with your clientMoveId arrives, or a REJECT snaps it home.
Do not send illegal local drops. That is not security. It avoids a bounce (send, reject, snap) and keeps garbage off the gateway. A local reject never leaves the view. Castling, en passant, and promotion are where home-rolled engines lie; use a library. Threefold and fifty-move are server claims. The client may show “Claim draw”. The claim is a message, not a local result.
The Move Protocol
A move is a command with an expected ply. The response is an event with a new ply. Those are not the same object.
// client -> gateway
type MoveCommand = {
type: "MOVE";
gameId: string;
ply: number; // the ply we believe is current
uci: Uci;
clientMoveId: string; // uuid minted on drop
};
// gateway -> both seats (and the delay feed)
type GameEvent =
| { type: "PLY"; move: Move }
| { type: "REJECT"; clientMoveId: string; reason: RejectReason }
| { type: "CLOCK"; clocks: ClockPair }
| { type: "DRAW"; offer: DrawOffer }
| { type: "ENDED"; result: Game["result"]; reason: EndReason; clocks: ClockPair };
type RejectReason = "illegal" | "stale_ply" | "not_your_turn" | "not_your_seat" | "ended";
Why this shape:
plyon the command is a compare-and-set. Server already at 13 and you send “moving on 12” isstale_ply, not a second e2e4. Two tabs cannot both land a move this way.clientMoveIdmakes the send idempotent. A retry after a dropped ack with the same id returns the same ply. A new drop mints a new id.- The pending piece is view state. The reducer does not change
fenorplyon send. If you optimistic-apply, a reject must invert a capture, a castle, and an en passant. That inverter is how clients desync. - Both seats apply the same
PLY. The mover commits pending. The opponent queues an animation. One event, three views.
Use a WebSocket per game room. HTTP POST per move adds a handshake to bullet. Long polling is the fallback if a proxy kills sockets, not the happy path. Same event types either way.
Clocks
The server owns remaining time. The client paints a number that is allowed to be a few tens of milliseconds off. A flag is an ENDED event, not a local if (ms <= 0).
The displayed time is a pure function of the last ClockPair, a color, and the current server-corrected time. If that color’s clock is not ticking, show its stored remaining time. If it is, subtract the time elapsed since serverNow, never going below zero. Nothing is stored or decremented. The label is recomputed from timestamps every time it paints.
On each ClockPair store localNow = performance.now() next to serverNow. Each frame, now = serverNow + (performance.now() - localNow). That cancels device-versus-server skew for the interpolation window. Re-sync on every ply, because increment and the hit happen there.
Do not tick with setInterval(1000). Intervals drift and bunch in background tabs. Use rAF while visible, and a timeout aligned to the next second (or tenth under ten seconds) to update the label. Remaining time is a function of timestamps, not a decrementing integer you must visit every frame.
A background tab on a rated game does not pause the clock. Casual pause-on-disconnect is a server flag. Showing 0:00 is a hint. Taking the win is cheating the protocol. Increment is applied on the server after the ply is accepted. Do not add it locally on send; a reject would have given free time. Low-time sounds need a user gesture. Fail quiet if the browser blocks them.
Game States
The status the server writes is small: matching, playing, ended. Draw-offered and reconnecting are overlays. If you put them in the same enum, you cannot offer a draw while a socket is retrying, which is a real position.
type Overlay =
| { kind: "none" }
| { kind: "draw"; by: Color }
| { kind: "promotion"; from: Square; to: Square }
| { kind: "reconnect"; since: number };
type ClientGame = {
game: Game;
clocks: ClockPair;
overlay: Overlay;
pending?: { uci: Uci; clientMoveId: string };
premove?: Premove;
role: Color | "spectator";
};
Checkmate and stalemate come from the engine after a ply. Flag comes from the clock authority, possibly with no ply at all. Resign and agree are commands. Repetition and fifty-move are server claims. Abort is “no real game happened.” Insufficient material is a server check after a capture. The client may disable Draw when the position is dead; the result still arrives as ENDED.
Resign is idempotent on clientMoveId. Do not flip the result on click. A race with a mate ply resolves on the server: whichever event landed first wins. The client that clicked Resign while mate was in flight shows the mate if that is what the server stored.
Animation Versus Server Ply
This is the part that looks like polish and is actually consistency.
The model applies a PLY the moment the event is reduced. fen, ply, clocks, and the move list update before the next paint. Hints and premove checks read that model. If you wait for transitionend to update FEN, a bullet opponent will send the next move while your knight is still sliding, and you will hint a dead position.
The view may trail. A queue holds { pieceId, from, to, captureId }. Play one job, 160–200ms, CSS transform; prefers-reduced-motion is 0ms. A second ply during the slide enqueues. A third drops the queue and snaps to the latest FEN. Two queued slides in bullet is a slideshow behind the position you are allowed to move from.
Also snap on reconnect, on document.hidden, on REJECT, and when a spectator cursor jumps. Captures hide the taken piece by captureId. Castling is two jobs in one ply. En passant removes a piece that is not on the to-square. If the job cannot express that, snap. The mover’s pending piece is already on the target; the matching PLY commits it with no second slide. The opponent is the one who animates.
Premoves
A premove is a local intention: “when it becomes my turn, send this UCI if it is still legal.” You paint a ghost piece on the target and a faded origin. You do not touch the engine’s position. You do not send until a PLY arrives whose fenAfter has you to move.
Premove handling runs inside the ply reducer. After applying an incoming ply, a spectator stops there. For a player, if the new FEN says it is their turn and a premove is armed, check it against the engine on the new position. If it is still legal, send it as a normal move (new clientMoveId, pending piece) in the same reduction, so there is no frame where the premove sits idle on the player’s turn. If it is now illegal, clear it and show a short toast.
Promotion premoves choose the piece up front. A castle through a now-attacked square dies. A capture of a piece that left dies. Toast and drop it if the local engine already knows; still handle REJECT. Cancel on Escape, a second click on the origin, or a new drag. Persist at most in sessionStorage with armedAtPly. Restoring a premove from a finished game is a bug. One premove is enough. A queue is the same machine with an array; mention it, do not build it unless asked.
Reconnect
A new JavaScript process knows nothing. Memory of the last FEN is gone. IndexedDB can hold a hint so the first paint is not an empty board, but the authority is a snapshot.
// GET /games/:id/snapshot
interface Snapshot {
game: Game;
clocks: ClockPair;
lastMoves: Move[]; // last ~20 for the move list; full PGN on demand
draw?: DrawOffer;
yourSeat?: Color;
serverNow: number;
}
// then subscribe
// WS /games/:id/stream?fromPly=24
Paint from cache if you have it, fetch the snapshot, replace the store, snap the board, open the socket from fromPly = snapshot.game.ply. Events at or below that ply are ignored. Ply numbers make a snapshot-versus-live race idempotent. Do not replay from move one. They need the current position and the clocks, now.
A dropped socket sets the reconnect overlay. Queue the send or POST the same MOVE. The clock keeps interpolating. You do not freeze it. If the drop lasts long enough to flag, the next snapshot is ENDED. After a long drop, snapshot-then-socket beats draining twenty missed slides. Backoff 200ms, 1s, 3s, 5s, cap.
Two tabs: the seat lock wins. The second is a spectator of the same game, or it POSTs a steal and the loser gets not_your_seat. Without this both tabs arm premoves and you debug ghosts.
Draw Offers, Resign, Abort
These are commands, not UCI: OFFER_DRAW, DECIDE_DRAW, RESIGN, each with the current ply. An offer paints Accept / Decline on the other seat. The game is still playing. Clocks still run. A ply can land while the banner is up; whether the offer expires on move is a server rule, not both rules. Accept becomes ENDED with agree. Decline clears the overlay. Resign kills the offer. Abort is a server decision in the first seconds with almost no play; hide the control once the snapshot says it is illegal.
Spectators
A spectator is the same view-model with role: "spectator". No send path, no premove. Flip follows a color or a toggle. Rated games use a delay cursor (or a delayed room) so a second device cannot coach. The live room never sees spectator sockets. Casual and finished games skip the delay. A finished game is a snapshot; do not keep a socket open for yesterday’s mate. Chat, if you add it, is the chat client and must not share the game reducer.
State and Data Flow
One store per gameId. The board reads pieces, highlights, pending, ghost, check, flip. Clocks read ClockPair and tick with rAF; they do not re-render the board. The move list appends SAN. Overlays read overlay and status.
The board mounts once. Pieces reconcile by id. Recreating 32 images on every ply hitches. A thin layer patches transforms; React is fine for the chrome. The live region speaks SAN and check, not every clock tenth. The URL is /game/:id. FEN in the query string is an analysis share trick, not the live seat.
API
| Method | Path | Purpose |
|---|---|---|
| POST | /matches |
Seek or accept a seek. Returns gameId when seated. |
| GET | /games/:id/snapshot |
Game, clocks, recent moves, draw, your seat. |
| GET | /games/:id/pgn |
Full history for the move list or a download. |
| WS | /games/:id/stream?fromPly= |
Live events after that ply. Heartbeats with serverNow. |
| WS / POST | MOVE, OFFER_DRAW, DECIDE_DRAW, RESIGN |
Commands. POST is the fallback when the socket is down. |
| POST | /games/:id/seat |
Steal the seat from your other tab. |
| WS | /games/:id/watch?delay= |
Spectator feed. Server enforces minimum delay on rated. |
Heartbeats carry serverNow and ClockPair with no ply. That is how a flag is detected while both players stare. The client replaces clocks and does not animate. Auth is a short-lived ticket from the snapshot endpoint. A spectator ticket cannot MOVE.
Optimizations
- Warm the piece set and the engine on the seek page so first paint does not wait on 32 SVGs.
- Legal-move queries are tiny. A sync JS library is fine. An analysis engine later is a worker. Do not block pointerup.
- Memoize highlights per FEN plus from-square. Send UCI, SAN, FEN, clocks. FEN is 90 bytes, not a 64-cell matrix.
- Virtualize the lobby, not the board. Prefetch the snapshot when a seek is about to pair.
Handling Edge Cases
- Promotion race. A snapshot that says ended, or an opponent ply, closes the picker. Do not send a promotion for a ply that is gone.
- Flip. Legal squares are board coordinates. Convert pointer-to-square after flip.
- Threefold the client sees and the server does not. Never auto-end. Show “Claim draw.”
- Lag on your send. Pending stays. An opponent
PLYwhile you are pending means you lost the race: clear pending, apply their ply, snap home. - Opponent ply and your premove in the same tick. Apply the ply first, then test the premove on the new FEN.
- Clock already 0 on snapshot. Paint 0:00. Wait for
ENDED. - Piece set fails. Fall back to letters. An empty queen square is unplayable.
- Safari pointer capture. If capture fails, listen on
window.touch-action: noneonly on the board. Recompute square rects on rotate.
Accessibility and Security
Accessibility
- The board is a
role="grid"of 64gridcells named “e2, white pawn” or “e4, empty.” The live region speaks SAN after a move, not the cell names twice. - Arrows move a focus ring, Enter picks up or drops, Escape cancels. The promotion chooser is a modal listbox.
- Clocks are
aria-live="off". Tenths in a live region drown the moves.prefers-reduced-motionsnaps.
Security
- Commands are authenticated as a seat. A spectator ticket cannot
MOVE. Do not trust a clientcolorfield. - The local engine is not a security boundary. The server validates FIDE rules, turn, and ply.
- Rated delay is anti-cheat. Do not honor a
live=1query on rated games. Chat and annotated PGN are untrusted text. Bots belong on the server, not in the hint worker.
What a Strong Answer Sounds Like
| Topic | Junior answer | Senior answer |
|---|---|---|
| Board | A canvas, because it is a game | DOM grid and CSS pieces; canvas only for 3D or a thousand thumbnails |
| Legal moves | Generate on the client and apply | Generate for dots and drag filters; commit only on a numbered server ply |
| Clocks | setInterval minus one second |
Interpolate remainingMs from serverNow; only the server flags |
| Animation | Move the piece, then update state | Update ply first; the view trails by one slide and snaps when behind |
| Reconnect | Replay every move from the PGN | Snapshot, snap the board, subscribe from that ply |
For the socket and room shape, the same seat-versus-spectator split shows up in Design Zoom. For a document that is also an append-only log with a snapshot, see Design Google Docs. Chess is stricter than both: there is one legal next position, not a CRDT.
Conclusion: How to Design an Online Chess Game
Start with the ply. The server numbers it, validates it, and hangs clocks and a result on it. The client paints a DOM board, generates legal squares so a drag feels instant, and holds a pending piece until that number arrives. If you cannot explain why a local engine is not an authority, you are not done.
Then separate the three clocks in the product. The server clock flags. The interpolator paints. The CSS transition is allowed to trail by one ply and must snap on reconnect, on a hidden tab, and when the queue grows. Premoves and draw offers are local or social state sitting on top of playing, not extra values in the result enum.
If you can walk through a reject after a stale ply, a flag while the tab is backgrounded, and a refresh that snaps to ply 24 with the right remaining time, you have the design. Everything else is a piece set.
