Real-Time Multiplayer Game Backend with Move Reversal
System DesignModel answerLast updated
Architect a scalable backend for a turn-based multiplayer game supporting concurrent matches, move reversal requests, and dynamic player rankings.
Problem Statement
You need to architect a backend system for a turn-based multiplayer game platform. The system must support real-time gameplay between matched opponents, allow players to propose reversing their previous moves (with opponent approval), and maintain updated player rankings based on match outcomes.
Requirements
Core Functionality
- Match Operations: Players get paired and exchange moves with immediate feedback on validity
- Move Reversal: Either player can propose rolling back to an earlier game state; the opponent decides whether to accept
- Player Rankings: A scoring system that reflects win/loss records and adjusts after every finished match
Quality Attributes
- Responsiveness: Players should see their opponent's moves and receive validation feedback with minimal perceived delay
- Correctness: Both players must always observe identical game states; no divergence permitted
- Fault Tolerance: Server failures should not lose in-progress games
- Throughput: The architecture must handle traffic spikes during organized events
What to Cover
Your design should address:
- Communication Protocol: How clients and servers exchange move data and reversal requests
- Storage Schema: How you represent current game positions, historical moves, and player scores
- Service Architecture: The components responsible for real-time message delivery, game logic, and ranking updates
- Reversal Mechanism: The technical approach to implementing move rollback while preserving history
- Ranking Updates: How to efficiently adjust player scores without creating database bottlenecks
Provide enough detail that the design could guide an implementation team.
Hints
Hint 1
Think about whether each game needs a single authoritative process or if you can distribute the work across multiple servers
Hint 2
Consider how optimistic concurrency control can prevent race conditions when both players submit moves simultaneously
Hint 3
Player rankings are computed from finished games, not live gameplay—does this suggest an asynchronous approach?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time Multiplayer Game Backend Design
1. Scoping and Capacity Planning
Begin by quantifying the problem to anchor your design decisions.
Assumed scale:
- 5 million simultaneous players translates to roughly 2.5 million active matches
- Peak traffic during tournaments reaches 2× baseline
- Average match duration: 10 minutes
- Move frequency: one move every 6–8 seconds per match
Derived metrics:
- Move throughput: 2.5M matches ÷ 7s ≈ 350K moves/second at baseline, 700K/s at peak
- Match completions: 2.5M matches ÷ 600s ≈ 4,000 finishes/second
- Persistent connections: 5M WebSocket connections requiring 100–150 gateway servers (assuming 50K connections per node)
- Hot state volume: ~2KB per active game (position encoding, move log, timers) = 5GB total, easily cached in distributed memory
Key observation: Each match operates as an independent state machine. This independence enables horizontal partitioning by match identifier. The architectural challenges are maintaining strict per-game ordering, ensuring durability, and aggregating cross-game ranking data.
2. API Design
Synchronous HTTP endpoints:
POST /matchmakingwith parameters{time_limit, ranked}→ returns{match_id, assigned_side, websocket_url}GET /matches/{match_id}→ snapshot of current position and move historyGET /rankings?page=0&size=100→ paginated leaderboardGET /players/{player_id}/score→ individual ranking details
WebSocket message types (bidirectional):
Client sends:
SUBMIT_MOVE {match_id, sequence_num, notation}PROPOSE_REVERSAL {match_id, target_sequence}RESPOND_REVERSAL {match_id, approved}RESYNC {match_id, last_seen_sequence}(recovery after disconnect)
Server broadcasts:
MOVE_CONFIRMED {sequence_num, notation, updated_position, time_remaining}REVERSAL_PENDING {requester, target_sequence, expires_in_seconds}REVERSAL_EXECUTED {new_sequence, updated_position}orREVERSAL_REJECTEDMATCH_FINISHED {outcome, score_changes}INVALID_MOVE {reason, current_sequence}
The sequence_num acts as a version number for optimistic concurrency: the server applies a move only if its sequence matches the server's current state. This automatically rejects duplicates, replays, and out-of-order submissions.
3. Data Models
In-memory cache (Redis, sharded by match_id):
Key pattern match:{id} stores a hash:
position: <encoded board state>
sequence: 42
active_side: white
white_time_ms: 180000
black_time_ms: 175000
last_move_timestamp: 1234567890
status: active
pending_reversal: {requester: black, target: 40, deadline: 1234567905}
Key pattern match:{id}:history stores a list of {notation, resulting_position, timestamp}
Key pattern match:{id}:reversal_stack holds moves that were undone (cleared on any new move)
Key pattern rankings is a sorted set (player_id → score)
Persistent storage:
players table (relational DB, partitioned by player_id):
player_id, username, current_score, score_volatility, total_matches, row_version
matches table (relational or wide-column DB):
match_id, player_white_id, player_black_id, time_control, ranked, status, outcome, created_at, finished_at
move_log table (append-only, wide-column DB like Cassandra):
partition key: match_id
clustering key: sequence_num
columns: notation, resulting_position, timestamp, event_type (MOVE | REVERSAL)
Event type distinguishes regular moves from reversals, creating an audit trail that can fully reconstruct any game.
score_updates table:
match_id (primary key for idempotency), player_white_delta, player_black_delta, processed_at
4. Service Architecture
Players ─(WebSocket)─> Load Balancer ─> Gateway Fleet
│
│ route by hash(match_id)
▼
Match Coordinator
(single writer per match)
│
┌───────────────────┼───────────────────┐
▼ ▼ ▼
Redis Cluster Kafka Topic Kafka Topic
(live state) "move_events" "match_results"
│ │
▼ ▼
Log Archiver Scoring Service
(write to DB) (update rankings)
Gateway tier:
- Maintains WebSocket connections
- Stateless; handles authentication and routes messages to coordinators
- Either maintains a registry (
player_id → gateway_address) for coordinator push-back, or subscribes to Redis pub/sub channelsmatch:{id}
Match Coordinator:
- Each match is owned by exactly one coordinator process (via distributed lock with lease in etcd/Consul)
- Single-writer-per-match guarantees strict ordering without distributed locking
- Consistent hashing assigns matches to coordinators; on coordinator failure, lease expires and another coordinator takes over
Move processing flow:
- Gateway forwards
SUBMIT_MOVEto the owning coordinator - Coordinator validates: correct player's turn, sequence number matches, move is legal (using server-side rules engine)
- Coordinator updates time clocks using server-authoritative timestamps to prevent client manipulation
- Coordinator atomically updates Redis using Lua script (check sequence, append to history, update position)
- Coordinator publishes event to Kafka topic for durable logging
- Coordinator pushes
MOVE_CONFIRMEDto both players via their gateways
Total server-side latency: network hop + ~1ms Redis operation ≈ 20–40ms.
5. Critical Design Details
Strong consistency guarantees:
- Single coordinator ownership per match
- Sequence-number-based optimistic locking
- Server-authoritative timestamps for timing
- Both players receive identical, server-sequenced events
Durability strategy: Redis operates with replication and append-only file persistence (fsync every second). For stronger guarantees, wait for Kafka acknowledgment (acks=all) before confirming the move to clients—adds 5–10ms latency but survives coordinated failures.
Coordinator recovery after crash:
- Lease expires in distributed lock store
- New coordinator acquires lease with higher epoch number
- Loads state from Redis; if Redis failed too, replays from Kafka or persistent move log
- Clients detect disconnection, reconnect, and send
RESYNCwith their last observed sequence - Coordinator sends catch-up events
Move reversal implementation:
Store the complete position encoding after each move (includes castling rights, en-passant state, etc.). Reversal becomes O(1): pop move(s) from history and restore the previous position.
Reversal flow:
- Player sends
PROPOSE_REVERSAL. Only allowed if no pending reversal exists and match is active - Determine target sequence:
- If opponent hasn't moved yet: revert just the requester's last move (sequence - 1)
- If opponent has responded: revert both moves (sequence - 2) to give requester their turn back
- Coordinator sets
pending_reversalwith 15-second timeout - Opponent approves or declines via
RESPOND_REVERSAL - On approval: Lua script verifies sequence unchanged, moves entries from history to reversal_stack, restores position and clocks, appends REVERSAL event to audit log
- On decline or timeout: clear
pending_reversal - Any new move clears both
pending_reversalandreversal_stack
Policy decisions to clarify with interviewer:
- Do clocks pause during pending reversal? (Usually no, to prevent abuse)
- Can players redo previously reversed moves? (If yes, requires same approval flow)
- What happens if a move arrives while reversal is pending? (Typically auto-rejects the reversal)
Leaderboard without contention:
Match completion publishes {match_id, player_white_id, player_black_id, outcome} to Kafka. The Scoring Service consumes asynchronously—gameplay never blocks on ranking updates.
Per consumed event:
- Insert into
score_updateskeyed by match_id; on conflict, skip (ensures idempotent processing under at-least-once delivery) - In a single transaction:
- Lock only the two participating player rows (not entire table)
- Compute new scores using chosen rating algorithm (Elo, Glicko, TrueSkill)
- Update both rows and increment
row_version
- Update Redis sorted set
rankingswith new scores - Commit transaction
Because only two rows are locked per match, and scoring is asynchronous, this scales horizontally. The Scoring Service can run multiple consumer instances, each processing a partition of match results.
Ranking queries:
- Top-N queries hit the Redis sorted set (O(log N + M) where M is result size)
- Individual rank lookup:
ZREVRANKin Redis, O(log N) - Redis updates are eventually consistent with the source-of-truth in the database; periodic reconciliation jobs can detect and fix drift
6. Additional Considerations
Partitioning strategy: Hash match_id consistently to assign coordinators. Player-based sharding doesn't work because both players need the same coordinator.
Observability: Emit metrics for move latency percentiles, reversal acceptance rates, coordinator rebalancing events, and cache hit rates. Distributed tracing across gateway → coordinator → Redis → Kafka helps diagnose tail latencies.
Anti-cheat: Server validates all moves using its own rules engine; clients never dictate legality. Time tracking uses server clocks exclusively. Deep behavior analysis (move timing patterns, out-of-game signaling) runs offline on the Kafka event stream.
Graceful degradation: If ranking updates lag during traffic spikes, display slightly stale scores with a staleness indicator. Core gameplay continues unaffected.
This architecture achieves low latency through in-memory state and single-writer-per-game design, strong consistency via sequencing and optimistic locks, fault tolerance through replication and event sourcing, and horizontal scalability by treating matches as independent shards.