game-backend-architecture · diff
git:20261114.b353ad0 to git:20261114.1296d8c
67 added, 265 removed. Audit A to A.
What this update changes in the checks
No check changed: every fixed check gives the same answer before and after this update.
A tripped check is a label, not a verdict: read the matched text and the lines below. This week's updates that newly trip a check.
---
name: game-backend-architecture
description: >-
- Use when building game servers, WebSocket connections, room management, game tick loops, or server-authoritative architecture with Elysia. Triggers: game server, WebSocket, rooms, tick loop, server architecture, multiplayer backend.
+ Covers the server side of a real-time game on Bun and Elysia: server-authoritative rooms, a fixed-timestep tick loop with a spiral-of-death cap, delta broadcasts over WebSocket, a session check on the WebSocket upgrade, and Redis fan-out between server instances. Use when a multiplayer or real-time game needs a game server, match rooms, a server tick loop, state pushed from server to clients, or more than one server instance.
---
- # Game Backend Architecture
-
- ## Purpose
-
- WebSocket + REST patterns, room/session management, game tick loops, genre-agnostic server design using Elysia + Bun. Covers server-authoritative architecture, fixed-timestep simulation, room lifecycle, typed message protocols, and horizontal scaling via Redis pub/sub.
-
- ## When to Use
-
- Trigger: game server, backend architecture, WebSocket, room management, game loop, tick system, server-authoritative, real-time, Elysia game server, multiplayer backend, session management, game tick, fixed timestep server
-
- ## Prerequisites
-
- - `postgres-game-schema` — database layer for persistent game state
- - `redis-game-patterns` — caching, pub/sub, presence, and ephemeral state
-
- ## Core Principles
-
- > "I'm not interested in creating a game that does things for the player. I want to create a simulation that responds to the player." — Will Wright
-
- > "A game is a series of interesting decisions." — Sid Meier
-
- The server is a simulation system that responds to player intentions and produces meaningful state changes. Every design decision should preserve determinism, enforce authority, and keep the door open for any genre.
-
- 1. **Server-authoritative**: the client sends intentions (actions), the server validates and executes. Never trust the client.
- 2. **Separate simulation loop from I/O**: the game tick runs on a fixed timestep independent of network or render cycles.
- 3. **Fixed timestep for deterministic game logic**: same inputs at the same tick always produce the same output, enabling replays, rollback, and offline catchup.
- 4. **Room-based architecture for multiplayer isolation**: each room encapsulates its own state, tick loop, and player set. Rooms are the unit of scaling.
- 5. **Stateless REST for CRUD, WebSocket for real-time state**: use REST for durable operations (create account, save inventory, fetch leaderboard) and WebSocket for ephemeral, high-frequency updates (game state, actions, presence).
- 6. **Event-driven**: game actions produce events, systems consume them. Decouple producers from consumers for testability and extensibility.
- 7. **Horizontal scaling via Redis pub/sub**: multiple Elysia instances share state through Redis. Any instance can handle any player; cross-server communication uses pub/sub channels.
-
- ## Step-by-Step Instructions
-
- ### 1. Define the Message Protocol
-
- Start with `templates/message-types.ts`. Define discriminated unions for every client-to-server and server-to-client message. This is the contract between frontend and backend — get it right first.
-
- ```typescript
- import type { ClientMessage, ServerMessage } from './templates/message-types';
- ```
-
- ### 2. Set Up the Elysia Server
-
- Use `boilerplate/server.ts` as the entry point. It wires together:
- - REST routes for CRUD operations (players, sessions, inventory)
- - A WebSocket endpoint with JWT authentication
- - Message routing to the room manager
-
- ```bash
- bun run boilerplate/server.ts
- ```
-
- ### 3. Implement Room Management
-
- Use `boilerplate/room-manager.ts`. The room manager handles:
- - Creating and destroying rooms
- - Joining and leaving players
- - Broadcasting messages to room members
- - Room lifecycle transitions (created -> active -> closing -> closed)
-
- Each room owns its game state and tick loop instance.
-
- ### 4. Configure the Game Loop
-
- Use `boilerplate/game-loop.ts`. The `GameLoop` class provides:
- - Fixed-timestep accumulator pattern
- - Configurable tick rate (default 20 TPS for most genres)
- - Speed multiplier for fast-forward or slow-motion
- - Delta time overflow protection (caps accumulated time to prevent spiral of death)
-
- Attach one `GameLoop` per room. The tick callback receives `dt` in seconds and updates room state.
-
- ### 5. Wire Room State to WebSocket Broadcasts
-
- After each tick, diff the room state and broadcast deltas to all room members:
-
- ```typescript
- room.gameLoop.onTick = (dt) => {
- room.state = updateGameState(room.state, dt);
- const delta = computeDelta(room.previousState, room.state);
- if (delta) {
- room.broadcast({ type: 'state_update', roomId: room.id, state: delta, tick: room.tick });
- }
- room.previousState = structuredClone(room.state);
- room.tick++;
- };
- ```
-
- ### 6. Add Redis Pub/Sub for Scaling
-
- When running multiple Elysia instances behind a load balancer:
-
- ```typescript
- import { Redis } from 'ioredis';
-
- const pub = new Redis(process.env.REDIS_URL!);
- const sub = new Redis(process.env.REDIS_URL!);
-
- sub.subscribe('game:broadcast', 'game:direct');
- sub.on('message', (channel, message) => {
- const parsed = JSON.parse(message);
- if (channel === 'game:broadcast') {
- server.publish(parsed.channel, parsed.data);
- }
- if (channel === 'game:direct') {
- const ws = connections.get(parsed.userId);
- if (ws) ws.send(parsed.data);
- }
- });
- ```
-
- ### 7. Implement Presence and Heartbeat
-
- - Client sends `ping` every 30 seconds
- - Server responds with `pong` + server timestamp
- - If no ping within 90 seconds, mark player offline and clean up room membership
- - Store presence in Redis with TTL for automatic expiry
-
- ## Code Examples
-
- ### Fixed-Timestep Server Loop
-
- ```typescript
- const TICK_RATE = 20;
- const TICK_DURATION_MS = 1000 / TICK_RATE;
-
- const loop = new GameLoop(TICK_RATE, (dt) => {
- for (const room of roomManager.getActiveRooms()) {
- room.update(dt);
- room.broadcastState();
- }
- });
-
- loop.start();
- ```
-
- ### Server-Authoritative Action Processing
-
- ```typescript
- const processAction = (
- room: Room,
- playerId: string,
- action: { type: string; payload: Record<string, unknown> },
- ): ActionResult => {
- // 1. Validate: is this action legal in current state?
- const validation = validateAction(room.state, playerId, action);
- if (!validation.valid) {
- return { success: false, error: validation.reason };
- }
-
- // 2. Execute: apply to authoritative state
- const events = applyAction(room.state, playerId, action);
-
- // 3. Broadcast: notify all room members of resulting events
- for (const event of events) {
- room.broadcast({
- type: 'game_event',
- event: event.type,
- data: event.data,
- tick: room.tick,
- });
- }
+ # Game backend architecture
- return { success: true, events };
- };
- ```
+ The boilerplate targets `elysia` 1.4.32. Use the `elysiajs` skill if it is installed, otherwise https://elysiajs.com, and check which Elysia major the project runs: the Elysia 2 beta rewrites the WebSocket API, so the `.ws()` code here does not carry over unchanged.
- ### Room-Scoped State Update
+ ## Requires
- ```typescript
- const updateRoomState = (room: Room, dt: number) => {
- // Run all registered systems in order
- for (const system of room.systems) {
- system.update(room.state, dt);
- }
+ - `betterauth-integration` for the Better Auth instance, roles and trusted origins
+ - `redis-game-patterns` for presence keys and per-action rate limits
- // Process queued player actions
- while (room.actionQueue.length > 0) {
- const { playerId, action } = room.actionQueue.shift()!;
- processAction(room, playerId, action);
- }
+ ## Decisions
- room.tick++;
- };
- ```
+ 1. The server is the authority. A client sends what it wants to do (`move north`), never the result (`I am at 100, 200`). The server validates the action against its own state, applies it, and tells clients what happened.
+ 2. Game logic runs on a fixed timestep, separate from network I/O. Every tick sees the same `dt`, so the same inputs give the same result.
+ 3. A room owns its state, its action queue, its player set and its `GameLoop`. Rooms share nothing, and one room runs on one server instance.
+ 4. REST for durable, request-response work (create a room, read a profile, buy an item). WebSocket for the match: actions in, state deltas out.
+ 5. Authenticate once, on the WebSocket upgrade, from the Better Auth session. The player id comes from that session for the life of the socket, never from a message.
+ 6. Default to 20 ticks per second. One tick then has a 50 ms budget for every room on the instance. Pick another rate per room when the genre needs it.
- ### WebSocket Message Routing
+ ## Files
- ```typescript
- const handleMessage = (ws: GameWebSocket, data: ClientMessage) => {
- const { playerId } = ws.data;
+ - `boilerplate/server.ts`: copy when wiring the server. It mounts the Better Auth handler, checks `Origin` and the session in `.derive()` on the upgrade, and routes WebSocket messages to the room manager.
+ - `boilerplate/room-manager.ts`: copy when adding rooms. Read when plugging in game logic: `tickRoom` and `processAction` are the hooks.
+ - `boilerplate/game-loop.ts`: copy when a room needs its tick loop; it needs no changes.
+ - `boilerplate/fan-out.ts`: copy when you run more than one server instance.
+ - `templates/message-types.ts`: copy when defining the client-server protocol; extend the unions with your game's messages.
+ - `references/architecture.md`: read when you need the connection flow or room lifecycle as a diagram.
+ - `references/sources.md`: read when you need the page behind a rule here.
- switch (data.type) {
- case 'join_room':
- roomManager.joinRoom(data.roomId, playerId, ws);
- break;
- case 'leave_room':
- roomManager.leaveRoom(data.roomId, playerId);
- break;
- case 'action':
- roomManager.queueAction(data.roomId, playerId, data.action);
- break;
- case 'ping':
- ws.send(JSON.stringify({ type: 'pong', serverTime: Date.now() }));
- break;
- }
- };
- ```
+ ## Wiring the server
- ### Delta State Synchronization
+ 1. Define the protocol first in `templates/message-types.ts`. Every message is a member of a discriminated union on `type`. Client messages are one TypeBox schema, `clientMessage`; `ClientMessage` is derived from it with `Static`, and `server.ts` validates with it, so malformed messages are rejected before your code sees them and the type cannot drift from the check.
+ 2. Create the server with `createGameServer(auth, trustedOrigins)`, passing the Better Auth instance and the game client origins. Put the same origins in Better Auth's `trustedOrigins` option.
+ 3. The upgrade check lives in `.derive()` on its own Elysia instance, so it does not run on the mounted auth routes. It returns 403 for an untrusted `Origin` and 401 without a session, and the route never upgrades. A direct `auth.api` call skips Better Auth's own origin checks, which is why the server checks `Origin` itself.
+ 4. Put per-request values (the player id) in `.derive()`, not in `store`. `store` is one object shared by every request.
+ 5. Write game logic in `RoomManager.tickRoom` and `processAction`. The pattern for one action:
```typescript
- const computeDelta = (
- previous: Record<string, unknown>,
- current: Record<string, unknown>,
- ): Record<string, unknown> | null => {
- const delta: Record<string, unknown> = {};
- let hasChanges = false;
-
- for (const key of Object.keys(current)) {
- if (JSON.stringify(previous[key]) !== JSON.stringify(current[key])) {
- delta[key] = current[key];
- hasChanges = true;
- }
- }
-
- return hasChanges ? delta : null;
- };
+ const result = validateAction(room.gameState, queued.playerId, queued.action);
+ if (!result.valid) {
+ this.sendToPlayer(room.id, queued.playerId, {
+ type: 'action_result',
+ action: queued.action.type,
+ success: false,
+ data: { reason: result.reason },
+ });
+ return;
+ }
+ applyAction(room.gameState, queued.playerId, queued.action);
```
- ## Cross-References
-
- - **`redis-game-patterns`** — presence storage, pub/sub for cross-server communication, room state caching, rate limiting
- - **`bullmq-game-queues`** — offload heavy computations (matchmaking, leaderboard recalc, scheduled events) to background workers
- - **`game-state-sync`** — client-side state reconciliation, interpolation, optimistic updates, rollback
- - **`postgres-game-schema`** — persistent storage for player profiles, inventory, match history, room configurations
-
- ## Pitfalls & Anti-Patterns
-
- ### 1. Client-Authoritative State
- **Wrong**: client sends "my position is (100, 200)" and server trusts it.
- **Right**: client sends "move north" intention, server validates movement speed, collision, and updates position.
+ Send the reason with a rejection; the client needs it to show the player why.
- ### 2. Variable Timestep for Game Logic
- **Wrong**: using wall-clock delta time directly in game formulas.
- **Right**: fixed-timestep accumulator — game logic always sees the same `dt`, regardless of how fast the server runs.
+ ## The tick loop
- ### 3. Global State Instead of Room Isolation
- **Wrong**: single shared game state object for all players.
- **Right**: each room owns its state, tick loop, and player set. Rooms are independent simulation contexts.
+ `GameLoop` adds real elapsed time to an accumulator and runs as many fixed `dt` steps as fit. The leftover stays for the next pass.
- ### 4. Synchronous Database Writes in the Tick Loop
- **Wrong**: `await db.update(players).set(...)` inside the tick callback.
- **Right**: batch state changes and persist asynchronously outside the tick loop (e.g., every N ticks or on room close).
+ - The elapsed time fed into one pass is capped at 250 ms. Without a cap, a slow tick makes the next pass run more steps, which makes it slower still: the spiral of death. With the cap, a long stall slows the game down instead of freezing it.
+ - `setSpeed()` scales elapsed time, for fast-forward or slow motion. `dt` stays fixed.
+ - After each tick the room diffs its state against the previous tick and broadcasts only the changed top-level keys as `state_update`. Removed keys arrive as `null`. Diffing against the previous tick is safe because WebSocket runs on TCP and delivers every message in order; over an unreliable transport, encode against the client's acknowledged snapshot instead (`game-state-sync`, step 3). Send the full state again when a client reconnects (`room_joined` carries it).
+ - A throw in a room's tick or in `processAction` stops that room's loop, is logged, and closes that room. Other rooms keep running.
- ### 5. Broadcasting Full State Every Tick
- **Wrong**: sending the entire game state to every player on every tick.
- **Right**: compute deltas and only send what changed. Use interest management to filter updates per player.
+ ## More than one instance
- ### 6. No Overflow Protection
- **Wrong**: accumulator grows unbounded when server lags, causing hundreds of catch-up ticks.
- **Right**: cap accumulated time (e.g., 1 second max) to prevent spiral of death.
+ A room lives in one instance's memory. Route every player of a room to the instance that holds it: return that instance's address when the room is created, or route on the room id at the load balancer.
- ### 7. Tight Coupling Between Message Types and Game Logic
- **Wrong**: game systems import WebSocket types and send messages directly.
- **Right**: game systems produce events, a separate broadcast layer translates events to WebSocket messages.
+ Create one ioredis client when the server starts (`new Redis(redisUrl)`, with a `redis://` URL) and pass it to `createFanOut` and to the `redis-game-patterns` helpers. Use `boilerplate/fan-out.ts` only for messages that cross instances: a direct message to a player connected elsewhere, a server-wide announcement, or closing a banned player's sockets on every instance (a ban revokes sessions, but an open socket stays open until the server closes it). Implement `LocalDelivery` with a map from player id to socket that `open` fills and `close` clears.
- ### 8. No Graceful Room Shutdown
- **Wrong**: rooms disappear instantly when the last player leaves, losing unsaved state.
- **Right**: transition through closing state — persist state, notify players, clean up resources, then destroy.
+ Redis Pub/Sub delivers at most once. A message published while an instance is down or reconnecting is lost. Send match results, rewards and purchases through a queue (`bullmq-game-queues`), not through fan-out.
- ## Designer Philosophy
+ ## Heartbeat and presence
- **Will Wright's Simulation Thinking**: the server is not a script executor — it is a simulation. Players interact with systems that have emergent behavior. The server defines rules and constraints; the interesting outcomes arise from player interactions within those rules. Design your tick loop as a simulation step, not a sequence of hardcoded events.
+ The client sends `ping`; the server answers `pong` with its time. On each ping, refresh the player's presence key with a TTL of a few heartbeat intervals (`redis-game-patterns`, presence pattern). A missing key means offline, so a crashed client needs no cleanup message. When the socket closes, `close` removes the player from every room that socket is in. After a reconnect the new socket replaces the old one in the room, so the old socket's late `close` leaves the player in place (the room compares socket ids).
- **Sid Meier's Interesting Decisions**: every message from the client represents a decision. The server's job is to make that decision meaningful by enforcing constraints (can you afford this action?), producing consequences (what happens as a result?), and communicating outcomes (what changed?). If an action has no validation and no consequence, it is not an interesting decision — remove it or make it matter.
+ ## Pitfalls
- **Practical Implications**:
- - Validation is gameplay. Rejection messages should explain *why* an action failed, giving players information for their next decision.
- - Events are the language of consequence. When an action produces events that other systems consume, you get emergent complexity without writing combinatorial logic.
- - The tick loop is your simulation clock. Everything that "happens" in the game happens during a tick. Between ticks, the game world is frozen and consistent.
+ - Trusting the client's state. Move, damage, inventory and score changes are computed on the server.
+ - Variable `dt` in game formulas. Game logic must see the fixed step, not wall-clock time.
+ - One global game state instead of rooms.
+ - Awaiting a database write inside a tick. Persist on room close or every N ticks, outside the tick callback.
+ - Broadcasting full state every tick. Send deltas; filter by what each player can see when the state is large.
+ - No cap on elapsed time per pass (spiral of death).
+ - Game systems that import WebSocket types and send messages. Systems change state and emit events; the room turns them into messages.
+ - Destroying a room the moment it empties. Go through `closing`: stop the loop, persist, notify, then delete.
+ - Reading the player id from a client message, or reading the session per message instead of once per upgrade.
+ - Forgetting that the session check runs once. Ban and logout do not close sockets that are already open; use the `kick` fan-out message.
- ## Sources
+ ## Related skills
- - Glenn Fiedler, "Fix Your Timestep!" — https://gafferongames.com/post/fix_your_timestep/
- - Gabriel Gambetta, "Fast-Paced Multiplayer" — https://www.gabrielgambetta.com/client-server-game-architecture.html
- - Elysia documentation — https://elysiajs.com/
- - Redis pub/sub documentation — https://redis.io/docs/manual/pubsub/
- - Will Wright, GDC talks on simulation design
- - Sid Meier, GDC 2012, "Interesting Decisions"
+ - `game-state-sync` for the client side: prediction, reconciliation, interpolation
+ - `bullmq-game-queues` for heavy or must-not-lose work off the tick loop
+ - `postgres-game-schema` for player profiles, inventory and match history
+ - `matchmaking-system` for filling rooms