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★ 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-integrationfor the Better Auth instance, roles and trusted originsredis-game-patternsfor presence keys and per-action rate limits
Decisions
- 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. - 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. - 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". - REST for durable, request-response work (create a room, read a profile, buy an item). WebSocket for the match: actions in, state deltas out.
- 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
Originplus the session cookie. Native clients (game-godot,game-unity) send noOriginand are checked by a bearer session. - 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
- Define the protocol first in
templates/message-types.ts. Every message is a member of a discriminated union ontype. Client messages are one TypeBox schema,clientMessage;ClientMessageis derived from it withStatic, andserver.tsvalidates with it, so malformed messages are rejected before your code sees them and the type cannot drift from the check. - Create the server with
createGameServer(auth, trustedOrigins), passing the Better Auth instance and the game client origins. Put the same origins in Better Auth'strustedOriginsoption. - 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 directauth.apicall skips Better Auth's own origin checks, which is why the server checksOriginitself.- With an
Originheader (a browser): the origin must be intrustedOrigins, else 403. The session comes from the cookie or a bearer token, asgetSessionreads it. No session is 401. - Without an
Originheader (a native client): the request must carryAuthorization: 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 sendOrigin(section 4.1), and that the check is not meant to keep non-browsers out (section 10.2). - An
Originthe client sets proves nothing, because only a browser guarantees it. An untrustedOriginis 403 even with a valid token. - The token is read from the
Authorizationheader 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.
- With an
- Put per-request values (the player id) in
.derive(), not instore.storeis one object shared by every request. - Write game logic in
RoomManager.tickRoomandprocessAction. 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.dtstays fixed.- After each tick the room diffs its state against the previous tick and broa
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- 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 запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
mcp-builder
AnthropicGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
claude-api
AnthropicReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
algorithmic-art
AnthropicCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
mcp-integration
AnthropicThis skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…