PK
Puzzle PK
Brain Games & Logic Arena
How We Built a Real-Time Multiplayer PK System for Puzzle Games
engineering multiplayer WebSocket game development

How We Built a Real-Time Multiplayer PK System for Puzzle Games

A developer deep-dive into building Puzzle PK's real-time multiplayer system — covering WebSocket architecture, game state synchronization, room management, anti-cheat measures, and scaling strategies.

PK
Puzzle PK Team
14 min

When we set out to build Puzzle PK, we had a bold vision: take 20 classic puzzle games — Sudoku, Minesweeper, Tetris, Nonogram, 2048, Sokoban, Gomoku, and more — and let players compete against each other in real time. Not turn-by-turn, not asynchronous, but true real-time head-to-head puzzle battles where every second counts.

This article is a behind-the-scenes technical deep-dive into how we designed and built the multiplayer PK system that powers Puzzle PK. We will cover the high-level architecture, WebSocket communication, room management, game state synchronization, the plugin-based game engine, our two PK modes (Speed PK and Steal PK), anti-cheat strategies, and how we plan to scale the system as our player base grows.


The High-Level Architecture

Technology Stack

Puzzle PK's architecture is built on a modern stack optimized for real-time performance:

  • Frontend: Angular with Server-Side Rendering (SSR) for SEO and fast initial loads. The game logic runs entirely in the browser for instant responsiveness.
  • Backend: Go (Golang) for the WebSocket server and API layer. Go's goroutine-based concurrency model is ideal for handling thousands of simultaneous WebSocket connections with minimal memory overhead.
  • Database: PostgreSQL for persistent storage (user accounts, game history, leaderboards) with connection pooling for high throughput.
  • Deployment: Cloudflare Pages for the frontend (global CDN with edge caching) and a dedicated server for the Go backend.

Why This Stack?

The choice of Go for the backend was driven by three factors. First, goroutines make it trivial to handle one goroutine per WebSocket connection without the thread-per-connection overhead of traditional languages. Second, Go's static typing and compilation catch many bugs at build time. Third, Go's standard library includes excellent WebSocket support through the gorilla/websocket package (now maintained as nhooyr/websocket), eliminating the need for heavy frameworks.

Angular was chosen for the frontend because its component-based architecture and dependency injection system make it easy to build a modular game engine where each puzzle game is a self-contained module that plugs into the shared PK infrastructure.


WebSocket Communication Layer

Connection Lifecycle

When a player opens Puzzle PK, the client establishes a WebSocket connection to the backend server. The connection lifecycle follows these stages:

  1. Handshake: The client sends an HTTP upgrade request with an authentication token (JWT). The server validates the token and upgrades the connection to WebSocket.
  2. Session initialization: The server creates a session object that tracks the player's state — their user ID, current room (if any), connection quality metrics, and last heartbeat timestamp.
  3. Heartbeat: Both client and server exchange periodic ping/pong messages every 15 seconds. If the server does not receive a pong within 30 seconds, the connection is considered dead and the player is marked as disconnected.
  4. Graceful disconnection: When a player navigates away or closes the browser, the client sends a close frame. The server cleans up the session and notifies any room the player was in.

Message Protocol

All WebSocket messages use a binary-encoded JSON format with the following structure:

{
  "type": "string",      // Message type identifier
  "room": "string",      // Room ID (if applicable)
  "payload": { ... },    // Type-specific data
  "seq": number,         // Sequence number for ordering
  "ts": number           // Server timestamp (milliseconds)
}

We chose JSON over Protocol Buffers or MessagePack for pragmatic reasons: the message payloads for puzzle games are small (typically under 500 bytes), and JSON's human-readability makes debugging significantly easier during development. The overhead of JSON encoding for small payloads is negligible compared to network latency.

Message Types

The system defines approximately 30 message types, grouped into categories:

  • Room messages: room.create, room.join, room.leave, room.ready, room.start
  • Game messages: game.state, game.move, game.progress, game.result
  • PK messages: pk.steal, pk.attack, pk.defend, pk.score_update
  • System messages: sys.ping, sys.pong, sys.error, sys.reconnect
  • Chat messages: chat.message, chat.emoji

Each message type has a corresponding handler on both the client and server side, implementing a clean command pattern.


Room Management

Room Architecture

