Building a real-time multiplayer browser game is one of the best crash tests a web developer can put themselves through. It instantly exposes every architectural trade-off you can easily ignore for years while building ordinary e-commerce sites or CRM dashboards.
Picture the task: you need to build a turn-based two-player card duel (in the spirit of Hearthstone or Magic: The Gathering). A player drags cards from their hand onto the board, casts fireballs, attacks enemy creatures, a turn timer ticks down, and an opponent halfway around the world needs to see smooth card movements and spell effects at a rock-steady 60–120 frames per second.
Most frontend devs' first instinct is to build the whole thing with their favorite stack: React, Framer Motion, and Tailwind CSS. Cards are just <div className="card">, the board is <div className="board">, dragging is react-dnd.
A couple of weeks into development, the project inevitably slams into two brick walls:
- The Performance Wall: when three spells go off at once, particle sparks fly everywhere, and a turn timer updates the DOM every second, the browser engine chokes on Recalculate Style, Layout, and Paint cycles. Frame rates plummet to a choppy 20–30 FPS.
- The Security Wall: if card cost and mana checks live only on the client, any player can open DevTools, call
playCard(legendaryDragon)with zero mana, and break the match.
Let's walk through an architectural recipe that solves both problems: splitting the interface between React and PixiJS 8, sharing an isomorphic state reducer in TypeScript, and enforcing strict move validation over WebSocket in Fastify.
Separation of Concerns: React + PixiJS
To eliminate DOM bottlenecks, you need to divide screen elements by their physical nature:
- Static UI (React DOM): player profile panel, avatars, health counter, text chat, Settings button, and tooltip modals. These elements change infrequently, don't need millisecond interpolation, and are great in standard HTML/CSS with proper accessibility (a11y).
- Dynamic game scene (PixiJS 8 on WebGL / WebGPU): the game board, cards in hand, projectile trajectories, glow effects, dissolve shaders, and drag physics. All of this rendering moves into a single
<canvas>element driven by the PixiJS graphics engine.
Patent blueprint of Redis RESP3 protocol parsing: a streaming state machine dissecting data type prefixes inside the libuv event loop.
PixiJS 8 talks directly to the GPU via WebGL or WebGPU, batching sprites and drawing thousands of interactive objects without touching the DOM tree once. The result is a locked 120 FPS even on mobile phones.
We also explored how declarative rules and state machines help structure complex interfaces in our piece on what web development can learn from gamedev.
The Architectural Core: An Isomorphic Deterministic Reducer
The most common mistake in networked games is duplicating game logic: writing the rules in TypeScript on the client and trying to mirror them in Python, Go, or Java on the backend. Sooner or later the rules drift apart, and you get desyncs.
The clean solution is an isomorphic pure reducer (Shared State Reducer) written in plain TypeScript. This module compiles into a shared NPM package imported by both the client web app and the Fastify backend service.
The reducer function is strictly deterministic:
duelReducer(currentState, action) -> newState
Given the exact same inputs, it always returns the exact same output with zero side effects.
Here's what the core reducer looks like:
// shared/duelReducer.ts — shared isomorphic module
export interface PlayerState {
id: string;
mana: number;
maxMana: number;
health: number;
hand: Card[];
board: Card[];
}
export interface GameState {
matchId: string;
turnPlayerId: string;
turnNumber: number;
players: Record<string, PlayerState>;
actionHistory: CardAction[];
}
export type CardAction =
| { type: 'PLAY_CARD'; playerId: string; cardId: string; targetId?: string; timestamp: number }
| { type: 'END_TURN'; playerId: string; timestamp: number };
export function duelReducer(state: GameState, action: CardAction): GameState {
switch (action.type) {
case 'PLAY_CARD': {
// 1. Check turn order
if (state.turnPlayerId !== action.playerId) {
throw new Error('Not your turn!');
}
const player = state.players[action.playerId];
const cardIndex = player.hand.findIndex(c => c.id === action.cardId);
// 2. Verify the card is in the player's hand
if (cardIndex === -1) {
throw new Error('Card is not in the player\'s hand');
}
const card = player.hand[cardIndex];
// 3. Check mana
if (player.mana < card.cost) {
throw new Error('Not enough mana to play this card');
}
// 4. Build the new immutable state
const nextHand = [...player.hand];
nextHand.splice(cardIndex, 1);
return {
...state,
players: {
...state.players,
[action.playerId]: {
...player,
mana: player.mana - card.cost,
hand: nextHand,
board: [...player.board, card]
}
},
actionHistory: [...state.actionHistory, action]
};
}
case 'END_TURN': {
const opponentId = Object.keys(state.players).find(id => id !== action.playerId)!;
const opponent = state.players[opponentId];
const nextMaxMana = Math.min(10, opponent.maxMana + 1);
return {
...state,
turnPlayerId: opponentId,
turnNumber: state.turnNumber + 1,
players: {
...state.players,
[opponentId]: {
...opponent,
maxMana: nextMaxMana,
mana: nextMaxMana
}
},
actionHistory: [...state.actionHistory, action]
};
}
default:
return state;
}
}
Server-Side Validation with Fastify and WebSocket
Never trust the client. The server acts as the incorruptible referee.
We use Fastify with the @fastify/websocket plugin, chosen for its minimal V8 event-loop overhead and high JSON serialization throughput.
Here's how an incoming game packet is handled on the server:
// server/gameSocket.ts
import Fastify from 'fastify';
import websocket from '@fastify/websocket';
import { duelReducer, GameState, CardAction } from '../shared/duelReducer';
const app = Fastify({ logger: true });
app.register(websocket);
// In-memory store of active game rooms
const activeMatches = new Map<string, GameState>();
app.register(async function (fastify) {
fastify.get('/ws/duel/:matchId', { websocket: true }, (connection, req) => {
const { matchId } = req.params as { matchId: string };
connection.socket.on('message', (rawMessage: string) => {
try {
const action: CardAction = JSON.parse(rawMessage.toString());
const currentState = activeMatches.get(matchId);
if (!currentState) {
connection.socket.send(JSON.stringify({ error: 'Match not found' }));
return;
}
// Run the shared reducer on the server!
// If the move is invalid, the reducer throws an exception
const nextState = duelReducer(currentState, action);
activeMatches.set(matchId, nextState);
// Broadcast the confirmed canonical state to all duel participants
broadcastToMatch(matchId, {
type: 'STATE_UPDATE',
state: nextState,
lastAction: action
});
} catch (err: any) {
// Illegal move: send a rollback signal
connection.socket.send(JSON.stringify({
type: 'REVERT_ACTION',
reason: err.message
}));
}
});
});
});
Optimistic Updates and Smooth Rollbacks
What does the player see when they drop a card onto the board? If you wait for a server round-trip (50–150 ms), the game will feel sluggish and unresponsive.
That's why the client uses Optimistic UI:
- The player releases the card: the client runs
duelReducerlocally, immediately starts the card-drop animation, and deducts mana in the UI. - In parallel, the WebSocket sends the
PLAY_CARDaction to the server. - The server approves the move and broadcasts confirmation: the client simply commits the transaction.
- If a rare desync occurs—or a cheater tried to spoof their mana—the server responds with
REVERT_ACTION. The client catches it and smoothly animates the card back into the hand alongside an error message.
This hybrid setup gives players instant tactile feedback and silky 120 FPS visuals while keeping competitive multiplayer completely honest and stable.

![Node.JS [ru]](/api/digests/it_development/daily/20261022/assets/sources/we-use-js.jpg?v=a0f44cd5adea38f5565ca34efcbf68f295fb7e34338ebf79f7f36277e0148001)
