The Problem#
We want to build an online chess site like Chess.com or Lichess. A player presses "Play 3 minutes", is paired within a few seconds with someone of similar skill, and plays a fast game in which every move appears on the opponent's screen almost instantly and each player's clock ticks only on their own turn. When the game ends, both ratings change, the leaderboard updates, the game is saved forever, and thousands of other people may have been watching live.
Think of a chess club that runs a tournament hall. An organiser at the door pairs people of similar strength. At each table an arbiter watches the board, refuses illegal moves, and controls a chess clock that both players trust. When a game ends, a scorekeeper writes the result in the club book and updates everyone's rating on the wall chart. Spectators stand behind the tables and watch. Our system is that club, run by software, for millions of people at once:
- the organiser is the matchmaking service;
- each arbiter is a game server that owns the official board and clocks for a game;
- the scorekeeper is the game archive and rating service;
- the wall chart is the leaderboard;
- the people behind the tables are spectators, served by a broadcast system.
Chess looks simple next to video or maps. Each move is a few bytes and each game is two people. The hard parts are elsewhere:
- Time is part of the game. In a 3-minute game, 100 ms of network delay on every move adds up to several seconds over a game. The server must keep clocks that are fair to a player on a slow mobile network in one country and a player on fibre in another.
- The server must be the authority. A client could claim an illegal move, claim it has more time, or claim the opponent ran out of time. Only the server can decide.
- Contention at pairing time. Many players wait at once, and each must be put into exactly one game. Pairing one person into two games is a visible, embarrassing bug.
- Scale with bursts. Chess.com reported over 31 million games on a single day in January 2023 and more than a million games an hour, after traffic nearly doubled in about seven weeks.
- Cheating. A player can secretly copy moves from a chess engine. The system must detect this from the moves themselves.
Background: a few terms used in this design#
- Ply. One move by one side. "Move 20" in chess notation is two plies (white's and black's). We count plies, because the server processes one ply at a time.
- Time control. How much time each player has. "3+0" means 3 minutes each with no extra time per move. "3+2" adds a 2-second increment after each move. Common groups are bullet (under 3 minutes), blitz (3–10 minutes), rapid (10–30 minutes), classical (longer) and daily or correspondence chess (days per move).
- Flagging. Losing because your clock reached zero ("your flag fell").
- Premove. Entering your next move before the opponent has moved. It is played the instant their move arrives, which matters in bullet.
- FEN (Forsyth–Edwards Notation). One line of text that describes a position: piece placement, side to move, castling rights, en passant square and move counters. Example:
rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1. - PGN (Portable Game Notation). The standard text format for a whole game: tags (players, result, date, time control) followed by the moves.
- SAN and UCI moves. SAN is the human notation (
Nf3,exd5,O-O). UCI notation is the machine form, from-square to to-square (g1f3,e1g1,e7e8qfor a promotion). Servers use the UCI form on the wire because it is easy to parse and check. - Elo and Glicko. Rating systems. Elo gives each player one number. Glicko adds a rating deviation (RD), how uncertain that number is; Glicko-2 adds volatility, how erratic a player's results are.
- Engine. A chess program such as Stockfish. Engines are far stronger than any human, which is why using one during a game is the main form of cheating.
- Abort. Ending a game before it really starts (for example, a player never makes a first move). Aborted games are not rated.
Clarifying Questions#
| Question | Assumed answer |
|---|---|
| Which time controls? | Bullet, blitz and rapid live games, with and without increment. Daily chess is a separate, simpler flow (Deep Dive 12 notes the differences). We design the core for 3+0 blitz and generalise. |
| How many players? | Design for 15 M daily active players, 40 M games per day and 500,000 concurrent games at peak (1 M player connections), with headroom for 2× bursts. |
| Rated and casual games? | Both. Ratings are kept per time-control group ("rating pool"): bullet, blitz, rapid. |
| How should pairing work? | By rating within the same pool and time control, widening the allowed rating gap the longer a player waits. Also direct challenges to a friend. |
| Can anonymous users play? | Yes for casual games; rated games need an account. |
| Do we need spectators? | Yes. Anyone can watch a live game; top games may have tens of thousands of viewers. |
| Do we keep every game? | Yes, permanently, with replay, PGN download and per-player history. |
| Leaderboards? | A global leaderboard per pool and each player's rank, updated shortly after games end. |
| Mobile and web? | Both. Mobile networks with high and variable latency are common. |
| Chat during games? | Basic chat between players, with an option to disable. Not a focus. |
| Anti-cheat? | Basic detection of engine use and abuse; deep fair-play investigations are a separate team's workflow, but our design must supply the data. |
| Tournaments, puzzles, lessons? | Out of scope for the core design; mentioned where they affect it. |
Requirements#
Functional requirements#
- Matchmaking: a player chooses a time control and is paired with an opponent of similar rating within seconds, or challenges a specific person.
- Real-time play: moves are validated by the server and delivered to the opponent in real time; the game handles resign, draw offers, draws by rule (repetition, 50-move rule, insufficient material), checkmate, stalemate and timeouts.
- Clocks: each player's clock runs only on their turn, increments are applied, and the server decides when time runs out.
- Ratings: rated games update both players' ratings right after the game ends.
- Leaderboard: players can see the global leaderboard for each pool and their own rank, updated within seconds of a game ending.
- Persistence and replay: every finished game is stored and can be replayed, downloaded and searched by player.
- Spectating: others can watch live games, including very popular ones.
- Reconnection: a player who loses connection can come back to the game with the correct position and clocks.
- Fair play: suspicious games are flagged for review; cheaters can be banned and their opponents' ratings restored.
Non-functional requirements#
- Low move latency. The server should process a move in under 10 ms; end-to-end delivery to the opponent should be under 100–150 ms for most players (network-bound).
- Correctness. No move may be lost or applied twice. Only legal moves are accepted. The clock decision is the server's and is the same no matter which server runs the game.
- Fairness. One player is never in two games at once. Network delay should not decide games: a player on a slow link should not lose seconds every move.
- Availability. 99.95% or better for play. A single server failure should not end games in progress; at worst a short pause.
- Scale. 500,000 concurrent games and 1 M player WebSocket connections at peak, plus spectators; tens of thousands of moves per second.
- Durability. Finished games are kept forever; games in progress survive a server crash.
- Consistency of ratings. Each rated game changes ratings exactly once. The leaderboard may lag by a few seconds.
Capacity Estimation#
We use the method from Back-of-the-Envelope Estimation. The anchor is real: in January 2023 Chess.com reported 10 million active members in one day, 31.7 million games on its busiest day, regularly more than one million games an hour, and an average of 16,000 moves per second. We design a little above that.
Games and concurrency.
- 40 M games per day. Many are short: aborted games, quick resignations and bullet. Assume an average game lasts 6 minutes.
- Game-minutes per day: 40 M × 6 = 240 M. Spread over 1,440 minutes, that is about 170,000 concurrent games on average.
- Peaks run about 3× the average (evenings in Europe and the Americas overlap), so 500,000 concurrent games at peak and 1 M player connections.
- New games start at 40 M / 86,400 ≈ 460 per second on average, and about 1,500 per second at peak.
Moves.
- Chess.com's figures imply about 16,000 / (31.7 M / 86,400) ≈ 44 plies per game on average, which fits a mix of short and long games. Use 45.
- 40 M × 45 = 1.8 B plies per day, about 21,000 moves per second on average and about 65,000 per second at peak.
- Each move causes: one validation, one clock update, one message to the opponent, one acknowledgement to the mover, one append to the move log, and one message per spectator.
Connections and messages.
- 1 M player WebSockets plus, say, 500,000 spectator connections at peak.
- Heartbeats every 3–5 seconds for lag measurement (fast games need fresh latency numbers): 1.5 M / 4 ≈ 375,000 small messages per second. This is more than the moves themselves.
- Move fan-out: 65,000 moves per second × (2 players + an average of 1 spectator) ≈ 200,000 deliveries per second, but a few top games have tens of thousands of viewers (Deep Dive 8).
Matchmaking.
- 1,500 pairings per second at peak means 3,000 players leave the queue per second. If the average wait is 3 seconds, about 9,000 players are waiting at any moment, spread across perhaps 10–20 pools (time control × rated or casual). The biggest pool (3-minute blitz) might hold 3,000 waiting players.
Ratings and leaderboard.
- Rated games are about 80% of the total: 32 M per day, 1,200 per second at peak, so 2,400 rating updates per second.
- Leaderboards: perhaps 30 M rated players in the blitz pool, with leaderboard and rank reads of a few thousand per second (profile pages, post-game screens).
Storage.
- A compact game record: about 45 plies × (1–2 bytes for the move + 2 bytes for the clock reading) ≈ 150 bytes, plus about 250 bytes of metadata (players, ratings, time control, result, timestamps). Call it 400 bytes per game.
- 40 M × 400 B = 16 GB per day, about 6 TB per year before replication. Even 20 billion stored games (Lichess says it stores more than 12 billion) is only about 8 TB of compact game data. Indexes, analysis and PGN exports add several times more.
- Moves in flight: each live game needs a few KB of memory (position, move list, clocks, player info); 500,000 × 4 KB = 2 GB. Live state is small.
Bandwidth.
- A move message is about 100–200 bytes with framing. 200,000 deliveries per second × 200 B = 40 MB/s, about 0.3 Gbps. Heartbeats add a similar amount. Bandwidth is not the constraint; connection count, per-message CPU and latency are.
| Quantity | Average | Peak |
|---|---|---|
| Concurrent games | 170,000 | 500,000 |
| Player connections | 340,000 | 1 M (+0.5 M spectators) |
| Games started per second | 460 | 1,500 |
| Moves per second | 21,000 | 65,000 |
| Rating updates per second | 750 | 2,400 |
| New game data per day | 16 GB | — |
Core Entities#
- Player: account, profile, settings, country, flags (closed for fair play, titled).
- Rating: one per player per pool (bullet, blitz, rapid): rating, deviation, volatility, games played, last game time.
- Seek: a request to play: player, pool, time control, rated or casual, rating window, created time. Lives only while the player waits.
- Game: id, white and black players, time control, rated flag, ratings before and after, status (created, started, finished, aborted), result and reason, start and end times, server that owns it.
- Move: game id, ply number, move in UCI form, the mover's clock after the move, server timestamp.
- Spectator subscription: a connection watching a game (transient).
- Fair-play report: a game or player flagged by automated checks or by users, with scores and a review status.
API Design#
Matchmaking, history and leaderboards use REST. Play and spectating use a WebSocket connection per client (see Polling, Long Polling, SSE, WebSockets and Webhooks).
POST /v1/seeks {pool: "blitz", time: 180, inc: 0, rated: true}
-> 202 {seek_id} (pairing result arrives on the WebSocket)
DELETE /v1/seeks/{seek_id} cancel waiting
POST /v1/challenges {opponent: "magnus_fan", time: 300, inc: 3, color: "random"}
GET /v1/games/{game_id} -> game record (players, moves, clocks, result)
GET /v1/games/{game_id}.pgn -> PGN text
GET /v1/players/{id}/games?cursor= -> recent games, newest first
GET /v1/leaderboards/{pool}?offset=0&limit=50
GET /v1/players/{id}/rank?pool=blitz -> {rating, rank, percentile}WebSocket messages (JSON shown for readability; production may use a compact binary form):
// client -> server: make a move; ply makes it idempotent
{"t": "move", "game": "g_8f2", "ply": 23, "uci": "e7e5", "lag_ms": 42}
// server -> both players: the accepted move with authoritative clocks
{"t": "move", "game": "g_8f2", "ply": 23, "uci": "e7e5", "san": "e5",
"clock": {"white_ms": 151230, "black_ms": 143870}, "status": "started"}
// server -> client: pairing done
{"t": "game_start", "game": "g_8f2", "color": "black", "opponent": {"id": "p_19", "rating": 1612},
"time": 180, "inc": 0}
// client -> server: other actions
{"t": "resign", "game": "g_8f2"}
{"t": "draw_offer", "game": "g_8f2"}
{"t": "resync", "game": "g_8f2", "last_ply": 21}
// server -> client: end of game
{"t": "end", "game": "g_8f2", "result": "0-1", "reason": "timeout",
"rating": {"white": [1604, -6], "black": [1612, 6]}}
// heartbeat for lag measurement, every few seconds
{"t": "ping", "id": 9912} -> {"t": "pong", "id": 9912}Design notes:
plymakes moves idempotent. If the client resends ply 23 after a reconnect, the server sees that ply 23 is already applied and replies with the current state instead of applying it twice. A move for the wrong ply (the opponent's turn, or a stale position) is rejected.- The server sends clocks, not the client. The client displays its own countdown between messages, but each server message carries the authoritative clock values, and the client resets to them.
lag_msis the client's measured round-trip estimate, which the server may use, within limits, for lag compensation (Deep Dive 5).
High-Level Design#
We build the design one requirement at a time, then combine everything into the full picture.
1) Find an opponent and start a game#
The player's client sends a seek. The matchmaking service keeps a waiting pool per time control and rated flag. A matcher repeatedly scans the pool for pairs whose ratings are close enough, atomically removes both players from the pool, and asks the game service to create a game. The game is assigned to a game server, and both players are told the game id and their colours over their WebSocket connections.
Two things need care: one player must never be removed from the pool into two games at once (Deep Dive 2), and the window of acceptable rating gap must widen with waiting time so that nobody waits forever (Deep Dive 1).
2) Play the game in real time#
Each live game has exactly one owner: a game server process that holds the board, the move list and both clocks in memory. Every move goes to that owner, which checks legality, updates the clocks, appends the move to a durable log, and pushes the result to both players and any spectators.
Clients do not connect to the game server directly. They connect to WebSocket gateways, which hold the connections and route messages to the right game server by game id. This split lets us scale and deploy connection handling separately from game logic. Lichess uses this split: its README says WebSocket connections are handled by a separate server (lila-ws) that talks to the main application through Redis.
3) Keep the clocks#
The game server is the clock authority. When it applies a move at server time t, it subtracts the time since the previous move from the mover's clock, adds any increment, and starts the opponent's clock. It also sets a timer for the moment the opponent's clock would reach zero; if no move arrives first, the server ends the game on time. Clients show a local countdown for smoothness, but they reset to the server's values with every message. Deep Dive 5 covers lag compensation.
4) End the game, save it and update ratings#
When the game ends (checkmate, resignation, timeout, draw or abort), the game server writes the final record to the games database and emits a game_finished event to a log such as Kafka. The rating service consumes the event, computes the new ratings for both players in one transaction keyed by game id (so the update happens exactly once), and emits a rating_changed event. Players see their new rating within a second because the game server can compute a preview immediately; the rating service makes it official.
5) Leaderboards#
The leaderboard service consumes rating_changed events and updates a sorted structure per pool, for example a Redis sorted set where the score is the rating. Reads of the top 50 and of "my rank" come from it in a millisecond. Deep Dive 7 covers correctness and scale.
6) Spectators#
A spectator subscribes to a game through the gateway. The game server publishes each move to a pub/sub channel for the game, and gateways that have spectators for that game forward the move to them. For very popular games, a fan-out tree or a separate broadcast tier serves the crowd, often with a short delay (Deep Dive 8).
7) Reconnection#
If a player's connection drops, the game continues on the server and their clock keeps running. The client reconnects to any gateway, sends resync with the last ply it knows, and gets the missing moves and the current clocks. If the player stays away too long, the opponent may claim the win (Deep Dive 10).
8) History, replays and analysis#
Finished games are read from the games database (recent games, a player's history) and from an archive for older games. A replay is just the move list played forward on the client. Computer analysis runs on an analysis cluster of engine workers, which is also the backbone of fair-play checks (Deep Dive 11).
The full high-level design#
Components:
- Load balancer and WebSocket gateways: terminate TLS, hold player and spectator connections, authenticate, measure latency with heartbeats, and route messages by game id to the owning game server.
- REST API service: seeks, challenges, profiles, game history, leaderboards; stateless and horizontally scaled.
- Matchmaking service: waiting pools per time control; pairs players by rating, removes them atomically, and requests a game.
- Game service and placement: creates game records, picks a game server (by consistent hashing of the game id or by least load), and tracks which server owns which game.
- Game servers: hold live games in memory, validate moves, run clocks and timers, detect the end of the game, and write moves to the durable move log.
- Pub/sub and move log: deliver moves from game servers to gateways for spectators, and keep a durable record of each move so a game can be recovered after a crash (Redis streams, Kafka or a replicated in-memory log).
- Event log, rating service and leaderboard service: turn finished games into rating changes exactly once, and keep per-pool leaderboards up to date.
- Fair-play pipeline and analysis cluster: run engines over finished games, compute suspicion scores, and feed a human review queue.
- Databases and archive: players and ratings (relational), games (a large, partitioned store), and cold archives and public PGN exports in object storage.
Key Flows#
Flow 1: a player seeks a game and is paired#
The matcher removes both players in one atomic step before the game exists. If the game creation then fails, both players are put back at the front of the pool.
Flow 2: a move and its clocks#
The append to the move log happens before the move is sent out, so a move that anyone has seen is never lost if the game server crashes. A local append to an in-memory replicated log takes under 1–2 ms, so this costs little.
Flow 3: a player disconnects and comes back#
The black clock kept running during the outage. That is fair: the server cannot know whether the player was really disconnected or was thinking. Deep Dive 10 covers how long to wait before the opponent can claim the game.
Flow 4: a game ends on time and ratings update#
If black has only a king left, a white timeout is a draw, not a loss, because black could not possibly win. The game server applies these rules (Deep Dive 3).
Flow 5: thousands of people watch a top game#
Flow 6: a finished game is checked for engine use#
Data Model#
The player and rating data is relational and needs transactions (one rated game updates two rating rows together). Games are append-only, huge in number and accessed by id or by player and time, so they suit a partitioned store. Live game state lives in memory on the game server, backed by a durable move log.
Moves and fair-play data hang off each game:
The rating update is a transaction over two rows, guarded by a table of games already rated:
CREATE TABLE rating (
player_id BIGINT NOT NULL,
pool TEXT NOT NULL, -- 'bullet', 'blitz', 'rapid'
rating REAL NOT NULL DEFAULT 1500,
deviation REAL NOT NULL DEFAULT 350,
volatility REAL NOT NULL DEFAULT 0.06,
games INT NOT NULL DEFAULT 0,
last_game_at TIMESTAMPTZ,
PRIMARY KEY (player_id, pool)
);
CREATE TABLE rated_game (game_id BIGINT PRIMARY KEY, rated_at TIMESTAMPTZ NOT NULL);
BEGIN;
INSERT INTO rated_game VALUES (:game_id, now()); -- fails if already rated
SELECT * FROM rating WHERE (player_id, pool) IN ((:w, 'blitz'), (:b, 'blitz'))
ORDER BY player_id FOR UPDATE; -- fixed order avoids deadlocks
UPDATE rating SET rating = :w_new, deviation = :w_rd, volatility = :w_vol,
games = games + 1, last_game_at = now() WHERE player_id = :w AND pool = 'blitz';
UPDATE rating SET rating = :b_new, deviation = :b_rd, volatility = :b_vol,
games = games + 1, last_game_at = now() WHERE player_id = :b AND pool = 'blitz';
COMMIT;Finished games go to a store partitioned by game id, with a second table (or index) for each player's history:
-- Cassandra-style CQL for history by player
CREATE TABLE games_by_player (
player_id bigint,
started_at timestamp,
game_id bigint,
opponent bigint,
color text,
result text,
pool text,
PRIMARY KEY ((player_id), started_at, game_id)
) WITH CLUSTERING ORDER BY (started_at DESC, game_id DESC);| Data | Store | Why |
|---|---|---|
| Players, ratings, accounts | PostgreSQL or MySQL, sharded by player id when large | Transactions across two rating rows, strong consistency |
| Live game state | Game server memory | Microsecond access, single owner |
| Move log for live games | Redis streams with replication, or Kafka | Durable append per move, replay on failover |
| Finished games | MongoDB, Cassandra or a sharded relational store, keyed by game id | Billions of immutable records, simple key access |
| Games by player | Wide-column table or secondary index | "My last 50 games" in one partition read |
| Waiting pools | Matchmaker memory or Redis sorted sets | Fast range queries by rating, short-lived data |
| Leaderboards | Redis sorted sets per pool | Rank and top-N in O(log N) |
| Game search | Elasticsearch | Search by player, opening, result, date |
| Event log | Kafka | Game finished and rating changed events, replayable |
| Archive and PGN dumps | Object storage | Cheap, permanent, bulk downloads |
For a general method of matching access patterns to stores, see Choosing a Database: A Decision Guide. Lichess's README notes that it uses MongoDB to store more than 12 billion games, indexed by Elasticsearch, which is one real example of this split.
Deep Dives#
1. Matchmaking by rating#
Goal. Pair two players quickly with a small rating gap. These goals pull against each other: the smaller the allowed gap, the longer people wait. A good matcher makes the trade-off explicit and adapts it per pool and per time of day.
Pools. Players only match others who want the same thing: same time control (3+0 is not 3+2), same rated flag, same variant. Each combination is a separate pool. Popular pools (3+0, 1+0, 10+0) have thousands of waiting players at peak; rare ones (say 2+1 Chess960) may have a handful, and need wider windows.
The widening window. Each seek has an acceptable rating range that grows with waiting time:
window(t) = base + growth * t e.g. base = 50, growth = 25 per second
capped at max_window e.g. 400 for rated, unlimited for casual
match(a, b) if |r_a - r_b| <= min(window_a(t_a), window_b(t_b))- With 3,000 players waiting in a pool, ratings are dense: most players find someone within 50 points in under a second.
- At 3 a.m. in a small pool, the window grows until a match appears. Using the minimum of the two windows respects both players' limits; some sites let a player set their own range ("only opponents within ±100").
- A player with a high deviation (new, uncertain rating) can safely use a wider window: their true strength is unknown anyway, and the rating system learns more from varied opponents.
Which pair to pick. A greedy matcher sorts waiting players by rating and pairs neighbours whose gap fits. That is simple and very effective. Two refinements:
- Prefer whoever has waited longest. Scan seeks in order of waiting time, and for each, find the closest-rated eligible partner. This keeps the tail of waiting times short.
- Batch matching. Instead of matching on every new seek, run the matcher every 100–250 ms over the whole pool. Batching gives better pairs (more choices at once) for a small added wait, and makes the matcher's work predictable. One pass over 3,000 sorted entries takes well under a millisecond.
Other constraints.
- Colour balance: give white to whoever had black more often recently.
- Avoid immediate rematches with the same opponent in automatic pairing (it can be abused to farm rating with a friend), unless both ask for a rematch.
- Network quality: in bullet, pairing a player on a 300 ms connection with a player on 20 ms is unfair to both. A matcher can prefer opponents served by the same region, as a tie-breaker after rating.
- Fair-play status: accounts under suspicion can be paired only with each other ("shadow pools"), so innocent players are protected while evidence builds. This is a policy choice; it must be used with care.
Where the pool lives.
| Option | How it works | Good for | Limits |
|---|---|---|---|
| Table in the main database | Seeks are rows; matcher queries and deletes in a transaction | Small sites; easy to reason about | Database load grows with every seek and poll; lock contention at peak |
| Redis sorted set per pool | Score = rating; ZRANGEBYSCORE finds neighbours; a Lua script removes two members atomically | Medium to large; very fast | Script must be atomic; one key per pool is one hot shard |
| In-memory matcher per pool | One process owns each pool; seeks are routed to it; it pairs in memory | Largest scale, lowest latency | Needs routing and failover for the owner; state is lost on crash (players simply re-seek) |
Matchmaking state is short-lived and cheap to lose: if the matcher crashes, clients re-send their seeks within a second. That makes an in-memory owner per pool a very good fit at scale.
Measuring the matcher. Track per pool: median and 95th-percentile waiting time, average rating gap, share of matches above 200 points, and abandon rate (people who cancel while waiting). These numbers show whether the window settings are right.
2. Never put one player into two games#
The race. Player A has a 3+0 seek open in two browser tabs, or the client resends a seek after a network blip. Two matcher instances (or two threads) each see A as available, pair A with B and with C at the same moment, and create two games. A now has two clocks running.
There are three places to prevent this.
Bad: check, then act. Read "is A waiting?", then create the game, then delete A's seek. Two workers can both pass the check before either deletes. This is the classic check-then-act race (see Pattern: Dealing with Contention).
Good: an atomic claim in the database. Make pairing a single transaction that claims both seeks:
BEGIN;
-- lock A and the best candidate, skipping rows another matcher is already handling
SELECT seek_id, player_id, rating FROM seek
WHERE pool = 'blitz-3+0-rated' AND status = 'waiting'
AND rating BETWEEN :r - :window AND :r + :window
ORDER BY abs(rating - :r), created_at
LIMIT 1
FOR UPDATE SKIP LOCKED;
UPDATE seek SET status = 'matched', game_id = :g WHERE seek_id IN (:a, :b) AND status = 'waiting';
-- abort if the update touched fewer than 2 rows
INSERT INTO game (...) VALUES (...);
COMMIT;FOR UPDATE SKIP LOCKED lets many matchers work at once without blocking on each other's rows. It handles the two-tab case if there is also a unique constraint on (player_id) for active seeks and active games, so the database itself refuses a second open seek or a second live game for the same player.
Great: a single owner per pool, plus a player-level guard.
- One matcher process owns each pool, so there is no concurrency inside a pool at all. It pairs in memory, in one thread.
- A player can still have seeks in two pools (blitz and bullet). The guard is a "player is busy" record, set atomically when a game is created:
SET busy:{player} {game_id} NX EX 3600in Redis, or the unique "one active game per player" constraint in the database. If the second pool's matcher fails to set the record, it drops that seek and the player stays in the first game. - When a game is created, the client cancels its other seeks.
What if the database cannot keep up? At about 1,500 pairings per second, plus seeks, cancels and expiries, a single database spends much of its time on short-lived rows and locks. This is the situation Chess.com described in January 2023: database writes were the bottleneck, and the fixes included splitting tables, sharding and "putting services in memory". For matchmaking, the path is:
- Move pools out of the main database into Redis or matcher memory. Seeks never touch the relational database.
- Partition by pool. Each pool's matcher is independent. The busiest pool (3+0 blitz) at about 500 pairings per second is still easily handled by one process.
- If a single pool is too big, split it by rating band (under 1200, 1200–1600 and so on), with overlap handling at band edges: a player near a boundary can be offered to the neighbouring band's matcher after a short wait.
- Keep the player-level guard in a fast store (Redis with
SET NX, or a sharded table keyed by player id). It is the final word on "one game per player".
Failover of a pool owner. Pool ownership is a lease, held in a coordination service such as etcd or ZooKeeper (see Leader Election and Coordination Services). If the owner dies, another process takes the lease, starts with an empty pool, and clients re-seek. Players notice a one- or two-second delay. Because the busy guard is outside the matcher, a half-finished pairing during failover cannot create a duplicate game.
3. Game state and move validation on the server#
Why the server must validate. Anything the client says can be forged. A modified client could send a knight move that jumps three squares, move twice in a row, or claim checkmate. The server keeps the only official board and applies only legal moves. The client also validates (to give instant feedback and to support premoves), but that is for user experience, not for trust.
What the game state holds.
- The current position: piece placement, side to move, castling rights, en passant square, half-move clock (for the 50-move rule) and full-move number. This is exactly what a FEN string records.
- The move list (in UCI form) from the start position, so any earlier position can be rebuilt.
- A count of how many times each position has occurred, for threefold repetition.
- Both clocks, the time the current turn started, and the timer handle for the next possible timeout.
- Pending offers (draw offer, takeback request) and player connection status.
How legality is checked. Chess programs use bitboards: a 64-bit integer per piece type and colour, where each bit is one square. Moves become bit operations: shifting a bitboard by 8 moves every pawn forward one rank. Sliding pieces (bishops, rooks, queens) use precomputed attack tables, often looked up with "magic bitboards" (a multiply-and-shift hash into a table of attack sets). A full legal-move generator produces all legal moves of a position in about a microsecond on a modern core.
Validation for one move:
- Is it this player's turn and the expected ply? (Reject stale or duplicate messages.)
- Is the move in the list of legal moves? Generating all legal moves and checking membership is simplest and fast enough.
- Apply it: move the piece, handle captures, castling (king and rook move, rights lost), en passant (remove the pawn that passed), and promotion (the UCI move says which piece, such as
e7e8q). - Update rights and counters; update the repetition table.
- Check for game end: does the opponent have any legal move? If not, it is checkmate (if in check) or stalemate. Also check insufficient material, threefold repetition (often requires a claim, but many sites apply it automatically), fivefold repetition and the 75-move rule (automatic draws).
Total cost per move: a few microseconds. At 65,000 moves per second at peak, chess logic needs only a few CPU cores across the whole fleet. Game servers are limited by connections, messages and memory, not by chess.
Repetition with Zobrist hashing. Comparing whole positions is slow, so each position gets a 64-bit Zobrist hash: XOR together a random 64-bit number for every (piece, square) pair present, plus numbers for side to move, castling rights and the en passant file. When a move is made, the hash updates with a few XORs (remove the piece from the old square, add it to the new one). Repetition checks become hash lookups in a small map. Collisions are possible in theory, but with 64 bits and at most a few hundred positions per game they are negligible.
Using a well-tested library. Chess rules have tricky corners (en passant that exposes the king to check, castling through attacked squares, promotion with capture). Lichess keeps its chess logic in a separate pure library (its README says the pure chess logic lives in the scalachess module). A shared, heavily tested rules library, ideally the same one on client and server, avoids rule mismatches between what a player is shown and what the server accepts.
Premoves. The client stores the player's premove locally and sends it the moment the opponent's move arrives. The server treats it as an ordinary move with a near-zero think time. Some sites apply premoves on the server (the client sends a conditional move ahead of time) to save a round trip in bullet; this is more complex because the premove must be re-validated against the new position.
Takebacks and draws. A takeback request is a small state machine: request, accept or decline, and on accept, the server pops the last ply (or two) and restores clocks to their values at that point. A draw offer is valid until the offering player's next move or until declined.
A game counts as started only after both players have made a move. Before that, either player can abort, and a player who never moves is timed out with an abort, not a loss, so a disconnected or distracted player does not lose rating before the game begins.
4. Scaling game servers to 500,000 concurrent games#
One owner per game. A game is a tiny piece of state that is written every second or two and must have a single clock authority. The simplest correct design is that one process owns each game, and all messages for that game go there. Inside the process, each game is an actor (a small object with a mailbox), so moves for one game are processed one at a time without locks, while thousands of games run in parallel on many cores.
How many servers. Memory per game is a few KB, so memory is not the limit. CPU per move is small. The real cost is message handling: each move means receiving one message, sending two or more, writing one log entry, and timers. A conservative figure is 20,000–50,000 games per game server process. For 500,000 games at peak with headroom, about 20–40 game servers. Connections live on the gateways: at 50,000–100,000 WebSockets per gateway, 1.5 M connections need about 20–30 gateways.
Placing games and routing messages. Several options:
| Approach | How a move reaches the owner | Strengths | Weaknesses |
|---|---|---|---|
| Sticky player connections to the game server | Both players' WebSockets go straight to the owning server | Fewest hops, lowest latency | The two players must land on the same server; reconnection and deploys are harder |
| Gateways plus consistent hashing | Gateway hashes the game id to a server on a ring | No lookup needed, even spread | Adding servers moves some games; must handle in-flight games during resharding |
| Gateways plus a placement directory | Game service records the owner; gateways cache the mapping | Flexible placement (by load, region), easy draining | Needs a directory (Redis, etcd) and cache invalidation |
| Gateways plus pub/sub | Gateways publish to a channel for the game; the owner subscribes | Decoupled; same channel serves spectators | One more hop through the broker; broker must be fast |
Lichess's published architecture is close to the last row: a separate WebSocket server talking to the main application through Redis. A common large-scale design combines a placement directory (for ownership) with pub/sub (for spectators).
See Consistent Hashing and Pub/Sub and Event Streaming.
Surviving a game server crash. If the owner dies, 20,000 games pause. To recover them:
- Every accepted move is appended to a durable move log before it is acknowledged (Flow 2). The log is keyed by game id: a Redis stream per game with replication, or a Kafka topic partitioned by game id.
- The placement service notices the failure (missed heartbeats, lost lease) and assigns the games to other servers.
- Each new owner replays the game's log: start position plus moves gives the board; the clocks after the last move are in the log too. It then sets the clock of the side to move. Most sites add the time lost during the outage back, or simply do not charge it: a server failure should not cost a player the game.
- Gateways learn the new owner (directory update or new subscription) and clients resync.
A crash then costs players a pause of a few seconds. Without the log, all 20,000 games would be lost, which for rated games means angry players and rating disputes.
How fresh must the log be? Writing to a replicated log on every move adds 1–2 ms. The alternative (batching moves every 100 ms) loses up to 100 ms of moves on a crash, which in practice means one move per game, and the mover's client will resend it on resync. Either is acceptable if the protocol uses ply numbers, because a resent move is applied once.
Deploying without ending games. Game servers hold live state, so deploys use draining: mark a server as draining, stop placing new games on it, and wait for its games to finish (most blitz games end within 10 minutes). For urgent deploys, hand games over: the old owner stops accepting moves for a game, flushes its log, and the new owner replays it, which looks to players like a one-second pause. See CI/CD and Deployment Strategies.
Where to run game servers. For fairness, latency matters more than anything else in bullet. A single central region is simplest and is what many chess sites run: a player in Sydney playing a player in Paris has to cross the world anyway, and the server is somewhere in the middle. Regional game servers help when both players are in the same region (place the game near them). Gateways at the edge help everyone, because TLS and WebSocket set-up happen close to the user and traffic then rides a provider's backbone. Deep Dive 5 deals with the remaining unfairness by compensating lag.
5. Clocks and time control, and fairness despite latency#
The naive clock. The server stops the mover's clock when the move message arrives. That means the mover is charged for their thinking time plus the time the message spent on the network. On a 20 ms fibre link this is noise. On a mobile network with 150 ms one-way delay and 40 moves, it adds up:
- 40 moves × 150 ms = 6 seconds lost in a 3-minute game, about 3% of the player's total time. In a 1-minute bullet game it is 10%, enough to decide many games.
Why not trust the client's clock? The client knows exactly when the player clicked. But a modified client can lie: report 0.1 seconds of thinking for every move and never run out of time. So the server cannot simply take the client's word.
Lag compensation within limits. The server measures each player's network delay itself and gives back some of it, up to a budget, so honest players on slow links lose less while cheaters cannot gain much.
- Measure lag. Gateways ping each client every few seconds and record the round-trip time. Use a smoothed estimate, for example an exponentially weighted moving average, and track its variation.
- Credit per move. When a move arrives, compute
elapsed = now - turn_started. Subtract a compensationcomp = min(estimated_one_way_lag, per_move_cap, quota_left). Chargeelapsed - compto the clock. - A quota that refills slowly. Each player has a lag-compensation quota (for example, a couple of seconds, refilled by a fraction of a second per move). A cheater claiming large lag every move empties the quota quickly and gains little more than an honest slow player would.
- Never compensate below a floor. Each move is charged at least a small minimum (for example, 0.1 s), so even an instant premove costs something, as it would over the board.
A worked example: player on 300 ms round trip, so about 150 ms one-way. Per-move cap 100 ms, quota starting at 2 s and refilling by 50 ms per move. The player gets about 100 ms back on each move until the quota runs low, then about 50 ms per move. Over 40 moves they recover roughly 2 s of the 6 s they would otherwise lose: the unfairness drops from 6 s to under 4 s, and a cheater can steal at most about the same 2–4 s. Exact numbers are a policy choice; the principle is "bounded credit for measured lag".
Chess sites commonly show players a lag indicator and apply some form of lag compensation, but the exact formulas differ between sites and change over time, so treat the numbers above as a design illustration rather than any site's real settings.
Client clock display. The client starts a local countdown when it receives a message, adjusted by its own estimate of how long the message took to arrive. It always snaps to the server's values when the next message arrives. A small discrepancy is normal; a big one means the network is struggling, and the UI can show a warning.
Detecting a flag (timeout) on the server. For each running game, the server knows when the side to move will run out: deadline = turn_started + clock_remaining. Two ways to act on it:
- Timer per game. Schedule a timer for the deadline; reset it on every move. With 500,000 games, use a hierarchical timing wheel, which inserts and cancels timers in O(1) instead of a heap's O(log N).
- Check on demand. When the opponent claims "their flag fell" (clients typically send this as their own timer hits zero), or on a periodic sweep, compare
nowwith the deadline.
When the deadline passes, the server should wait a short grace period (for example, the compensation amount) before declaring a timeout, in case the move is already in flight. If a move then arrives with an elapsed time just beyond the deadline, the server rejects it and ends the game on time; the rule must be applied the same way every time.
Timeout result rules. A player who runs out of time loses, unless the opponent has no way to checkmate (for example only a bare king, or king and a single knight against a bare king in many rule sets); then it is a draw. The server must check this with the same rules library.
Increments and delays.
- Fischer increment (the "+2" in 3+2): after each move, add 2 seconds to the mover's clock.
- Bronstein delay: after the move, add back the time used, up to the delay.
- Simple delay (US delay): the clock waits a few seconds before it starts counting down each turn.
Implementing them is a few lines each in the clock logic, but they must be written into the game record so replays and rule disputes use the same rules.
First move and abort. If white does not move within, say, 30 seconds of the game starting, the game is aborted. The same applies to black's first move. This handles players who have walked away or whose clients never received the game start.
Clock state machine per move (pseudo-code):
function onMove(game: Game, player: Color, move: Uci, ply: number, now: number) {
if (game.status !== "started" && game.status !== "created") return reject("over");
if (game.turn !== player || ply !== game.ply + 1) return resync(game); // stale or duplicate
if (!rules.isLegal(game.position, move)) return reject("illegal");
const elapsed = now - game.turnStartedAt;
const comp = Math.min(lag.oneWay(player), CAP_MS, game.quota[player]);
game.quota[player] -= comp;
const charged = Math.max(elapsed - comp, MIN_CHARGE_MS);
if (game.status === "started" && charged >= game.clock[player]) {
return endGame(game, rules.canMate(game.position, other(player)) ? lossOnTime(player) : draw("timeout vs insufficient material"));
}
if (game.status === "started") game.clock[player] += game.incMs - charged; // clock runs once started
game.quota[player] = Math.min(QUOTA_MAX, game.quota[player] + QUOTA_REFILL);
game.position = rules.apply(game.position, move);
game.ply = ply; game.turn = other(player); game.turnStartedAt = now;
moveLog.append(game.id, { ply, move, clock: game.clock[player], at: now });
timers.reset(game.id, now + game.clock[game.turn]);
broadcast(game);
}6. Rating updates: Elo and Glicko#
What a rating does. A rating is an estimate of strength, built so that the gap between two ratings predicts the result. It drives matchmaking (pairing similar players), leaderboards and players' motivation.
Elo. Arpad Elo's system, adopted by FIDE (the international chess federation) in 1970, gives each player one number. The expected score of player A against B (win = 1, draw = 0.5, loss = 0) is a logistic curve:
E_A = 1 / (1 + 10^((R_B - R_A) / 400))
R_A_new = R_A + K * (S_A - E_A)- A 400-point gap means the stronger player is expected to score about 91%. A 200-point gap gives about 76%; equal ratings give 50%.
- K sets how fast ratings move. FIDE uses larger K for new and young players and K = 10 for top players. Some internet chess servers have used a global K of 32.
- Worked example: A is 1600, B is 1700. E_A = 1 / (1 + 10^(100/400)) = 1 / (1 + 1.778) ≈ 0.36. If A wins with K = 20: A gains 20 × (1 − 0.36) = 12.8 points; B loses the same.
Elo is a zero-sum transfer: points move from loser to winner. Over the long run, this causes inflation or deflation, because players join low and leave high (taking points with them) or improve faster than their rating catches up. Real federations add mechanisms such as rating floors or periodic adjustments to counter this.
Glicko. Mark Glickman introduced Glicko in 1995. Each player has a rating and a rating deviation (RD), a standard deviation for the rating. A player rated 1500 with RD 50 has a 95% interval of about 1500 ± 1.96 × 50, roughly 1402 to 1598. The idea:
- A new player starts with RD 350 (highly uncertain). Their rating moves quickly with each game.
- As a player plays, RD shrinks and their rating moves less per game.
- When a player stops playing, RD grows again over time, up to 350, because their strength may have changed.
- A result against an opponent with a high RD counts for less, because that opponent's rating is unreliable.
Glicko-2 adds a volatility σ per player (0.06 for a new player): how erratic their results are. A player whose results suddenly jump (a fast learner, or an account shared with a stronger friend) gets higher volatility, so their rating adapts faster. A system constant τ limits how fast volatility can change; typical values are between about 0.3 and 1.2, and smaller values prevent dramatic swings after upsets. The update converts ratings to an internal scale (μ = (r − 1500) / 173.7178), computes the variance and improvement implied by the period's results, solves a one-dimensional equation for the new volatility with an iterative method (the Illinois variant of regula falsi is commonly used), then updates RD and rating.
Both Glicko and Glicko-2 are public domain, and Lichess and Chess.com are among the online chess servers that use Glicko-family systems. Lichess's own rating page says it uses Glicko-2, starts new players at 1500 as the Glicko-2 definition recommends, and also takes colour into account, awarding more points for results with the black pieces (black scores slightly worse on average, so a black win is a bigger achievement). The same page makes a point worth repeating in interviews: ratings from different sites cannot be compared, because they use different systems and different pools of players.
Rating periods. Glicko assumes games are grouped into rating periods and all games in a period are treated as simultaneous. Online sites usually want an instant update after every game, so they treat each game as its own very short period, or run a hybrid. The trade-off: instant updates are what players expect, but very short periods make the RD growth between games depend on time rather than on a fixed period length, which needs careful constants.
Per-pool ratings. Bullet skill and rapid skill differ, so each time-control group has its own rating. The pool is decided by estimated game length (for example, base time + 40 × increment), so 2+1 and 3+0 can land in the same pool.
Making the update happen exactly once.
- The game server emits
game_finishedwith a unique game id. The rating service applies it in one transaction that also inserts the game id into arated_gametable (Data Model SQL). A replayed event fails the insert and is skipped. See Delivery Guarantees: At-Most, At-Least and Exactly-Once. - Both players' rows are locked in a fixed order (by player id) to prevent deadlocks when two games involving the same player finish at the same moment.
- If one player has two games ending almost together (rare, since one game per player), the second update reads the result of the first because of the row lock.
Provisional ratings and abuse.
- New players are marked provisional until RD drops below a threshold; they are excluded from leaderboards.
- Sandbagging (losing on purpose to lower your rating, then entering lower sections or farming easy wins) and rating manipulation with a friend (one account resigning repeatedly to the other) are detected by patterns: many fast losses, the same opponent pair, unusual resignation times. Affected games can be voided.
- When a cheater is banned, opponents who lost to them may get their rating points back. This is a batch job over the cheater's games, applying the reversal with the same exactly-once guard.
7. Leaderboards that are correct and fast at tens of millions of players#
The queries.
- Top N for a pool: "top 50 blitz players". Very frequent, identical for everyone, easy to cache.
- My rank: "you are #184,203 of 31 M in blitz, top 6%". Frequent, different for every player.
- Around me: the 10 players above and below me.
- Filtered boards: by country, by friends, by titled players.
Eligibility rules first. A leaderboard that includes everyone is noisy. Typical rules: rated games only, not provisional (RD below a threshold), at least N games, played in the last few weeks, account in good standing (not closed for fair play). Applying these rules is part of correctness: when a player becomes inactive or is banned, they must leave the board.
Redis sorted sets. A sorted set keeps members ordered by score in a skip list plus a hash table. ZADD lb:blitz 1612 p_19 updates a player in O(log N); ZREVRANGE lb:blitz 0 49 WITHSCORES returns the top 50; ZREVRANK lb:blitz p_19 returns a rank in O(log N). For 30 M members, memory is roughly 100 bytes per entry including overhead, so about 3 GB per pool: one Redis node can hold it, with a replica for reads and failover. See Redis in Practice.
- Ties. Many players share a rating. Make the score unique and stable, for example
score = round(rating) * 2^32 + (2^32 - 1 - unix_seconds_when_reached), so whoever reached a rating first ranks higher. Redis scores are 64-bit floats with 53 bits of exact integer range; a 12-bit rating plus a 32-bit timestamp fits. Otherwise ranks jump around between reads. - Updates. 2,400 rating changes per second at peak is trivial for one Redis node (which handles over 100,000 simple operations per second).
Keeping the leaderboard consistent with the ratings database. The ratings database is the source of truth. The leaderboard is a derived view, updated from rating_changed events. To keep them in step:
- Events carry the new rating and a version (games played count). The leaderboard applies an update only if its version is newer than the stored one, so out-of-order or duplicate events cannot move a player backwards.
- Use the outbox pattern or change data capture so that a committed rating change always produces an event (see Change Data Capture and the Outbox Pattern).
- Run a nightly rebuild from the database into a fresh key, then swap it in with
RENAME. This also applies inactivity rules and repairs any drift.
When one Redis node is not enough. If the pool grows past what one node holds, or you need many filtered boards:
- Top N stays easy: only the top few thousand players matter. Keep a small sorted set of the best players per pool; updates from lower players that cannot enter it are ignored.
- Exact rank for everyone: shard by rating band (each shard holds a contiguous range of ratings). A player's rank = (number of players in all higher bands, kept as counters) + rank within their band. Moving between bands is a delete in one shard and an insert in another.
- Approximate rank is often enough for most players: a histogram of players per rating point (a few thousand buckets) gives "top 6.2%" in O(1). Show exact ranks only for, say, the top 10,000.
Country and friends boards. Country boards are just more sorted sets, one per pool and country, updated from the same event. Friends boards are computed on read: fetch the friend list (a few hundred ids) and their ratings in one batch, then sort; no global structure is needed.
Caching. The top 50 is the same for everyone; cache it in the CDN or in memory for a few seconds. "My rank" changes only after my own games or after many others' games, so a short cache per player is fine. This keeps read load off Redis even when millions open their profile.
The general design of ranking at scale is in Design Top-K / Trending (Top Videos, Leaderboards).
8. Spectators and broadcasting popular games#
Ordinary games. Most games have zero or one spectator. When someone opens a live game, the gateway subscribes them to the game's channel (for example a Redis pub/sub channel game:g_8f2) and fetches the current position (FEN plus move list and clocks) from the game server. After that, each published move reaches them. This costs almost nothing.
Popular games. A top streamer or a world-class event can have tens of thousands of live viewers, plus many more watching through a streaming platform. Problems appear:
- The game server would have to send each move to many gateways. With pub/sub, it publishes once; the broker sends one copy per subscribed gateway (maybe 50–200), and each gateway fans out to its local viewers. This two-level fan-out is the standard answer. See Pattern: Pushing Realtime Updates.
- Late joiners all ask for the current position at once (a "thundering herd" right after a famous move). Serve the position from a broadcast cache (the latest FEN, clocks and the last few moves), not from the game server.
- Reconnect storms: if a gateway restarts, thousands of viewers reconnect together. Add jitter to reconnects and serve them from the cache.
Delay for fairness. Spectators can help a player cheat by telling them the engine's evaluation, or by relaying the live board to an accomplice. For top events and streamed games, the public broadcast is often delayed (by some minutes, or a few moves). This is easy to implement in the broadcast tier: buffer moves and release them after the delay. The players' own channel is never delayed.
Choosing the protocol. Spectators only receive, so Server-Sent Events over HTTP would work and can pass through CDNs and proxies easily. Using the same WebSocket protocol as players keeps one code path. For truly huge audiences (a world championship), a page that polls a CDN-cached JSON of the current position every second is cheap and scales without limit, at the cost of up to a second of delay, which is fine for viewers.
"TV" channels. Sites often show a featured game that rotates to the most interesting live game in each pool. A featured game selector picks one game every few minutes by players' ratings and game state, and spectators of the channel are moved from game to game. This is a fan-out of one game to many viewers that changes source over time, which the broadcast tier handles by re-subscribing on behalf of the channel.
Spectator counts. Showing "1,234 watching" needs a counter per game. Each gateway counts its local viewers per game and reports every few seconds; the totals are summed in the broadcast tier. Exact counts are not needed.
Chat for spectators. Large-game chat is like live comments: high write volume, mostly read by many. Use the same fan-out path with sampling or slow mode for huge rooms; the design is the same as in Design Live Comments (Facebook Live).
9. Game persistence and replays#
Two kinds of storage. A live game needs durability per move (so a crash loses nothing) for a few minutes. A finished game needs cheap, permanent storage and fast reads by id and by player. These are different systems:
- During the game: the durable move log (Deep Dive 4). It can be deleted a while after the game is archived.
- After the game: one immutable record in the games store, plus entries in each player's history and the search index.
Compact encoding. Storing PGN text works, but it is wasteful at billions of games. A compact binary form:
- Moves as an index into the list of legal moves in that position, sorted in a fixed order. There are at most 218 legal moves in any chess position, so each ply fits in one byte; with entropy coding (frequent moves get shorter codes, using a model of which moves are likely) it drops to a few bits per ply.
- Clock readings as deltas from the previous reading in centiseconds, variable-length encoded: usually one or two bytes per ply.
- Metadata: player ids, ratings and rating changes, time control, result and reason, start time, variant, opening code.
That gives the roughly 400 bytes per game from the capacity estimate, so the whole history of a big site fits on a modest cluster. Lichess states that it stores more than 12 billion games in MongoDB and publishes all rated games in a free PGN database, which researchers have used for many academic studies.
IDs. Game ids must be unique without coordination across game servers: use a time-ordered 64-bit id (Snowflake-style) or random base-62 strings like the 8-character ids common in chess site URLs. A real lesson in id width: in June 2017, Chess.com's game number passed 2,147,483,647 (2³¹ − 1, the largest signed 32-bit integer), and its app stopped working on 32-bit iOS devices because the id no longer fit. Use 64-bit ids from the start. See Unique ID Generation.
Read paths.
- Game page by id: key lookup in the games store, then cache (finished games never change, so caching is easy and can be long-lived). Popular games go into the CDN.
- Player history: "last 50 games" reads one partition of
games_by_player, newest first (Data Model). Pagination uses a cursor of(started_at, game_id). - Search: "my games as black in the Sicilian that I lost on time" needs an index over players, colours, openings, results and dates: Elasticsearch or a similar engine, fed from the
game_finishedevents. Lichess's README mentions that its games are indexed by Elasticsearch. See Elasticsearch and Search Systems. - Replay: the client receives the move list and clock readings and plays them forward with its own rules library. No server work beyond the record fetch.
- PGN export and bulk downloads: generated on demand for single games; monthly bulk exports are written as compressed files to object storage.
Opening explorer and statistics. Many sites show, for any position, how often each move was played and how it scored. This is an aggregate over billions of games, keyed by position hash. It is built in batch (Spark or a similar engine) from the archive and served from a key-value store; it is an analytics product on top of the game store, not part of live play.
Storage tiers. Recent games (the last few months) are read most: keep them on fast storage. Older games are rarely read but must stay available: move them to cheaper storage tiers, still reachable by id, with slower reads. See Data Lifecycle, Tiering and Retention.
Analysis results. A computer analysis of a game (evaluation per move, mistakes, best lines) is large compared with the game itself: storing evaluations for every ply adds several hundred bytes to a few KB. Store it separately, only for games where someone asked for analysis or fair play ran it.
10. Disconnections, reconnection and abandonment#
What can go wrong. Mobile networks drop for a few seconds when users walk between cells or switch from Wi-Fi. Laptops sleep. Browsers throttle background tabs. A TCP connection can look open while no data flows ("half-open"). In a 3-minute game, a 5-second outage is a big deal.
Detecting dead connections. The gateway sends an application-level ping every few seconds and expects a pong. If two or three are missed, it treats the client as disconnected, tells the game server, and closes the connection. Without this, a half-open TCP connection could take minutes to be noticed. The pings also give the latency samples used for lag compensation. With 1.5 M connections and a 4-second interval, that is about 375,000 tiny pings per second across the gateway fleet, which is fine.
Reconnecting without losing moves.
- The client keeps the game id and the last ply it has seen. On reconnect (to any gateway), it sends
resyncwith that ply. - The gateway routes it to the game's owner, which replies with all later moves, the clocks and the status. If the game ended while the client was away, the reply is the final result.
- If the client had sent a move just before the outage and is not sure it arrived, it resends it with the same ply number; the server ignores it if already applied (idempotency), or applies it if not, as long as it is still that player's turn.
- The client reconnects with exponential backoff with jitter (for example 0.5 s, 1 s, 2 s, plus random spread) so a gateway restart does not cause a reconnection stampede.
The clock keeps running. The server cannot distinguish a player who is thinking from one whose connection is down, so the clock of the side to move always runs. This is the standard rule on chess sites.
Abandonment and claiming victory. If a player is disconnected and does not come back:
- After a short period (for example 10–30 seconds in blitz, longer in slow games), the opponent is offered a button to claim victory or call a draw, or to keep waiting.
- If the absent player's clock runs out first, the game simply ends on time.
- Repeated abandoning is tracked per account; serial abandoners get matchmaking cool-downs.
Server-side failures look like disconnections. If a gateway dies, all its clients reconnect elsewhere and resync. If a game server dies, gateways get errors for its games; the placement service moves the games, and clients resync once the new owner has replayed the log. In both cases, the same resync protocol handles recovery, which is why making resync correct and idempotent is so valuable.
Message ordering. Within a game, all messages come from one owner, which numbers them by ply, so clients can always detect gaps and duplicates. Across gateways, ordering does not matter because each client only needs the order of its own game's messages.
11. Anti-cheat basics#
The threat. The most common and damaging cheat is engine assistance: running a chess engine on another device or in another browser tab and copying its moves. Engines are far stronger than any human; by 2023 top engines were rated above 3500, while the best humans are around 2800. Other abuses include sandbagging, rating manipulation between accounts, multiple accounts, and harassment. Cheating is also a public issue: in September 2022, Chess.com was at the centre of a widely covered controversy when it banned a grandmaster after accusations by the world champion, which shows how much trust in fair play matters to the business.
Why the server cannot simply prevent it. The engine runs on a device the site does not control. Browser checks (detecting that the tab lost focus) are weak signals that honest players also trigger. So detection is statistical: does the way this player plays look like a human of their strength, or like an engine?
Signals.
- Move matching. For each position, compare the player's move with the engine's top choices. Strong humans match the engine's first choice often in simple positions, but much less in complex ones. A 1400-rated player who matches the top engine move 90% of the time over many games is very unlikely to be honest.
- Average centipawn loss (ACPL) and accuracy. A centipawn is 1/100 of a pawn in the engine's evaluation. For each move, the loss is how much worse the position became compared with the best move. Low average loss across many games, far below what is typical for the player's rating, is suspicious.
- Timing patterns. Humans spend more time on hard moves and less on obvious ones. Engine users often take similar time for every move (the time to read and copy), or think long on obvious recaptures. Consistent move times in complex positions are a signal.
- Performance versus rating. A sudden jump in results (winning streaks against much stronger players) that is not explained by a new account getting calibrated.
- Behaviour signals. Focus changes, unusual input patterns, multiple accounts on the same device or IP, and reports from opponents.
Making it affordable. Deep engine analysis costs real CPU: analysing a 45-ply game at a useful depth takes several CPU-seconds to a CPU-minute. Analysing all 40 M games a day at depth would cost millions of CPU-minutes a day. So use a funnel:
- Cheap screen for every game: rating change, result streaks, move-time statistics, reports, account age. Pure arithmetic over data already in the event.
- Shallow analysis for flagged games and for samples: a quick engine pass.
- Deep analysis for players whose scores keep rising, across many of their games.
- Human review for the highest scores. Reviewers see the statistical case plus the games and decide.
Lichess offloads engine analysis to fishnet, a system of distributed analysis workers (its README says analysis is distributed with fishnet and that it talks to Stockfish on a cluster of donated servers). A large commercial site would run the same idea on its own fleet or on cheap interruptible cloud capacity.
Statistics and false positives. A single great game proves nothing; strong humans sometimes play near-perfect games. Decisions rely on many games and on how unlikely the pattern is for an honest player of that strength. A false ban harms an innocent player and the site's reputation, so thresholds are set very high for automatic action, and appeals exist. Some decisions are delayed on purpose so cheaters cannot learn which game triggered the ban.
Actions. Close the account; mark its games; restore rating points to opponents who lost to the cheater (a batch job using the same exactly-once guard as normal rating updates); remove the account from leaderboards; and optionally pair suspected accounts only among themselves while evidence builds.
Events and titled play. For prize events, sites use stronger measures, which can include identity checks, camera and screen monitoring, and dedicated fair-play software (when Chess.com changed its weekly Titled Tuesday event in September 2025, the changes included rolling out its fair-play software, called Proctor). These are product and process measures more than system design, but the data pipeline must support them.
Fair play inputs from the game server. The fair-play pipeline needs data that only the live system has: precise per-move think times (server-side), lag measurements, focus events from the client, and connection metadata. The game server should include these in the game_finished event, so analysis never needs to query live systems.
12. Reliability, surges and operations#
What fails and what users feel.
| Failure | User impact | Response |
|---|---|---|
| Game server crash | 20,000 games pause for a few seconds | Replay from the move log on another server; clients resync |
| Gateway crash | Its clients disconnect briefly | Reconnect with jitter to another gateway; resync |
| Matchmaker crash | Seeks for one pool vanish | Lease moves to a standby; clients re-seek automatically |
| Ratings database slow or down | Ratings and leaderboard updates lag | Events queue in Kafka; games continue; show "rating pending" |
| Games store slow | History and game pages slow | Games in progress unaffected; archive writes buffered from the event log |
| Redis leaderboard lost | Leaderboard empty | Rebuild from the ratings database; serve the cached top N meanwhile |
The key rule: live play must not depend on anything slow. A move touches the gateway, the game server and the move log. Ratings, leaderboards, history, search and fair play are all downstream of events and can lag without breaking games.
Surges. Chess traffic jumps with events: the 2020 lockdowns, the Netflix series The Queen's Gambit, and the December 2022 to January 2023 boom. In that last surge, Chess.com wrote that traffic nearly doubled in about seven weeks, that it saw more than 250,000 new accounts a day, and that its databases could not write fast enough, causing 502 errors and timed-out games during peak hours (around noon to 4 p.m. US Eastern time). Its fixes included more hardware (it runs a hybrid of on-site and cloud infrastructure), separating database tables, sharding, moving services into memory, and making failures more graceful. The design lessons:
- Keep the hottest writes off the shared database. Moves, seeks and live state live in memory and in logs, not in the main relational database.
- Shard by the natural key early: players by player id, games by game id.
- Fail gracefully: when downstream systems are slow, keep games going and delay ratings and history, rather than failing the whole site.
- Load test the bursts, especially the top-of-the-hour tournament start and big-event spikes, where many players seek at once. See Capacity Planning and Load Testing.
Graceful degradation. Under extreme load, turn off what is optional before what is essential: first spectator counts and live analysis features, then computer analysis requests, then history and search freshness. Keep matchmaking and play last. A "high load" banner with slightly longer pairing waits is far better than failed games.
Observability. The metrics that matter to players:
- move processing time on the server (p50, p99), and end-to-end move delivery time;
- measured lag per player and the share of games played with high lag;
- pairing wait time per pool;
- disconnect and resync rates per gateway, region and client version;
- timeouts that happened during server or network incidents (to compensate affected players);
- game aborts per hour (a sudden rise often means a bug at game start).
See Observability: Logs, Metrics and Traces.
Daily (correspondence) chess. Games that last days use the same rules library and the same game record, but none of the real-time machinery: moves arrive by REST, the "clock" is a deadline per move stored in the database, a scheduled job times out expired games, and notifications (push or email) replace WebSockets. It is a different, simpler workload that shares storage and ratings with live chess.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Race in pairing puts one player in two games | Two clocks running; player loses one game; trust damage | Single matcher owner per pool, atomic removal of both seeks, plus a per-player "busy" guard (SET NX or a unique active-game constraint) |
| Hot pool at peak (3+0 blitz) | Matcher CPU or Redis key becomes a hotspot | In-memory matcher per pool; split by rating band if needed; batch matching every 100–250 ms |
| Database write saturation during a surge | 502 errors, games time out, sign-ups fail | Keep moves, seeks and live state out of the relational DB; shard players and games; queue ratings and history through Kafka |
| Game server crash | 20,000 games pause; risk of lost moves | Durable move log before acknowledging; reassign games and replay; do not charge lost time |
| Network lag on mobile | Slow-link players lose seconds every move | Server-measured lag with bounded compensation and a refilling quota; prefer opponents in the same region for bullet |
| Forged client messages | Illegal moves, fake timeouts, fake clocks | Server-authoritative rules and clocks; ply-numbered, idempotent moves; ignore client clock claims |
| Timer load from 500,000 running clocks | CPU spent on timer management | Hierarchical timing wheels; one timer per game reset on each move |
| Viral game with huge audience | Fan-out overload on the owning server; join herd | Two-level pub/sub fan-out, broadcast cache for late joiners, CDN polling for the largest audiences, broadcast delay |
Duplicate or replayed game_finished events | Ratings changed twice | rated_game insert in the same transaction; version checks in the leaderboard |
| Leaderboard drift or loss | Wrong ranks, empty boards | Versioned updates, nightly rebuild from the ratings DB, cached top N |
| Reconnect stampede after a gateway restart | Thundering herd on gateways and game servers | Exponential backoff with jitter; resync served from in-memory state; spread over many gateways |
| Engine cheating | Unfair results and ratings, lost trust | Funnel of cheap screens, sampled and deep engine analysis, human review, rating refunds, broadcast delay |
What Interviewers Expect#
Mid-level. A clear split between REST (matchmaking requests, history, leaderboards) and WebSockets (moves, game events). The server validates moves and owns the clocks; the reason is that clients cannot be trusted. A simple matchmaking queue by rating, a games table, and ratings updated when the game ends. A leaderboard using a sorted set. Reasonable numbers for concurrent games and moves per second.
Senior. One owner per game, with gateways routing by game id, and a plan for game server failure (durable move log and replay). Atomic pairing that prevents a player being matched into two games, with a concrete mechanism. Clock handling: server-side elapsed time, increments, timeouts with insufficient-material draws, first-move aborts, and an honest discussion of lag. Exactly-once rating updates via an idempotency key. Spectator fan-out with pub/sub. Reconnection with resync by ply number.
Staff and above. Lag compensation with bounded credit and its abuse model. Glicko-2 and why rating deviation matters for matchmaking and leaderboards. Scaling matchmaking beyond a database (in-memory owners per pool, rating bands, leases), and leaderboards beyond one node (top-N sets, band sharding, approximate ranks). The economics and statistics of anti-cheat (funnel, false positives, refunds). Lessons from real surges: keeping hot writes off shared databases and degrading gracefully, using Chess.com's 2023 experience as an example.
Deep Dive: sizing every tierShow
Starting point: 500,000 concurrent games at peak, 1 M player connections plus 500,000 spectators, 65,000 moves per second, 1,500 new games per second.
WebSocket gateways.
- A tuned gateway holds 100,000–200,000 mostly idle WebSockets in a few GB of memory (about 10–30 KB per connection for TLS state and buffers). Use 60,000 per gateway so that losing one gateway does not overload the others.
- 1.5 M / 60,000 = 25 gateways, plus 30% spare: about 32 gateways, spread across two or three zones.
- Messages: 375,000 heartbeats per second, 200,000 move deliveries per second, and resyncs. That is about 20,000 messages per second per gateway, well within one server's capacity.
Game servers.
- Per move: parse, validate (microseconds), append to the log, send three or more messages. Budget 50 µs of CPU per move including networking. 65,000 moves per second × 50 µs = 3.25 CPU-seconds per second, so about 4 cores of pure work for the whole fleet.
- So game servers are sized by safety and failure domains, not by CPU. With 25,000 games per server, 500,000 games need 20 servers; add spare capacity for a zone failure: about 30 game servers. A crash then affects 25,000 games, about 5% of the total.
- Memory: 25,000 games × 4 KB = 100 MB. Trivial.
Move log.
- 65,000 appends per second at peak, each about 100 bytes: 6.5 MB/s. A Redis cluster with a few primaries and replicas, or a Kafka topic with 30–60 partitions, handles this comfortably.
- Retention: keep a game's log until it has been archived and for a safety window (for example 24 hours). 1.8 B plies per day × 100 B = 180 GB per day, deleted on a rolling basis.
Matchmaking.
- 1,500 pairings per second total; the largest pool at about 500 per second. One in-memory matcher per pool, each on a small instance, with a standby. 10–20 small matcher processes.
- Busy guards: 1,500 games × 2 players = 3,000
SET NXoperations per second, plus deletes at game end. One Redis primary is enough.
Ratings database.
- 2,400 rating row updates per second at peak, in 1,200 two-row transactions. A single well-provisioned PostgreSQL primary can do this, but player profiles, settings and other writes share it. Shard by player id into 8–16 shards for headroom; a rating transaction touches two shards only when the players live on different shards, so either use a small two-shard transaction or keep ratings in their own store with per-player single-row updates (apply each player's change independently, idempotent per game id).
Games store.
- Writes: 40 M finished games per day, 460 per second on average, 1,500 per second at peak, about 400 bytes each. Plus two
games_by_playerrows per game. - Total stored: 16 GB per day of compact data; 6 TB per year; with replication factor 3 and indexes, about 30 TB per year. A Cassandra or MongoDB cluster of 10–20 nodes holds years of games.
- Reads: game pages and histories, perhaps 20,000 per second at peak, mostly served from caches for popular games.
Leaderboards.
- 30 M entries per pool × 100 bytes = 3 GB per pool; 3–4 pools plus country boards: one Redis node of 16–32 GB with a replica, or two shards.
Search.
- 40 M documents per day into Elasticsearch, about 1 KB each with indexed fields: 40 GB per day, 15 TB per year before replicas. Keep recent years hot, older years in cheaper tiers.
Fair-play analysis.
- Suppose 5% of games get a shallow pass (2 CPU-seconds) and 0.5% get a deep pass (60 CPU-seconds): 2 M × 2 + 200,000 × 60 = 16 M CPU-seconds per day, about 185 cores busy around the clock. Add on-demand analysis for users: another few hundred cores. A pool of 500–1,000 cores, ideally cheap interruptible capacity.
| Tier | Peak load | Fleet |
|---|---|---|
| WebSocket gateways | 1.5 M connections, ~600,000 msg/s | ~32 servers |
| Game servers | 500,000 games, 65,000 moves/s | ~30 servers |
| Move log | 65,000 appends/s | Small Redis or Kafka cluster |
| Matchmakers | 1,500 pairings/s | 10–20 small processes |
| Ratings DB | 2,400 row updates/s | 8–16 shards |
| Games store | 1,500 writes/s, 20,000 reads/s | 10–20 nodes |
| Leaderboards | 2,400 updates/s | 1–2 Redis nodes + replicas |
| Analysis | ~16 M CPU-s/day for fair play | 500–1,000 cores |
Deep Dive: real-world systems comparedShow
Two very different organisations run the largest chess sites, and their public descriptions show different answers to the same problems.
Lichess. A free, ad-free, open-source chess server run by a non-profit, founded in 2010 by the French programmer Thibault Duplessis. Its public README describes the architecture:
- The main application (lila) is written in Scala 3 on a modified Play framework, fully asynchronous, using futures and streams.
- WebSocket connections are handled by a separate server (lila-ws) that talks to the main application through Redis. This is the gateway and game-logic split from our design.
- Pure chess rules live in a separate library (scalachess), so they can be tested and reused independently.
- MongoDB stores more than 12 billion games, indexed by Elasticsearch.
- Computer analysis is distributed with fishnet to Stockfish running on a cluster of donated servers.
- All rated games are published in a free PGN database.
- Ratings use Glicko-2, starting at 1500, with a small adjustment for colour.
Lichess shows that a few core processes on a modest number of servers can run a top chess site, because chess state is tiny and the rules are cheap to compute.
Chess.com. The largest chess platform, using a freemium model. Public information:
- It reported about 11 million daily active users in April 2023, and more than 250 million members by early 2026.
- In January 2023 it reported 31.7 million games in one day, more than a million games an hour, and an average of 16,000 moves per second, with peaks between noon and 4 p.m. US Eastern time.
- It runs a hybrid of its own hardware and cloud infrastructure.
- The 2023 surge exposed database write limits; its fixes were to split tables, shard databases and move services into memory.
- Its live chess servers have been publicly associated with the Java platform (Chess.com chose Azul's Zing JVM for real-time gaming, according to a press release).
- It has a fair-play team and tooling, and in 2025 introduced its Proctor fair-play software for titled events.
- The 2017 game-id overflow past 2³¹ − 1, which broke its app on 32-bit iOS devices, is a classic warning about id widths.
What the two have in common. Both validate moves and run clocks on the server, use WebSockets for live play, keep per-time-control ratings with a Glicko-family system, store every game, and run large engine-analysis pools for both user features and fair play.
| Aspect | Lichess | Chess.com |
|---|---|---|
| Organisation | Non-profit, donations, open source (AGPL) | Company, freemium subscriptions and ads |
| Main language (public) | Scala on a modified Play framework | Java for live chess servers (public press release) |
| Real-time layer | Separate WebSocket server, Redis between it and the app | Not described in detail publicly |
| Game storage | MongoDB, Elasticsearch index, public PGN exports | Not described in detail publicly; sharded databases after 2023 |
| Ratings | Glicko-2, colour adjustment | Glicko family |
| Engine analysis | fishnet workers, donated servers | Own engines (it acquired Komodo in 2018 and built Torch) and analysis fleet |
Deep Dive: a 45-minute interview planShow
| Minutes | What to do | What to put on the board |
|---|---|---|
| 0–5 | Clarify: which time controls, rated and casual, scale, spectators in or out, anti-cheat in or out | Functional list; "3+0 blitz first" |
| 5–10 | Non-functional goals and numbers: 500,000 concurrent games, 65,000 moves/s, move latency, one game per player, fair clocks | Capacity lines; "connections and latency are the constraint, not bandwidth" |
| 10–15 | Entities and APIs: seek, game, move, rating; REST for seeks and history, WebSocket messages with ply numbers | API sketch with ply and server clocks |
| 15–25 | High-level design: matchmaker, game service, gateways, game servers as single owners, move log, event log, rating and leaderboard services | The HLD |
| 25–40 | Deep dives: double-match prevention, game server scaling and failover, fair clocks with lag, leaderboard at scale; add spectators or anti-cheat if asked | Pairing transaction or Lua script; move flow sequence; clock pseudo-code |
| 40–45 | Failure modes, surge lessons, what you would measure | Bottleneck table, key metrics |
Common traps.
- Trusting the client for move legality or clock values.
- Storing every move in the main relational database synchronously and calling it "done": this is the write bottleneck Chess.com hit in 2023.
- "Check if the player is free, then create the game": a race that pairs one player twice.
- Ignoring lag: in bullet, network delay decides games unless the design addresses it.
- Updating ratings in the game server without an idempotency guard, so retries change ratings twice.
Deep Dive: follow-up questions and strong answersShow
"Why WebSockets and not HTTP polling?" Moves must arrive within about 100 ms and both sides send. Polling at 100 ms intervals for 1 M players would be 10 M requests per second, most of them empty. A WebSocket gives a single long-lived, two-way connection with tiny frames. SSE would work for spectators, who only receive.
"How do you make sure a move is never lost?" The game server appends the move to a replicated log before it acknowledges the move or forwards it. If the server crashes after the append, the new owner replays it; if it crashes before, the mover never got an acknowledgement and resends with the same ply number on resync.
"Two moves for the same game arrive on different gateways at the same time. What happens?" Both are routed to the single owner, which processes the game's mailbox one message at a time. Only one can be the expected ply for the side to move; the other is rejected or treated as a duplicate.
"A player claims they lost on time because of your servers. How would you know?" The game record has server-side timestamps for every move, measured lag, and the server's view of the connection. Metrics show whether the game server or gateway had an incident at that moment. If so, rating changes for affected games can be reverted in bulk.
"How would you support 10× more games?" Live play scales horizontally: more gateways, more game servers, more partitions of the move log. The parts that need care are matchmaking (more pools or rating-band sharding), ratings (shard by player), and the games store (add nodes; it is append-only). Tournament starts and global events need load tests at that size.
"How would you run a tournament with 20,000 players starting at the same minute?" Pair in batches with a dedicated pairing service for the tournament, create games in bulk across all game servers, and stagger the game-start messages over a few seconds. Arena-style tournaments re-pair players as soon as their game ends, which spreads load over the event. See the tournament Deep Dive below.
"Could you run games on the clients and just have the server referee?" You could exchange moves peer to peer, but clocks, results and ratings would depend on trusting the clients, and a disconnect would be ambiguous. The server is cheap at this scale, so the authoritative server model wins.
"How do you rank 30 million players exactly?" For most players, show a percentile from a rating histogram; for the top players, an exact rank from a sorted set. Exact ranks for everyone are possible by sharding sorted sets by rating band and keeping counts per band.
Deep Dive: chess engines and the analysis clusterShow
Engines power three features: playing against the computer, post-game analysis for users, and fair-play detection. All three run on the same kind of worker pool.
How engines talk to the system. Most engines speak the Universal Chess Interface (UCI), an open text protocol released in 2000 by Rudolf Huber and Stefan Meyer-Kahlen. The host sends a position (position startpos moves e2e4 e7e5) and a search command (go depth 20, go movetime 1000, or with clock values go wtime 60000 btime 58000), and the engine streams info lines with depth, score and best line, then bestmove. Moves use the same from-square-to-square notation our wire protocol uses. UCI also defines options such as UCI_LimitStrength and UCI_Elo, which some engines (including Stockfish) support to play at a chosen strength. That is how "play the computer at level 5" is built.
How engines search (the short version).
- Minimax with alpha-beta pruning: explore moves for both sides to a given depth, assume each side plays its best, and skip branches that cannot change the result. With good move ordering, alpha-beta searches roughly the square root of the nodes plain minimax would, so it reaches about twice the depth for the same work.
- Iterative deepening: search depth 1, then 2, then 3 and so on, reusing results to order moves better at each depth. The search can stop at any time with the best move so far, which is ideal for time-limited analysis.
- Transposition table: a large hash table, keyed by the Zobrist hash, that stores results for positions already searched, because the same position can be reached by different move orders.
- Evaluation: a function that scores a position. Classical engines used hand-written terms (material, mobility, king safety, pawn structure). Modern Stockfish versions use an efficiently updatable neural network (NNUE) evaluation, which runs fast on ordinary CPUs.
Sizing analysis. A modern engine searches millions of positions per second per core. A depth that gives reliable per-move evaluations for fair play might take 0.5–2 seconds per position; a 45-ply game is then 20–90 CPU-seconds. That is why the fair-play funnel (Deep Dive 11) analyses only a small share of games deeply.
The worker pool.
- A job queue holds analysis requests with priorities: users waiting for a post-game analysis are high priority; fair-play batch jobs are low priority and fill idle time.
- Workers pull jobs, run the engine with fixed settings (depth or node limits, not wall-clock time, so results are comparable between machines), and post results.
- Determinism: for fair-play statistics, use the same engine version and settings for a whole cohort of analyses, and record the version with each result.
- Caching: positions in openings and common endgames repeat across games; caching evaluations by position hash saves a large share of work.
- Cheap capacity: analysis is batch work and tolerates interruption, so interruptible cloud instances or donated machines suit it. Lichess's fishnet is an example of this design with volunteer and donated hardware; results from untrusted workers can be spot-checked by re-running a sample.
Client-side engines. Browsers can run engines compiled to WebAssembly, so a user's own analysis board can run locally without server cost. Lichess, for example, runs a version of Stockfish inside the user's browser for local analysis. Server analysis is then needed only for shared, stored analyses and for fair play.
Engines against cheating. The same engine output that helps users is the raw material for fair-play signals: per-move evaluation loss, match rate with the engine's top choices, and how these change with position complexity. The analysis cluster therefore serves both product and trust features, and capacity planning must cover both.
Deep Dive: tournaments, arenas and the top-of-the-hour spikeShow
Tournaments were out of scope for the core design, but they create the sharpest load spikes on a chess site, so the design must leave room for them.
Formats.
- Arena: a fixed time window (for example one hour). As soon as a player's game ends, they are paired again with someone near them in the standings. Points for wins and draws, often with streak bonuses. Players come and go freely.
- Swiss: a fixed number of rounds. In each round, players with similar scores are paired, avoiding repeat opponents and balancing colours. Everyone starts each round at the same time.
- Knockout and round robin for small invitational events.
Why they hurt. A Swiss round with 20,000 players creates 10,000 games in the same second. A popular arena starting at the top of the hour adds thousands of seeks at once. Normal matchmaking at 1,500 games per second is smooth; a 10,000-game burst is not.
Arena pairing. A tournament has its own pairing service (one owner per tournament), which keeps a list of players waiting for their next game, sorted by tournament score and rating. Every second or two, it pairs waiting players with nearby scores, like matchmaking with a different sort key. Because games end at different times, arena load is spread out after the first round.
Swiss pairing. Pairing algorithms for Swiss events (for example the Dutch system used in many FIDE events) group players by score, then pair within groups while avoiding rematches and balancing colours. Computing pairings for 20,000 players takes a moment of CPU; it happens once per round, so it is fine. The hard part is the start of each round.
Smoothing the start.
- Pre-create games. Compute pairings, create all game records in bulk (one batch write), and place them across game servers in advance.
- Stagger the start. Send game-start messages over a few seconds rather than in one instant; the clocks start only on the first move, so a 2-second stagger is invisible.
- Pre-warm. Scale gateways and game servers before scheduled starts. Tournament schedules are known in advance, so capacity can be planned, not just autoscaled.
- Standings as a derived view. Each finished game updates the tournament standings: a sorted set per tournament (score, tie-break, rating). Large audiences read standings, so cache them for a second or two.
Correctness rules.
- A player in a tournament must not be in a normal matchmaking game at the same time: use the same per-player busy guard.
- Withdrawals, disconnects and byes (an odd number of players) are part of pairing logic.
- A cheater discovered after the event changes standings and prizes, so tournament results must be recomputable from the game records.
Load test the spike. The worst moment of the week is often a big scheduled event's first round overlapping with the daily evening peak. Simulate it before it happens, with synthetic clients that connect, seek, play moves on a realistic schedule and disconnect.
Deep Dive: Glicko step by step, with numbersShow
Glicko-2 looks frightening on paper, but each step has a simple meaning. Here is the flow for one player after one rating period, and then a worked example using the simpler Glicko-1 formulas to show the effect of rating deviation.
Glicko-2, in words.
- Convert to the internal scale. μ = (r − 1500) / 173.7178 and φ = RD / 173.7178. (173.7178 is 400 / ln 10, which converts the base-10 Elo scale to a natural-log scale.)
- Weigh each opponent by their uncertainty. g(φⱼ) = 1 / √(1 + 3φⱼ² / π²). An opponent with a large RD gets a g value well below 1, so a result against them counts less.
- Expected score against each opponent: E = 1 / (1 + exp(−g(φⱼ)(μ − μⱼ))).
- Estimated variance v of the player's rating, from the information the games carry: v = 1 / Σ g(φⱼ)² E (1 − E). Few games, or games against very uncertain or very mismatched opponents, give a large v (little information).
- Improvement Δ: Δ = v Σ g(φⱼ)(sⱼ − E), the rating change the results suggest.
- New volatility σ′: solve a one-dimensional equation that balances the observed surprise (Δ² compared with φ² + v) against the prior volatility, constrained by τ. An iterative root-finding method (commonly the Illinois variant of regula falsi) converges in a handful of steps.
- Pre-period RD: φ* = √(φ² + σ′²). Uncertainty grows by the volatility before the new information is applied.
- New RD and rating: φ′ = 1 / √(1/φ*² + 1/v), and μ′ = μ + φ′² Σ g(φⱼ)(sⱼ − E). Convert back: r′ = 173.7178 μ′ + 1500, RD′ = 173.7178 φ′.
Why RD matters, with a Glicko-1 example. Glicko-1 uses the same ideas without volatility. With q = ln 10 / 400 ≈ 0.0057565:
g(RD) = 1 / sqrt(1 + 3 q^2 RD^2 / pi^2)
E = 1 / (1 + 10^(-g(RD_j) (r - r_j) / 400))
d^2 = 1 / (q^2 * sum g(RD_j)^2 E (1 - E))
r' = r + q / (1/RD^2 + 1/d^2) * sum g(RD_j) (s_j - E)
RD' = sqrt(1 / (1/RD^2 + 1/d^2))Two players, both rated 1500, each beat the same opponent (rating 1500, RD 50). For that opponent g ≈ 0.988, E = 0.5 and d² ≈ 123,750.
- Player A, established, RD 50. 1/RD² = 0.000400, 1/d² ≈ 0.0000081, so the step is 0.0057565 / 0.000408 ≈ 14.1, times g(s − E) ≈ 0.494: A gains about 7 points. RD goes from 50 to about 49.5.
- Player N, new, RD 300. 1/RD² ≈ 0.0000111, so the sum is ≈ 0.0000192 and the step is ≈ 300, times 0.494: N gains about 148 points. RD drops from 300 to about 228.
The intuition is Bayesian: the rating is the centre of a belief, RD is its width. New evidence moves a wide belief a lot and a narrow belief a little, and every game narrows it.
What this means for the system.
- Matchmaking can use RD: pair new players with wider rating windows, since their rating is a guess anyway.
- Leaderboards should exclude high-RD players, whose ratings are not yet reliable.
- Inactivity increases RD over time. Compute this lazily: store
last_game_atand apply the RD growth when the player next plays or when the leaderboard is rebuilt, rather than updating millions of rows every day. - Storage: three floats per player per pool (rating, RD, volatility), plus games count and last game time. Tiny.
- Testing: rating code is easy to get subtly wrong. Use published worked examples (Glickman's paper on Glicko-2 includes one) as unit tests.
Deep Dive: the client side of a fast gameShow
In bullet chess, the client is half the experience. The server is authoritative, but the client hides latency and keeps the board feeling instant.
Optimistic moves. When the player drops a piece, the client checks legality locally (with the same rules library as the server), shows the move at once, and starts the opponent's clock on screen. The server's acknowledgement normally arrives 50–200 ms later with the official clocks. If the server rejects the move (very rare with a correct client: usually a resync race), the client rolls back to the server's position.
Clock display. The client shows a countdown driven by its local timer, starting from the last server clock value minus an estimate of the message's travel time. When a new server message arrives, it snaps to the server's value. A smooth correction (adjusting over a few hundred milliseconds) avoids visible jumps of a tenth of a second. Under 10 seconds, show tenths so players can judge flagging.
Premoves and move queues. The client stores one premove (some sites allow a queue of several) and sends it the instant the opponent's move arrives and the premove is legal in the new position. If it became illegal (the opponent captured the piece), it is dropped silently.
Background tabs and mobile apps. Browsers slow down timers in background tabs, and mobile operating systems suspend apps. When the app returns to the foreground, it must resync immediately rather than trust its local clock. On mobile, a game in progress should keep the connection alive while the screen is on and reconnect quickly when the network changes.
Sounds and haptics. Move and capture sounds, and a warning at low time, are small features with a big effect on fast play. They are played locally from the client's own state, not from server messages, so they are instant.
Rendering cost. A chessboard is cheap to draw, but animations, arrows and highlights on low-end phones can drop frames. Pieces as vector images, CSS transforms for movement and minimal re-rendering keep the board responsive.
Offline and analysis features. Puzzles, the analysis board with a local WebAssembly engine, and replaying stored games can all work without a live connection once the data is loaded. This takes load off the servers and keeps the app useful on poor networks.
Fair-play signals from the client. Clients can report focus changes and input patterns, but these signals are easy to forge, so they are only weak evidence, combined with statistical analysis on the server. The protocol should never let a client report something the server can measure itself, such as move timing.
See Mobile System Design and Frontend System Design for the general client patterns.
Deep Dive: accounts, abuse and rate limitingShow
Engine cheating gets the attention, but a chess site also deals with simpler abuse that the platform must handle at the system level.
Multiple accounts and rating abuse. One person creating many accounts can farm wins against their own alternates, dodge bans, or sandbag into lower rating ranges. Signals: the same device fingerprint or IP address across accounts, games mostly between the same pair, fast resignations, and accounts created in bursts. The response is to void the affected games, merge or close accounts, and restore opponents' ratings.
Seek and challenge spam. A script can create and cancel thousands of seeks or challenges per minute, which loads the matcher and annoys other players. Rate limit per account and per IP: for example a few seeks per 10 seconds and a cap on open challenges. Use token buckets at the gateway and API layer (see Rate Limiting and Throttling).
Message floods on the game socket. A modified client can send hundreds of messages per second (draw offers, chat, invalid moves). The gateway enforces per-connection message rates and closes abusive connections. The game server ignores repeated draw offers within a short time and limits takeback requests.
Aborting to avoid opponents. Some players abort every game where they get the colour or opponent they dislike. Track abort rates and apply matchmaking cool-downs for players who abort too often.
Bots and automated play. Official bot accounts (for people who want to play against or build engines) can be allowed through a separate API with clear labels, so they never enter human pools. Unlabelled automated play in human pools is treated like engine cheating.
Account security. Ratings, titles and paid subscriptions make accounts worth stealing. Use the usual protections: strong password hashing, optional two-factor authentication, login rate limits and checks for unusual logins. See Authentication and Authorization.
Chat moderation. In-game chat between strangers needs filters for abuse and a quick way to mute and report. Many players disable chat entirely; making "chat off" easy is part of the design. Reports feed the same review queue as fair-play flags, with different reviewers.
Data for decisions. All these checks need the same raw data as fair play: who played whom, from which device and network, how quickly, with what results. Keeping this data in the event log and the analytics store (with sensible retention and privacy rules) lets the trust and safety team build new detectors without touching live play.
Key Takeaways#
- The server is the arbiter. It owns the board and both clocks, validates every move with a shared rules library, and never trusts the client's view of time or results.
- One owner per live game. Gateways hold connections and route by game id; a game server holds each game in memory and processes its messages one at a time.
- Moves are numbered and logged. Ply numbers make every message idempotent and every gap detectable; a durable move log written before acknowledging lets another server replay a game after a crash.
- Pairing needs an atomic claim. A single matcher per pool plus a per-player busy guard prevents one player landing in two games. Move matchmaking out of the main database as you grow.
- Clocks are a fairness problem. Charge elapsed server time, compensate measured lag within a capped and refilling budget, use timing wheels for timeouts, and apply draw-on-insufficient-material and first-move abort rules.
- Ratings change exactly once. Consume
game_finishedevents, update both ratings in one transaction guarded by the game id, and lock rows in a fixed order. Glicko's rating deviation also guides matchmaking windows and leaderboard eligibility. - Leaderboards are derived views. Redis sorted sets for top N and rank, versioned updates, nightly rebuilds from the source of truth, percentiles for the long tail.
- Spectators are a fan-out problem. Two-level pub/sub, a broadcast cache for late joiners, CDN polling for the biggest audiences, and a delay for top games to prevent assistance.
- Store games compactly and forever. About 400 bytes per game makes billions of games affordable; use 64-bit ids, per-player history partitions and a search index.
- Anti-cheat is statistics plus people. A funnel of cheap screens, engine analysis and human review, with rating refunds for victims.
- Keep hot writes away from shared databases. Chess.com's 2023 surge showed that database writes are where a chess site breaks; live play must keep running while ratings and history catch up.