One process, one port, forty players

One Bun process serves SSR pages, the tRPC API and Colyseus game rooms on a single port, with Vite HMR sharing it in development.

The Act II desert town at dusk, palms around an oasis inside sandstone walls
Contents
  1. The mount order is the architecture
  2. Two consumers on one upgrade event
  3. Matchmaking is plain HTTP
  4. Accounts are a bearer token
  5. A room is a world
  6. zod at every edge
  7. Saves, evictions and shutdown
  8. Migrations, not db push
  9. Shipping it
  10. The blog rides the same server
  11. What one process gives up
  12. Read next

Pages, tRPC, matchmaking and every game websocket run in one Bun process on one port: bun --watch server.ts on 4477 in dev, bun server.ts in a container in prod. No separate game server, gateway or sidecar.

The starter template already put Express, Vite SSR and tRPC on one port. Colyseus fits in the same process only if it's wired in by hand instead of owning the HTTP server.

A diagram of one Bun process: Express handling requests in mount order, an upgrade filter sending game sockets to Colyseus and HMR sockets to Vite, with the matchMaker, the hub and Postgres on the right
The whole backend. One http.Server has one listener for requests and one for websocket upgrades. Everything else is in-process state.

The mount order is the architecture

server.tsTypeScript
const app = express()
const httpServer = http.createServer(app)
 
app.get('/healthz', async (_req, res) => { /* SELECT 1 */ })
 
// Colyseus: websocket upgrades on /<processId>/<roomId> + HTTP matchmaking on /matchmake/*
const game = await createGameServer(httpServer)
app.use(game.matchmaking)
 
app.get('/api/status', async (_req, res) => res.json(await gameStatus()))
app.use('/api/trpc', createExpressMiddleware({ router: appRouter, createContext }))
 
if (!isProd) {
  vite = await createViteServer({ server: { middlewareMode: true, hmr: { server: httpServer } }, appType: 'custom' })
  app.use(vite.middlewares)
} else {
  app.use(compression(), express.static('dist/client', { index: false, redirect: false }))
}
 
app.get('/blog/rss.xml', /* rendered from the SSR bundle */)
app.use(/* SSR catch-all */)
 
httpServer.listen(PORT)
  • Non-page endpoints go before the catch-all, which renders React Router for any extension-less GET.
  • The catch-all refuses what it shouldn't render. /api/* misses get a JSON 404; anything with a file extension gets a plain 404. A missing favicon.ico shouldn't cost a React render.
  • Vite xor static. Dev: Vite middleware plus HMR on our httpServer. Prod: compressed dist/client, a year of immutable caching on hashed /assets.
  • redirect: false exists for this blog. Without it, serve-static sees public/blog/<slug>/ and answers 301 → /blog/<slug>/ before SSR runs, in prod only.

Two consumers on one upgrade event

Node emits websocket handshakes as upgrade events, and in dev both Vite HMR and Colyseus listen. new Server({ server }).listen() would install its own request listener, add CORS headers and claim /, so the parts are assembled by hand:

server/game/index.tsTypeScript
const COLYSEUS_WS_PATH = /^\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/?$/
 
export async function createGameServer(httpServer: HttpServer): Promise<GameServer> {
  await matchMaker.setup()
 
  const transport = new WebSocketTransport({ noServer: true, pingInterval: 5000, pingMaxRetries: 3 })
  transport.attachToServer(httpServer, {
    filter(req) {
      if (req.headers['sec-websocket-protocol'] === 'vite-hmr') return false
      const { pathname } = new URL(req.url ?? '/', 'http://localhost')
      return COLYSEUS_WS_PATH.test(pathname)
    },
  })
  setTransport(transport)
 
  matchMaker.defineRoomType('zone', ZoneRoom).filterBy(['zoneId', 'difficulty', 'privateKey'])
  matchMaker.defineRoomType('house', HouseRoom).filterBy(['ownerCharacterId'])
  await matchMaker.accept()
 
  const nodeMiddleware = createNodeMatchmakingMiddleware()
  const matchmaking: RequestHandler = (req, res, next) => { nodeMiddleware(req, res, next).catch(next) }
  // …
}

Vite always sends Sec-WebSocket-Protocol: vite-hmr; Colyseus always connects to exactly /<processId>/<roomId>. Giving HMR its own port would skip the filter but cost a second port per checkout, so two copies couldn't run side by side on different PORTs. One if was cheaper.

Matchmaking is plain HTTP

