Forty heroes in one room, and what they did to the tick
Rooms, instances and parties in one Bun process, a forty-hero level-99 stress test that pushed the 20 Hz tick past 200 ms, and the batched, budgeted event fan-out that brought boss p95 under 5 ms.

Contents
ROOM_MAX_CLIENTS is 40 and the bot load test passed, so the landing page promised 39 other players per zone. Forty level-99 heroes in Act 6 showed that was only true for bots that didn't do much. Then the fix.

One zone instance is one room
Each instance is a ZoneRoom around the plain-object World (the sim):
matchMaker.defineRoomType('zone', ZoneRoom).filterBy(['zoneId', 'difficulty', 'privateKey'])
matchMaker.defineRoomType('house', HouseRoom).filterBy(['ownerCharacterId'])- Open zones:
joinOrCreatefills an instance to 40, then creates #2 - Difficulty is in the key; parties are per difficulty
- Private worlds:
privateKeyis the hero's id;onAuthre-checks it and admits the party (companions) - Houses and rifts are their own rooms; rift layouts come from
rift_<act>_<tier>_<seed36>_<floor>(procgen) - Towns seed from
hash32(zoneId)(every Hollowmere is the same); wilds and dungeons fromhash32(zoneId, roomId)(instance #2 is a different map)
Parties across instances
With two open instances, a party member could land in the other one. So every connect asks first:
// Where is my party? The client asks before joining a zone so it can `joinById` the instance a party
// member is already in (transfer events also carry `roomId` when one exists).
instance: accountProcedure
.input(z.object({ characterId: z.string().min(1).max(64), zoneId: z.string().min(1).max(64) }))
.query(({ ctx, input }) => {
const me = hub.get(input.characterId)
const partyId = hub.partyOf(input.characterId)
if (me && me.accountId !== ctx.account.id) return { roomId: null, partyId: null }
return { roomId: hub.findPartyInstance(partyId, input.zoneId, input.characterId), partyId }
}),hub.ts is an in-process module, not a service: presence, parties (max 8, 30 s disconnect grace), cross-room chat, town-portal pairs (tp_<ownerId>), 60 s transfer tokens, stash locks, admin handles. No Redis, no pub/sub.
The cost is ordering: a second-tab login evicts the old session and waits for its leave-save before loading, tested in server/game/foundation.test.ts ("evict waits for the old session to save and let go"). Opening town portals to everyone (f1d44f5) was one change, because the hub owns the pairing.
The first load test was too kind
scripts/bots.ts joins N guests over real websockets with the browser's @colyseus/sdk. 40 bots, ~160 monsters: 1.2 ms average, ≤ 4 ms p95, ~10 KB/s per client. QA with 30 bots plus 3 browsers: 1.56 ms, 9.6 ms p95, 60 fps.
Real numbers, wrong workload. The bots are level 1–4 and mostly auto-attack. A level-99 hero casts area spells several times a second, each producing damage numbers on every monster touched, cast and impact effects, and deaths. The sim was never the problem; the event count was.
Forty level 99 heroes in Act VI
A showcase agent built the forty-hero video as two scripts.
scripts/showcase.ts makes 40 guests, runs dev.maxOut on each (level 99, every act, max-rolled uniques and sets, skills bound) and drives 39 headless:
// Showcase pack: N god-tier heroes (dev.maxOut level 99) join ONE zone instance over real
// websockets and rampage through it, filmed by the one rendered client (scripts/showcase-camera.ts,
// hero 0, which trails the pack). The first headless hero leads from cluster to cluster (or to the
// boss); the rest hold a loose ring around it, rush monsters near the pack and spam their class
// kits (AoE, projectiles, summons, auras, buffs). Samples /api/status → sim and per-client
// downstream bandwidth while it runs.The leader plans full-zone A* legs on its own nav grid. One constant is pure cinematography:
/** pack-wide minimum ms between two heroes' big bloom spells: 13 Starfalls in one frame white out the camera */
const PACK_SPACING: Record<string, number> = { e_starfall: 450, w_skyfall: 200, s_rain_of_barbs: 250 }scripts/showcase-camera.ts is hero 0: a GPU Chromium at 1080p on a separate non-watching server, CDP screencast like the trailer.
Hell wiped the pack (134 deaths in 75 s on the Isles); Nightmare wiped it at bosses. The shoot runs on Normal, which says level normalization works. Even so, the camera hero died at least once.


What the shoot measured
| Where | Tick avg | Tick p95 | Tick max | Down per client |
|---|---|---|---|---|
| Shattered Isles, marching | 5–17 ms | 40–150 ms | — | 11–40 KB/s |
| Hollow Sanctum, at the Hollow Saint | 40–60 ms | ~210–240 ms | ~600 ms | 11–40 KB/s |
The budget is 50 ms. A 240 ms p95 is five ticks in one: prediction runs ahead, authority arrives late, and all forty heroes rubber-band at once.
The cause was the fan-out
private flushEvents(): void {
const events = this.world.drainEvents()
if (events.length === 0) return
const r2 = EVENT_RADIUS * EVENT_RADIUS
for (const { to, ev } of events) {
if (to.kind === 'all') {
this.broadcast(ev.type, ev.payload)
} else if (to.kind === 'player') {
this.sessions.get(to.sid)?.client.send(ev.type, ev.payload)
} else {
for (const p of this.world.players.values()) {
const dx = p.x - to.x
const dy = p.y - to.y
if (dx * dx + dy * dy > r2) continue
this.sessions.get(p.sid)?.client.send(ev.type, ev.payload)
}
}
}
}Every client.send re-encodes and writes its own frame. Hundreds of near events per tick × forty recipients in the 45-tile radius = thousands of encodes and frames on the sim's thread.
The netperf agent added rooms/tickProfile.ts, timing every phase into the 400-sample ring on /api/status:
export const TICK_PHASES = ['companions', 'sim', 'pets', 'endgame', 'sync', 'events', 'requests', 'self', 'patch'] as constForty-hero baseline, no camera: events 11–13 ms average with ~150 ms peaks; sim ~0.8 ms; patch ~1.4 ms. An A/B of old and new paths in one build confirmed the cause.
The fix, in two parts
Encode once, one frame per client per tick:
// Per-tick event delivery for a zone room. The sim queues events scoped to everyone, one player, or
// everyone within EVENT_RADIUS of a point. Sending each one with client.send() msgpack-encoded it
// again for every recipient and cost one websocket frame per event per client: at 40 heroes
// spamming AoE that was 10-100 ms a tick. Here every event is encoded ONCE into a shared arena,
// and each client gets one ROOM_DATA frame per tick (EVENT_BATCH) that is a byte concatenation of
// the events it should see.
/** Colyseus' packr settings (the SDK's unpack reads it like any room message) + 5-byte floats. */
const packr = new Packr({ useRecords: false, useFloat32: FLOAT32_OPTIONS.DECIMAL_FIT })
const HEADER = Uint8Array.from(getMessageBytes.raw(Protocol.ROOM_DATA, EVENT_BATCH))- A valid
ROOM_DATAmessage, so the SDK decodes it normally; the client walks[typeIndex, payload, …]into the same handlers (shared/eventBatch.ts) - Coordinates quantized to 1/100 tile as float32
- A missing type index would drop events silently, so it's a compile error:
/** Append-only in practice: EVENT_BATCH carries indices into this list. Must name every ServerEvents key. */
export const SERVER_EVENT_NAMES = [
'fx', 'hit', 'death', 'levelUp', 'chat', 'system', 'transfer', 'toast', 'self', 'dialog', 'party', 'catalog',
] as const satisfies readonly ServerEventName[]
/** 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 = trueCosmetic level of detail. Always delivered: your casts, hits on or by you, your summons and companions, telegraphs, heals, deaths, toasts. Other heroes' casts, hits and impacts share a per-client byte budget, spent in tier order from a start point that rotates each tick:
/** Delivery tiers: ESSENTIAL always goes; the rest spend the cosmetic budget in this order. */
export const Tier = { ESSENTIAL: 0, CAST: 1, HIT: 2, IMPACT: 3 } as const
const COSMETIC_TIERS: readonly TierValue[] = [Tier.CAST, Tier.HIT, Tier.IMPACT]/** per client per tick: bytes of other heroes' spell fx / hit numbers (cosmetic LOD, rooms/eventFanout.ts) */
const COSMETIC_BYTES_PER_TICK = 400Rejected in decisions.md:
- Grouping clients by identical visibility: your own events make every set differ; a memcpy is cheaper than hashing
- Per-client msgpack with records: still forty encodes
StateViewproximity culling: at a boss everyone is in range, and patches were ~9 KB/s- Lower patch rate: costs movement feel
Before and after
scripts/room-perf.ts boots its own non-watching server on an uncommon port, runs forty headless heroes through three 90 s scenarios, prints avg/p95/max, phases and KB/s against a budget (avg ≤ 10 ms, p95 ≤ 35 ms, ~20 KB/s), and stops everything.
| Scenario | Tick avg | Tick p95 | Tick max | Down per client |
|---|---|---|---|---|
| Shattered Isles, marching | 6.7 → 2.7 ms | 36 → 18 ms | 88 → 76 ms | 28 → 15 KB/s |
| Hollow Sanctum, boss fight | 12.6 → 1.6 ms | 56 → 4.4 ms | 110 → 16 ms | 42 → 19.5 KB/s |
| Unwritten Throne, boss fight | 14.1 → 1.8 ms | 61 → 4.5 ms | 154 → 10 ms | 49 → 18.9 KB/s |
- The Isles 18 ms p95 was a stall from other work on the machine; quiet runs give 5–6 ms
- Boss fights, the densest event load in the game, now use under a tenth of the tick at p95
- Bandwidth halved at bosses: one frame header, float32, the budget. Isles and Sanctum ran with 500 bytes; the Throne with the shipped 400
The reshoot on a production build
NODE_ENV=production, wider spaces, fewer summons, four scenes, a 127-second cut:
| Scene | Tick avg | Tick p95 | Tick max | Down/client | Casts/s |
|---|---|---|---|---|---|
| Hollowmere | 0.36 ms | 1.3 ms | 4.2 ms | 0.5 KB/s | 1.7 |
| Frozen Forest | 2.05 ms | 5.1 ms | 20.7 ms | 17 KB/s | 34.9 |
| River of Flame | 2.12 ms | 4.9 ms | 12.9 ms | 14.6 KB/s | 14.9 |
| Sepulcher (Colossus) | 1.16 ms | 3.4 ms | 17.6 ms | 8.2 KB/s | 11.9 |
Runs of 90, 155, 115 and 130 s; no deaths; the 1080p camera held 59.5–60 fps. Frozen Forest phase averages: patch 1.10 ms, sim 0.79, events 0.59, sync 0.43. Events, once 11–13 ms, are now smaller than the sim; the biggest cost is the schema patch, 1.1 ms even in an empty town.


What I'd do differently
The load test measured what was easy to script. Level-1 bots and level-99 heroes differ by two orders of magnitude in events per tick, and only the second was the real claim. A video shoot turned out to be the most useful perf test of the day; it's now the regression bench verify.md lists for room changes.
decisions.md still says per-player proximity culling isn't worth it below ~60 players per zone or 25 KB/s per client. Both held: 15–20 KB/s at bosses. The bandwidth was never the problem; the CPU cost of sending it was.

Related posts
- The server-authoritative sim: the tick this post is about
- Companions: the other way to fill a room, at 0.29 ms a tick for 160 heroes
- Making the trailer: where the forty-hero footage ended up
- Testing an ARPG that agents wrote: the other harnesses and budgets