Command Palette

Search for a command to run...

Назад к скиллам
скилл № 08218

game-backend-architecture

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…

БесплатноЗапускает вложенные скрипты
fcsouzaот fcsouza★ 29 звёзд на GitHub

Установить game-backend-architecture в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

Game backend architecture

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.

Requires

  • betterauth-integration for the Better Auth instance, roles and trusted origins
  • redis-game-patterns for presence keys and per-action rate limits

Decisions

  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. This holds for session games, where a match has a fixed, small player count. It stops holding when one space must carry more players or entities than one process can tick in its budget; see "When one space outgrows a process".
  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. Browsers are checked by Origin plus the session cookie. Native clients (game-godot, game-unity) send no Origin and are checked by a bearer session.
  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.

Wiring the server

  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 is the function authorizeUpgrade, called from .derive() on its own Elysia instance, so it does not run on the mounted auth routes. The route never upgrades on a failure. A direct auth.api call skips Better Auth's own origin checks, which is why the server checks Origin itself.
    • With an Origin header (a browser): the origin must be in trustedOrigins, else 403. The session comes from the cookie or a bearer token, as getSession reads it. No session is 401.
    • Without an Origin header (a native client): the request must carry Authorization: Bearer <token>, and the session must come from that token alone, else 403. A cookie on such a request does not count. RFC 6455 says only browser clients must send Origin (section 4.1), and that the check is not meant to keep non-browsers out (section 10.2).
    • An Origin the client sets proves nothing, because only a browser guarantees it. An untrusted Origin is 403 even with a valid token.
    • The token is read from the Authorization header only, never from the query string: a URL ends up in access logs and proxies.
    • This needs the bearer() plugin on the Better Auth instance (betterauth-integration). The token is a session credential: a native client keeps it in the OS secure store (Keychain, Android Keystore), never in a URL, a log line or a crash report.
  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:
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);

Send the reason with a rejection; the client needs it to show the player why.

The tick loop

GameLoop adds real elapsed time to an accumulator and runs as many fixed dt steps as fit. The leftover stays for the next pass.

  • 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 broa
Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

  • boilerplate/fan-out.ts
  • boilerplate/game-loop.ts
  • boilerplate/room-manager.ts
  • boilerplate/server.ts
  • references/architecture.md
  • references/sources.md
  • templates/message-types.ts

FAQ

Что делает скилл game-backend-architecture?

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?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл game-backend-architecture запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить game-backend-architecture с