Joining is two requests: POST /matchmake/joinOrCreate/zone reserves a seat in a room matching filterBy, then the client opens /<processId>/<roomId> and onAuth runs before anything is sent.

A sequence diagram: the browser creates a guest and a character through tRPC, reserves a seat over HTTP, then upgrades to a websocket where onAuth checks the token and character before the full state arrives
From a fresh visitor to a live room. Timings are the medians of six runs against a local dev server.
Step (median of six, local) Time
Create guest ~1.5 ms
Create character ~4 ms
joinOrCreate, room exists ~7 ms
joinOrCreate, new room (map generation) ~20 ms
First full state after join < 1 ms

The matchmaker is ordinary Express middleware, so it shares logging, error formatting and origin. The client needs no URL config:

src/game/net/zoneClient.tsTypeScript
/** One SDK client per page; same origin as the app (Colyseus shares the HTTP port). */
export function getColyseusClient(): Client {
  client ??= new Client(window.location.origin)
  return client
}

Accounts are a bearer token

No email, no cookie. "Enter the Reach" calls account.createGuest: 32 random bytes as hex, stored in localStorage['gr.token']. Claiming adds a username and a Bun.password hash for other devices.

server/auth.tsTypeScript
/** Parse `Authorization: Bearer <token>`; null if absent/malformed. */
export function bearerToken(header: string | undefined): string | null {
  if (!header) return null
  const m = /^Bearer\s+([a-f0-9]{64})$/i.exec(header.trim())
  return m?.[1] ?? null
}

tRPC reads the header in createContext. Browsers can't set websocket headers, so Colyseus gets the token as a join option:

server/game/rooms/ZoneRoom.tsTypeScript
async onAuth(_client: ZoneClient, rawOptions: unknown, context: AuthContext): Promise<AuthData> {
  const parsed = joinOptionsSchema.safeParse(rawOptions)
  if (!parsed.success) throw new ServerError(400, 'bad join options')
  const opts = parsed.data
  let account: Account | null
  let character: LoadedCharacter | null
  try {
    account = await accountFromToken(opts.token)
    character = account ? await loadCharacter(opts.characterId, account.id) : null
  } catch (e) {
    // Never leak DB/zod internals to the client.
    log.error(`[zone] onAuth failed: ${formatError(e)}`)
    throw new ServerError(500, 'could not load character')
  }
  if (!account) throw new ServerError(401, 'invalid token')
  if (!character) throw new ServerError(403, 'character not found on this account')
  // …
}

Cost: SSR never knows the user. useToken() returns undefined through SSR and hydration so markup matches, then string | null:

src/lib/use-token.tsTypeScript
export function useToken(): string | null | undefined {
  return useSyncExternalStore(subscribeToken, getToken, () => undefined)
}

Landing, blog and ladder are public anyway, and /play mounts client-side only.

A room is a world

Each ZoneRoom is one zone instance, capped at ROOM_MAX_CLIENTS = 40, with its own map, nav grid, monsters, loot and 20 Hz tick. Empty rooms dispose after 60 s. See Twenty ticks a second.

Parties, whispers, town portals and stash locks cross rooms. They live in hub.ts, a module-level registry:

server/game/hub.tsTypeScript
export interface RoomHandle {
  roomId: string
  zoneId: string
  /** deliver an event to one character in this room; false if they aren't here */
  send<K extends ServerEventName>(characterId: string, type: K, payload: ServerEvents[K]): boolean
  broadcast<K extends ServerEventName>(type: K, payload: ServerEvents[K]): void
  setParty(characterId: string, partyId: string | null): void
  portalsChanged(): void
  // …
}

One process means the hub is a Map. A zone transfer is hub.setPending(characterId, …) in the old room and hub.peekPending in the new room's onAuth. A join to an unexpected zone with no pending entry is admitted and immediately sent a transfer back to the saved zone.

Forty heroes in the Act I town square at night, lamps lit, a waypoint glowing at the top
A full room. Every one of these heroes is a separate websocket on the same process as the page you are reading.

Cap check: 39 headless @colyseus/sdk bots (moving, fighting, drinking potions) plus a headless browser in one Blighted Fields instance, 75 seconds:

Metric Value
Tick average 1.55 ms
Tick worst-window p95 4.78 ms
Worst single tick 11.08 ms
Downstream per client 8.8 KB/s, ~22 msg/s
Browser client 60 fps, 240 draw calls
The fortieth player in a bot-filled Blighted Fields instance, with another hero nearby and a party-up prompt in the corner
The fortieth seat, captured from a headless browser while 39 bots played the same instance. The corner card is the one-click party prompt for a nearby player.