A room is the fundamental unit of multiplayer interaction. Each room represents a single game session between two or more players. The room lifecycle follows this pattern:

  1. Creation: A player creates a room by selecting a game type (e.g., Sudoku), difficulty level, and PK mode (Speed or Steal). The server generates a unique room ID and adds the creator as the first participant.
  2. Matchmaking: Other players can join the room through direct invitation (sharing a room code), random matchmaking (the server pairs players with similar skill ratings), or the public room browser.
  3. Ready check: Once all players have joined, each must signal readiness. This prevents games from starting when a player has stepped away.
  4. Game start: When all players are ready, the server generates the puzzle (ensuring both players receive the identical puzzle instance) and broadcasts the start signal with the initial game state.
  5. Active game: During gameplay, the server relays moves, validates progress, and maintains the authoritative game state.
  6. Game end: The game ends when a win condition is met (one player finishes first, or time runs out). The server calculates final scores, updates leaderboards, and archives the game record.
  7. Cleanup: After results are acknowledged, the room is destroyed and resources are freed.

Puzzle Generation Fairness

A critical design decision was ensuring absolute fairness in puzzle generation. When two players compete in a Sudoku PK, they must solve the exact same puzzle. The server generates the puzzle using a deterministic seed and distributes the identical puzzle state to all players. The seed is never shared with clients to prevent pre-computation cheating.

For games like Tetris where randomness is inherent (the sequence of falling pieces), both players receive the same pseudo-random sequence generated from a shared seed. This ensures that differences in performance are due to skill, not luck.


Game State Synchronization

The Authoritative Server Model

Puzzle PK uses an authoritative server model for game state synchronization. The server is the single source of truth for the game state. Clients send their moves to the server, the server validates them, updates the canonical state, and broadcasts the updated state to all players in the room.

This model prevents a wide class of cheating attacks (more on this later) at the cost of introducing a small amount of latency between a player's action and the visual confirmation. For puzzle games, this latency (typically 20-80ms depending on the player's distance from the server) is acceptable because puzzle games do not require the sub-10ms responsiveness of first-person shooters.

Optimistic Updates with Reconciliation

To keep the user experience smooth despite network latency, the client uses optimistic updates: when a player makes a move, the client immediately applies the move locally and displays the result, without waiting for server confirmation. If the server rejects the move (e.g., because it violates a game rule), the client rolls back to the last confirmed state.

In practice, rollbacks are extremely rare because the client performs the same validation as the server before sending a move. The optimistic update pattern means that players experience near-zero perceived latency during normal gameplay.

Delta Compression

Rather than sending the full game state with every update, we use delta compression: only the changes since the last acknowledged state are transmitted. For a Sudoku game, this means sending a message like "cell (3,5) set to 7" instead of the entire 81-cell grid. This reduces bandwidth consumption by approximately 90% compared to full-state updates.

Delta compression is especially important for games with large state spaces, such as Nonograms (which can have grids up to 25x25 = 625 cells) and Minesweeper (up to 30x16 = 480 cells).


The Plugin-Based Game Engine

Architecture Philosophy

One of the most important architectural decisions in Puzzle PK was designing the game engine as a plugin system. Each of the 20 puzzle games is implemented as a self-contained plugin that conforms to a common interface. This design has several advantages:

  • Isolation: A bug in one game cannot affect other games.
  • Independent development: Different team members can work on different games simultaneously without merge conflicts.
  • Easy expansion: Adding a new game requires implementing the plugin interface, not modifying the core engine.
  • Consistent PK experience: The PK infrastructure (rooms, matchmaking, scoring) works identically across all games.

The Game Plugin Interface

Every game plugin must implement the following interface:

interface GamePlugin {
  // Game identity
  readonly gameId: string;
  readonly displayName: Record<string, string>;

  // Puzzle generation
  generatePuzzle(difficulty: Difficulty, seed: number): GameState;

  // Move validation
  validateMove(state: GameState, move: GameMove): ValidationResult;

  // State application
  applyMove(state: GameState, move: GameMove): GameState;

  // Win condition
  checkWinCondition(state: GameState): WinResult;

  // Progress calculation (0-100%)
  calculateProgress(state: GameState): number;

  // Scoring
  calculateScore(state: GameState, timeMs: number): number;

  // Rendering (client-side only)
  render(state: GameState, container: HTMLElement): void;
}

This interface is intentionally minimal. The core engine handles all multiplayer concerns (rooms, communication, synchronization, scoring), while the plugin focuses purely on game logic and rendering.

Server-Side Validation

A key security feature is that the game plugin runs on both the client and the server. The client uses the plugin for rendering and optimistic updates, while the server uses it for authoritative validation. When the server receives a game.move message, it calls validateMove() and applyMove() on its copy of the game state. If validation fails, the move is rejected and the client must reconcile.


PK Modes: Speed PK and Steal PK

Puzzle PK offers two distinct multiplayer modes, each creating a different competitive dynamic.

Speed PK

