t1k:gamebackend:game-server:architecture
| Field | Value |
|---|---|
| Module | game-server |
| Version | 1.10.3 |
| Effort | medium |
| Tools | — |
Keywords: do hibernation billing, durable object game backend, game backend on cloudflare, per-player durable object, player durable object, playerdo class
How to invoke
Section titled “How to invoke”/t1k:gamebackend:game-server:architecture<decision | review | cost | limits>Game backend on Cloudflare: per-player Durable Object (decision record)
Section titled “Game backend on Cloudflare: per-player Durable Object (decision record)”Architecture decision record (ADR) for a mobile or casual game backend on Cloudflare, 10K to 1M DAU,
minimum maintenance. It is the SSOT for the decision and its invariants. Prices and the full
scenario tables live in core: t1k-datastore-cost, its per-player DO game-backend reference file (per-player-do-game-backend)
(SSOT for money, link to it, do not copy it here). Port a client contract: t1k-gamebackend-game-server-rest-contract-port.
Auth and IAP: t1k-gamebackend-game-server-auth-iap. Start a repo: t1k-gamebackend-game-server-template-bootstrap.
Deploy mechanics: core t1k-cloudflare (the cf CLI; wrangler is retired studio-wide).
Evidence labels used below
Section titled “Evidence labels used below”| Label | Meaning |
|---|---|
| measured | observed by running it locally (Miniflare/workerd), see references/measured-findings.md |
| published | stated on a Cloudflare page, [retrieved 2026-10-07], URLs in references/limits-and-prices.md |
| modelled | arithmetic over stated assumptions, not traffic |
| UNVERIFIED | read second-hand or not checked; do not build on it without a probe |
Decision tree
Section titled “Decision tree”| Question | Go to |
|---|---|
| “Is this the right stack for my game?” | Decision |
| “What does it cost at N DAU?” | Cost model and core’s reference |
| “Why is my Durable Object bill high?” | Hibernation |
| “What can one object / one DB do?” | references/limits-and-prices.md |
| “How should a client call fail / retry?” | Error contract |
| “Did my change break an invariant?” | rule gamebackend-game-server-invariants |
Decision
Section titled “Decision”client --HTTPS--> Worker `api` (stateless, verifies JWT first) |-- /connect/token, link ---> D1 `directory` (device/provider id -> playerId; written at register/link only) `-- player state ----------> PlayerDO (one SQLite Durable Object per player, getByName(playerId))- PlayerDO: one SQLite-backed Durable Object per player, addressed with
getByName(playerId). State is one row (a JSON blob) plus small append-only tables (mailbox, purchase events, idempotency ring). - D1
directory: only the identity index. Never player state. - Worker: stateless; authenticates before it touches any object; maps DO results to the client contract.
Why per-player objects
Section titled “Why per-player objects”- Single-writer per player. Input/output gates make read-modify-write race-free inside one object as long as no other awaited I/O sits between the read and the write (published). That replaces hand-written optimistic concurrency.
- Per-player restore. Point-in-time recovery per object for 30 days via
getBookmarkForTime(published). - Scales by adding objects, not by resharding: unlimited objects per namespace, 10 GB SQLite each (published).
- A D1 database IS a Durable Object (published). D1 does not escape the single-thread ceiling or per-row pricing; it adds a managed SQL layer at $0.75/GB-month versus $0.20 for DO SQLite storage.
Decision (2026-10-09): a game server is built ON the template core (GameServerTemplate: src/core plus the
game’s own src/game), never as a flat Worker written from scratch. The guards in
t1k-gamebackend-game-server-template-bootstrap -> references/core-guards-and-pull-flow.md live in core once, instead
of being re-found per game.
Decision (2026-10-21): a game’s server lives INSIDE the game repo, at server/. Default: the client
(Unity<Game>/ or the engine project) and the server are the same repository, server at the repo root subdirectory
server/. Not a separate repo, and never the repo of a reconstruction/prototype the game was ported from — that port is
evidence for the contract, not the home of the production server. Same tree
means one commit carries a contract change plus its client change, one PR review sees both sides of the wire, and
git log --follow server/ dates a route. Layout (all server paths below are relative to server/):
package.json, cloudflare.config.ts, src/{core,game}/, migrations/NNNN_*.sql, test/{core,game,support}/,
docs/{RUNTIME.md,migration/}, scripts/, README.md, AGENTS.md, .template-pin.json + core-files.sha256 when
the core is vendored.
Exception, and it needs an issue. A separate server repo is correct only when the backend is shared by more than
one game (one account/economy plane for a title family) — a shared backend is not “a game’s server” and must not live
inside one game’s tree. Take that exception with an issue on the server repo stating which games share it and who owns
it; do not split a single game’s server out on convenience, repo-size or “cleaner separation” grounds. The SteelBorn
port that predates this decision held its server in the reconstruction repo; the production default is server/ in the
game repo. Setup, rename and deploy: t1k-gamebackend-game-server-template-bootstrap.
Rejected alternatives
Section titled “Rejected alternatives”| Alternative | Why not |
|---|---|
| Sharded D1 | 15-20% cheaper in the model, but no per-player restore, painful resharding, whole-shard Time Travel only, hand-written optimistic concurrency |
| Many players per DO | single-thread ceiling ~1,000 req/s per object makes hot spots |
| WebSocket per player for the core loop | billing trap, see Hibernation |
| Alarms or timers per player | pin the object, bill duration; compute offline progress lazily from timestamps instead |
Route families
Section titled “Route families”| Family | Path |
|---|---|
| Auth, login, link | Worker -> D1 directory -> signed token |
| Player state (sync, claim, upgrade, purchase, inbox) | Worker -> PlayerDO RPC; one state row, idempotency ring, client sequence number; lazy offline progress; no alarms, timers, WebSocket or waitUntil fetches |
| IAP receipt verification | PlayerDO -> Queue (batched) -> consumer verifies with the store, calls back. Never await the vendor fetch inside the DO |
| Config, catalog, localisation | versioned JSON in R2 behind a custom domain with Cache Rules; KV only for small flags |
| Leaderboards | PlayerDO reports score (throttled) -> Queue -> consumer batch-upserts D1 ranks; Cron every 1-5 min writes top-N + percentile bands to R2; clients read via CDN; “your rank” interpolated from bands |
| Guild, social | D1 directory + one GuildDO per guild (Hibernation WebSocket API only here) |
| Telemetry | client batches one request per session; a Worker calls writeDataPoint up to 250 times -> Analytics Engine |
A mailbox is a pull model: global service mails as one manifest (R2/CDN or D1) with a per-player cursor copied at login; targeted mails go into the PlayerDO. Never fan a write out to 1M players.
Cost model (modelled)
Section titled “Cost model (modelled)”Assumptions are the model’s, not measurements: 30 days; one Worker request plus one DO RPC per client request; no WebSockets; registered players 3-5x DAU; peak 5x average; concurrent ~10% of DAU (UNVERIFIED ratio).
| DAU | LOW (DO / sharded D1) | MID | HIGH | OPT |
|---|---|---|---|---|
| 10K | 10 / 8 | 27 / 20 | 574 / 256 | 17 / 13 |
| 100K | 97 / 71 | 583 / 512 | 6,230 / 3,033 | 219 / 176 |
| 1M | 1,443 / 1,181 | 6,328 / 5,590 | 62,913 / 30,922 | 2,680 / 2,228 |
Monthly USD, Oct 2026 prices. Scenario definitions are in core’s reference. A second model with other assumptions
(references/measured-findings.md § “Second cost model”) lands in the same order of magnitude; the lesson both share
is that requests per DAU decides the bill (a 12x spread between an unoptimized and an optimized client).
Levers, in order: (1) cut request count, ~$0.45/M requests before CPU; (2) one row per save, no secondary indexes on state rows (an indexed write counts 2 rows); (3) keep every object hibernation-eligible; (4) sample Workers Logs (unsampled invocation logs at 1M DAU ~ $2,690/mo, 5% ~ $123); (5) serve static config from R2 behind the CDN or as Workers static assets, not through a Worker.
Hibernation: what pins an object (published)
Section titled “Hibernation: what pins an object (published)”A hibernateable object hibernates after 10 s idle; a non-hibernateable idle object is evicted after 70-140 s. An idle object that is eligible for hibernation is not billed for duration. Each of these pins the object and bills duration, so none may appear in a PlayerDO:
setTimeout/setInterval- an unfinished
waitUntil - an open outbound connection, for example awaiting a vendor
fetchinside the DO - the standard WebSocket
accept()API (use the Hibernation WebSocket API, and only for chat or guild)
Each pending I/O can pin an object for up to 15 minutes. WebSocket billing trap: an always-on non-hibernating
socket is ~$4.12 per connection-month: ~$40K/mo at 10K concurrent, ~$405K/mo at 100K concurrent; 40 min/day of such
sockets at 1M DAU is ~$112K/mo. Duration spans three orders of magnitude ($23 LOW to ~$30,000 HIGH) with
hibernation discipline alone. blockConcurrencyWhile across I/O is an anti-pattern.
Error contract (published)
Section titled “Error contract (published)”error.retryable === true: retry with backoff on a fresh stub, with a small cap (SteelBorn uses 3 attempts, 25 ms then 100 ms).error.overloaded === true: never retry; return HTTP 503 +Retry-After.- D1 “overloaded” or “Too many requests queued” are not retryable: do less work or shard.
- An account-level “generating too much load” throttles stub creation (rate UNVERIFIED).
- Return a discriminated result from the DO (
{ok:true,value}/{ok:false,code}), not a thrown error, so a domain error code survives the RPC boundary intact.
Placement, deploys, backups (published)
Section titled “Placement, deploys, backups (published)”- Objects are created near the first request; location hints are best-effort; jurisdictions (eu, us, fedramp) are enforced; objects never relocate.
- Deploys are eventually consistent for seconds to minutes: a new Worker can call an object running old code. Keep the Worker-to-DO API backward AND forward compatible.
- A Worker rollback cannot cross a DO class lifecycle change. Renaming or deleting a class declaration destroys
data and PITR does not help; treat the
exportsblock ofcloudflare.config.tsas append-only. - No documented bulk export of DOs. D1 directory: Time Travel 30 days (whole-database restore) plus a Cron export to R2; the export blocks other requests while it runs.
- Migrate player data lazily on read: a version number inside the blob plus
PRAGMA user_versionfor table definitions. No known way to run a migration across every object at once.
UNVERIFIED (keep marked)
Section titled “UNVERIFIED (keep marked)”DO cold-start latency from distant regions; stub-creation throttle rate; whether DO and D1 included allowances stack; whether DO storage billing is active (the page says January 2026); whether a large-blob UPDATE is one row written on production (measured 1 row locally, see measured-findings); Rate Limiting binding pricing; when Analytics Engine billing starts; the DAU-to-concurrent ratio; real DO duration per request (needs a 100K-object soak); PITR price. Game-specific evidence is thin: no published idle-game backend at 100K+ DAU on Cloudflare was found.
Related
Section titled “Related”Core: t1k-datastore-cost (money SSOT, request-volume audit), t1k-cloudflare (cf CLI, gaps). Sibling skills of this module: see the header.