Design the Backend for a Real-Time Multiplayer Board Game
System DesignModel answerLast updated
Design a backend that manages live game state, enforces turn-based rules, and delivers move updates in real time across thousands of concurrent sessions.
Context
A startup is building an online platform for a classic two-player turn-based board game (think 8×8 grid, two opposing piece sets, strict movement rules, and mandatory capture sequences). You have been asked to design the backend that powers live gameplay.
The board state is small, but correctness under concurrent writes and low-latency delivery to both players are non-negotiable.
What you need to design
Functional scope
- Lobby and pairing: players enter a queue and get matched with an opponent of similar skill.
- Move handling: the server receives a player's intended move, validates it against the current board and the full ruleset (turn order, legal paths, forced captures, multi-step sequences), and applies it if valid.
- Live delivery: both players see the updated board within a fraction of a second.
- Session replay: players can step through every move of a completed game.
Non-functional targets
- Tens of thousands of simultaneous games.
- End-to-end move latency under ~150 ms within a region.
- Zero tolerance for illegal state: two moves sent in the same instant must not both succeed.
What to cover in your answer
- API surface — the endpoints or WebSocket events players use to make moves, receive updates, and reconnect after a drop.
- Data model — schema for players, active game state, and the move log.
- Concurrency control — the exact mechanism that guarantees only one valid move commits per turn.
- High-level architecture — the major components (gateways, game service, cache, pub/sub, persistent store) and how a move flows through them end to end.
- Trade-offs — at least two meaningful design choices with reasoning.
You are not expected to implement a rules engine. Focus on infrastructure and correctness.
Hints
Hint 1
Start by separating hot state from durable state: the board the server checks every move doesn't need to live in Postgres on the critical path.
Hint 2
Think about what 'one move per turn' really means technically: it's a check-and-set operation. Which primitive gives you an atomic compare-and-swap, and where does it live?
Hint 3
The two players might connect to different gateway nodes. How does a move applied by one gateway reach the other player's socket? Sketch the pub/sub path explicitly.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the Problem
The bottleneck here is correctness, not throughput. A board fits in under 1 KB, moves arrive roughly once every few seconds per game, and 10 k concurrent games at that rate produce maybe 2 k moves/s — comfortably within what a single Redis instance handles. The interesting problems are: serializing concurrent writes to the same game, pushing updates to two players who may sit on different servers, and recovering cleanly from dropped connections.
1. Clarify and Size
Before drawing boxes, establish scope:
- Rules: standard 8×8, forced captures, multi-jumps as a single move path, kinging. No spectators initially but the design should not preclude them.
- Scale: ~10 k concurrent games → ~20 k WebSocket connections. Move history at ~60 moves/game × ~1 M games/day ≈ 6 GB/day, well within a modest Postgres instance with archival.
- Latency: under 150 ms end-to-end within a region is achievable with WebSockets and an in-memory game store.
State out loud: the hard parts are race conditions on writes, reconnect state sync, and fan-out latency — not raw throughput.
2. API Design
REST for out-of-band operations:
POST /queue— join matchmaking, returns{ticket_id}.DELETE /queue/{ticket_id}cancels.GET /games/{id}— full snapshot: board, whose turn, current version number, clocks.GET /games/{id}/moves?from_seq=N— paginated move log for replay.
WebSocket (/ws?token=...), one persistent connection per client:
Client → server:
{ "type": "move", "game_id": "...", "move_id": "uuid", "expected_version": 17,
"path": [[5,2],[3,4],[1,2]] }
{ "type": "resign" | "offer_draw", "game_id": "..." }
{ "type": "resume", "game_id": "...", "last_seq": 17 }
Server → client:
{ "type": "move_applied", "seq": 18, "path": [...], "captured": [...],
"promoted": false, "next_turn": "red", "version": 18 }
{ "type": "move_rejected", "move_id": "uuid",
"reason": "STALE_VERSION | NOT_YOUR_TURN | ILLEGAL | CAPTURE_REQUIRED" }
{ "type": "game_over", "result": "black_wins", "reason": "resignation" }
Two details matter here: clients send intent (a path), never a board; and expected_version enables optimistic concurrency. move_id makes retries idempotent.
3. Data Model
Postgres (durable, off the hot path):
players(id, username, rating, created_at)
games(id, red_player_id, black_player_id, status,
result, started_at, ended_at)
moves(game_id, seq, player_id, path, captured_squares,
promoted, board_hash_after, created_at,
PRIMARY KEY (game_id, seq))
moves is an append-only event log. Storing captured_squares and promoted explicitly makes replay and undo trivial without re-running the rules engine on old states.
Redis (hot state, millisecond access):
game:{id} HASH board, turn, version, status, clocks
game:{id}:events STREAM recent events, for reconnect catch-up
game:{id}:seen SET processed move_ids (idempotency, short TTL)
mm:queue:{bucket} ZSET player_id → enqueue_timestamp
conn:{player_id} STRING gateway node id
4. Architecture and Move Flow
Clients ──WS──> L4 LB ──> WebSocket Gateways (stateless, hold sockets)
│
Game Service (rules engine + validation)
│ │ │
Redis Pub/Sub Kafka ──> History Writer ──> Postgres
(live state, (per-game channel) (async)
Lua scripts)
Matchmaking Service ── rating-bucketed Redis ZSETs
A move flows like this:
- Client sends
moveover WebSocket to a gateway node. - Gateway forwards it to the Game Service (stateless; any instance can handle it).
- Game Service runs the pure rules function: checks turn, piece ownership, movement direction, forced-capture obligation, multi-jump completeness.
- If valid, it commits via a Lua script against Redis (see section 5).
- On success, it publishes
move_appliedtogame:{id}pub/sub channel. - Both gateways — even if the two players connect to different nodes — are subscribed and push the event down their respective sockets.
- The event is also enqueued to Kafka; a history writer batches inserts into Postgres asynchronously.
Postgres never sits on the synchronous path for a move.
Matchmaking: workers pop pairs atomically from rating-bucketed ZSETs using a Lua ZPOPMIN, widen the rating window as wait time grows, initialize Redis state, and push match_found to both clients.
5. Concurrency Control — One Move per Turn
The race condition: a player double-taps, a retry arrives after a timeout, or (less likely) both players submit simultaneously. Exactly one state transition per version must win.
Approach: optimistic concurrency via a Redis Lua script.
The script runs atomically (Redis is single-threaded for script execution) and does the following:
-- inputs: game_id, expected_version, player_id, move_id, new_board, next_turn
if redis.call("SISMEMBER", moves_seen, move_id) == 1 then
return "DUPLICATE" -- re-deliver prior ack
end
local v = redis.call("HGET", game_key, "version")
if tonumber(v) ~= expected_version then
return "STALE" -- lost the race, refetch
end
if redis.call("HGET", game_key, "turn") ~= player_id then
return "NOT_YOUR_TURN"
end
redis.call("HMSET", game_key, "board", new_board, "turn", next_turn,
"version", expected_version + 1)
redis.call("SADD", moves_seen, move_id)
redis.call("XADD", events_key, "*", ...)
redis.call("PUBLISH", channel, payload)
return "OK"
The losing client gets STALE, refetches with GET /games/{id}, discovers it's no longer their turn, and surfaces a clean error. No polling loop needed.
Alternative — single-writer actor per game: assign each game to one Game Server via consistent hashing on game_id. That node processes moves through an in-memory queue, eliminating CAS retries and reducing latency by ~5–10 ms. The cost is sticky routing and lease-based ownership handoff on failure, which adds operational complexity. Worth mentioning as the natural evolution for higher scale.
Clocks: compute elapsed time server-side at commit time, inside the Lua script. A timeout job (backed by a Redis sorted set keyed by deadline) fires a synthetic timeout move through the same CAS path — so it can't race a last-second valid move.
6. Trade-offs Worth Raising
WebSockets vs. SSE / long-polling. WebSockets give sub-100 ms bidirectional flow and are the right call here. SSE works for server→client push but requires a separate channel for client→server moves. Long-polling adds 50–200 ms of artificial latency. The only reason to avoid WebSockets is restrictive corporate proxies, which are rare for a consumer game.
Redis Lua (stateless servers) vs. actor model (stateful servers). Lua keeps game servers stateless, simplifies horizontal scaling, and makes failover trivial — any healthy node picks up the next request. The actor model shaves a network round-trip per move and avoids lock contention but requires a lease / fencing-token scheme on handoff. Start with Lua; migrate to actors if profiling shows Redis CAS retries becoming a bottleneck.
Synchronous vs. asynchronous persistence. Writing to Postgres on the critical path would add 5–20 ms and create a single point of failure. The async Kafka path means a crash between Redis commit and Kafka publish could lose a move from the log. Mitigate by treating the Redis Stream (game:{id}:events) as the source of truth for recovery and draining it into Postgres on startup after a crash.
Common Mistakes
- Letting clients send a new board state instead of a move path — the server must always be the authority.
- Storing live game state only in Postgres — it can't sustain the read/write rate at low latency.
- Forgetting that
PUBLISHin Redis does not guarantee delivery to subscribers who reconnect later; the Stream fills that gap. - Skipping the forced-capture check — it's a hard rule in standard checkers and a common source of illegal-state bugs.