In Speed PK, both players solve the same puzzle independently and simultaneously. The first player to complete the puzzle wins. There is no direct interaction between the players during the game — each focuses on their own grid. The competitive element comes purely from speed.

Speed PK is the simpler of the two modes and is available for all 20 games. It is ideal for players who want a pure test of puzzle-solving ability without interference.

During a Speed PK match, the server broadcasts each player's progress percentage to the other player. This creates a dynamic progress bar UI that shows how close your opponent is to finishing, adding psychological pressure without mechanical interaction.

Steal PK

Steal PK is our more innovative mode, available for selected games. In Steal PK, players can interfere with each other through "attack" and "defend" actions. The specific mechanics vary by game:

  • Sudoku Steal PK: When you complete a row, column, or box, you can "steal" a completed section from your opponent, forcing them to redo it.
  • Tetris Steal PK: Clearing multiple lines sends "garbage rows" to your opponent's board, pushing their stack higher.
  • Minesweeper Steal PK: Successfully flagging a mine cluster lets you reveal (and potentially detonate) a random cell on your opponent's board.
  • 2048 Steal PK: Achieving a merge combo sends a disruptive tile (with an odd value like 3 or 5) to your opponent's board.

Steal PK creates a fundamentally different strategic calculus. Players must balance offense (trying to disrupt their opponent) and defense (building resilience against attacks) alongside the core puzzle-solving task. This three-dimensional strategic space makes Steal PK endlessly replayable.

Implementing Steal PK Attacks

When a player triggers an attack action, the flow is:

  1. The client sends a pk.attack message with the attack type and parameters.
  2. The server validates that the attack is legal (the player has earned the right to attack through gameplay achievements).
  3. The server applies the attack effect to the opponent's game state.
  4. The server broadcasts a pk.attack notification to the attacked player, including an animation trigger.
  5. The attacked player's client displays the attack animation and applies the state changes.

This flow ensures that attacks are validated by the server, preventing players from sending fake attack messages.


Anti-Cheat Measures

Threat Model

In a competitive puzzle game, the primary cheating vectors are:

  1. Auto-solvers: Bots that automatically solve puzzles faster than any human could.
  2. State manipulation: Modifying the client-side game state to skip to the solution.
  3. Time manipulation: Sending fake timestamps to appear faster.
  4. Replay attacks: Replaying a previously recorded solution.

Detection Strategies

We employ multiple layers of defense:

Server-side timing analysis: The server tracks the time between consecutive moves. Human solving exhibits characteristic patterns — pauses for thinking, bursts of quick moves when a deduction chain is found, and occasional corrections. Bot solving typically shows unnaturally consistent timing. Our anomaly detection system flags sessions with suspiciously regular move intervals.

Move sequence analysis: For each game, we maintain statistical models of typical human solving patterns. An auto-solver might fill a Sudoku grid column by column, while a human solver typically works on constrained cells first. Unusual solving patterns trigger manual review.

Server-authoritative state: Because the server maintains the authoritative game state and validates every move, client-side state manipulation is ineffective. A player cannot simply send a "puzzle complete" message — they must send every individual move, and each move must be valid given the current state.

Progress rate limiting: We impose maximum progress rates based on the theoretical minimum solving time for each puzzle type and difficulty. A player who solves an expert Sudoku in 5 seconds is automatically flagged and their result invalidated.

Reconnection integrity: When a player disconnects and reconnects, the server resumes from the last confirmed state. The client cannot resume from a locally modified state.

Fair Play Philosophy

We believe in proportional responses. First-time minor anomalies result in a warning. Repeated anomalies lead to result invalidation. Persistent cheating results in temporary suspensions. Permanent bans are reserved for the most egregious cases. All automated flags are reviewed by a human moderator before severe penalties are applied.


Scaling Strategies

Current Architecture

Currently, Puzzle PK runs on a single Go server that handles all WebSocket connections and game logic. Go's efficient memory model (each goroutine uses only about 4KB of stack space) allows a single server to handle approximately 50,000 concurrent WebSocket connections comfortably.

Horizontal Scaling Plan

As our player base grows, we plan to scale horizontally using the following approach:

Connection routing: A load balancer distributes incoming WebSocket connections across multiple Go server instances. Connections from players in the same room must be routed to the same server instance. We use consistent hashing on the room ID to achieve this.

Room migration: When a server becomes overloaded, rooms can be migrated to a less loaded server. The migration process involves serializing the room state, transferring it to the target server, and transparently reconnecting both players. The entire migration takes less than 200ms and is invisible to the players.

Shared state via Redis: For cross-server operations (like matchmaking, which needs to see all available rooms across all servers), we use Redis as a shared state store. Redis Pub/Sub is used for inter-server communication when a room spans servers during migration.