zod at every edge

Anything from outside TypeScript's view is parsed:

  • Env: server/env.ts at import time, so a missing DATABASE_URL fails at boot
  • Client messages: one schema each in shared/protocol.ts; failures are dropped
  • Join options: joinOptionsSchema in onAuth
  • JSON columns: parseCharacter on every load
shared/protocol.tsTypeScript
const coord = z.number().finite().min(-10000).max(10000)
const id = z.string().min(1).max(64)
 
export const ClientMessageSchemas = {
  /** click-to-move destination (`walk`: a lightly pushed gamepad stick moves at walking pace) */
  move: z.object({ x: coord, y: coord, walk: z.boolean().optional() }),
  attackTarget: z.object({ id }),
  cast: z.object({ skill: id, x: coord, y: coord, targetId: id.optional() }),
  invMove: z.object({ from: SlotZ, to: SlotZ }),
  chat: z.object({ channel: z.enum(CHAT_CHANNELS), text: z.string().trim().min(1).max(200), to: z.string().max(32).optional() }),
  // …27 messages in all
} as const

Server → client events are typed, not validated. Batched events carry an index into SERVER_EVENT_NAMES, so a missing name would silently drop events; a conditional type makes that a compile error:

shared/protocol.tsTypeScript
/** compile error here = a ServerEvents key is missing from SERVER_EVENT_NAMES (batched events would drop it) */
export const SERVER_EVENT_NAMES_COMPLETE: [Exclude<ServerEventName, (typeof SERVER_EVENT_NAMES)[number]>] extends [never] ? true : never = true

Saves, evictions and shutdown

A character saves on leave (disconnect, transfer, tab close), every 30 s while dirty, and on shutdown. SIGTERM → matchMaker.gracefullyShutdown() → every onLeave saves:

server.tsTypeScript
const stop = (signal: string) => {
  log.info(`${signal} received, saving players…`)
  void game.shutdown().finally(() => process.exit(0))
}
process.once('SIGINT', () => stop('SIGINT'))
process.once('SIGTERM', () => stop('SIGTERM'))

Double login (second tab, phone reconnecting) would mean two sessions saving one row. onAuth asks the hub, evicts the old session, waits for its save, then reloads from the database.

Migrations, not db push

db push --accept-data-loss drops columns without asking, so once real characters existed the project moved to migrations: a baseline 0_init marked applied, then named migrations, with prisma migrate deploy before each container starts. Six so far: 0_init, endgame, rift_runs, admin, companions, items_database.

The schema is 337 lines, 18 models. Core: Account, Character, Stash. Character state lives in zod-guarded Json columns, so new stats or item properties need no migration.

Shipping it

Production is Drydock: an arm64 container from a generated Dockerfile, a provisioned Postgres, Caddy passing websockets through.

drydock.yamlYAML
name: gloamreach
kind: ssr          # ssr | static
runtime: bun        # bun | node
port: 4477
memory: 384        # MiB soft reservation (overrides size)
build: bun run build
start: bun run start
database: true      # provision Postgres + DATABASE_URL
prisma: true        # prisma generate on build, db push predeploy
predeploy: bun run db:deploy

dist/client holds the browser bundle, with Three.js and the game in chunks only engine pages load; dist/server holds the SSR entry. The container writes nothing to its filesystem. See shipping it.

The blog rides the same server

Posts in content/blog/ compile at build time through a Vite plugin into one lazy chunk each, highlighted at build time. The route's handle.head produces title, description, canonical and Open Graph tags, swapped into index.html:

server.tsTypeScript
// A route's own <head> (blog posts) replaces the default title + social block.
if (head) template = template.replace(/<!--head-->[\s\S]*?<!--\/head-->/, () => head).replace(/<!--social-->[\s\S]*?<!--\/social-->/, '')

Function-form replace, because the HTML contains code samples and a string replacement would expand $&. /blog/rss.xml calls renderRss from the same SSR bundle, so there's one copy of the post data per build.

What one process gives up

  • One core runs every room. A 40-player room costs ~2 ms of a 50 ms tick, so a couple of dozen busy rooms fit before ticks collide. The admin live page shows per-room timings.
  • Rooms can't move between processes. Scaling out means Colyseus presence and turning the hub from a Map into a bus; cross-room state is already confined to one module.
  • A deploy disconnects everyone. Saves make it safe; the client reconnects into the saved zone after a few seconds.

In exchange: one command, one port, one log stream, one artifact, and stack traces that run from a React loader to a Prisma query.