Geographic distribution: To minimize latency for players worldwide, we plan to deploy server instances in multiple regions (North America, Europe, Asia). Players are automatically connected to the nearest server. For cross-region PK matches, a relay server in a neutral location ensures fair latency for both players.

Database Scaling

PostgreSQL handles our current load comfortably, but we have prepared for growth:

  • Read replicas: Leaderboard queries and game history reads are directed to read replicas, keeping the primary database focused on writes.
  • Partitioning: Game history tables are partitioned by month, allowing old data to be archived efficiently.
  • Connection pooling: PgBouncer manages a pool of database connections, preventing connection exhaustion during traffic spikes.

Lessons Learned

Building a real-time multiplayer puzzle system taught us several valuable lessons:

1. Simplicity Wins

Our initial design included a complex event sourcing system with CQRS (Command Query Responsibility Segregation). After extensive prototyping, we simplified to a straightforward request-response model with optimistic updates. The simpler architecture was easier to debug, easier to reason about, and surprisingly performed better because it avoided the overhead of event replay.

2. Latency Budgets Matter

We established strict latency budgets for every component: WebSocket message processing must complete within 5ms, database queries within 10ms, and end-to-end move confirmation within 100ms. These budgets drove design decisions throughout the system — for example, they led us to pre-compute puzzle solutions at room creation time rather than validating moves against a solver in real time.

3. Test with Real Network Conditions

Our test suite includes network simulation tools that introduce artificial latency, packet loss, and connection drops. Testing with 200ms latency and 5% packet loss revealed several bugs that never appeared in local testing, including race conditions in the reconnection logic and state desynchronization under poor network conditions.

4. Monitor Everything

We instrument every component with detailed metrics: WebSocket message latency histograms, room lifecycle durations, game completion rates by type and difficulty, matchmaking queue times, and client-reported frame rates. These metrics have been invaluable for identifying performance bottlenecks and guiding optimization efforts.


What is Next

We are continually improving the PK system. Our roadmap includes:

  • Spectator mode: Allow friends to watch live PK matches with real-time commentary.
  • Tournament system: Automated bracket-style tournaments with leaderboard integration.
  • Team PK: 2v2 and 3v3 team matches where team members can assist each other.
  • Replay system: Watch and analyze completed matches, with move-by-move playback and analysis.
  • Mobile optimization: Further reducing bandwidth and latency for mobile players on cellular connections.

Frequently Asked Questions

Q: What programming languages and frameworks does Puzzle PK use? A: The frontend is built with Angular (TypeScript) and the backend is built with Go (Golang). We use PostgreSQL for the database and WebSocket for real-time communication.

Q: How does Puzzle PK ensure fair matches? A: Both players in a PK match receive the exact same puzzle, generated from a deterministic seed on the server. The server validates every move and tracks timing to detect automated solving.

Q: What is the difference between Speed PK and Steal PK? A: In Speed PK, players solve the same puzzle independently — the fastest solver wins. In Steal PK, players can interfere with each other through game-specific attack actions, adding a strategic layer on top of puzzle-solving skill.

Q: Can I play Puzzle PK on mobile devices? A: Yes! Puzzle PK is a Progressive Web App (PWA) that works on any modern browser, including mobile. The game interface is fully responsive and optimized for touch input.

Q: How does the anti-cheat system work? A: We use multiple layers: server-authoritative game state (clients cannot modify the state directly), timing analysis to detect automated solving, move pattern analysis to identify bots, and progress rate limiting to catch impossible solving speeds.


Conclusion

Building a real-time multiplayer system for 20 different puzzle games was one of the most challenging and rewarding engineering projects we have undertaken. The plugin-based architecture allowed us to scale from a single game to 20 without rewriting the core infrastructure, and the authoritative server model gives us confidence in the fairness and integrity of competitive matches.

If you want to experience the system firsthand, head over to Puzzle PK and challenge a friend — or a stranger — to a puzzle duel. Whether you prefer the pure speed test of Speed PK or the strategic chaos of Steal PK, there is a mode for every type of player.

We hope this technical deep-dive has been interesting and informative. If you have questions about our architecture or want to discuss real-time multiplayer systems, feel free to reach out through our contact page. Happy puzzling!

PK

Puzzle PK Team

The Puzzle PK Team is a group of puzzle enthusiasts crafting free, high-quality logic games and brain-training guides for players of all ages. Got feedback or ideas? We would love to hear from you.

More about Puzzle PK →
📱

Add to Home Screen for Quick Access

Enjoy native fullscreen & offline instant play