Twenty ticks a second

One click through the netcode, covering the 20 Hz authoritative tick, commands as intents, quantized patches, prediction reconciled against its own past, interpolation and effects as events.

Four heroes of different classes fighting together on the sand of the Scorched Dunes
Contents
  1. The world is plain objects
  2. Commands are intents
  3. The tick and its budget
  4. Sync: plain objects into a schema
  5. Prediction: move now, argue later
  6. Everyone else, 100 ms in the past
  7. Effects are events, not state
  8. What authority buys
  9. Read next

The server decides everything: position, hits, damage, drops. The client sends requests. What follows is one click from mouse to screen and what each layer does to make that feel instant.

The world is plain objects

Each room owns a World of plain objects: no Colyseus, no schema classes, no decorators. Phases run in a fixed order:

server/game/sim/world.tsTypeScript
tick(dtMs: number): void {
  const t0 = performance.now()
  this.now += dtMs
  this.pathBudget = PATH_BUDGET_PER_TICK
  this.rebuildHashes()
  tickEnvironment(this, dtMs) // acts:
  tickPlayers(this, dtMs)
  tickMonsters(this, dtMs)
  separateMonsters(this)
  tickProjectiles(this, dtMs)
  tickAreas(this)
  tickTraps(this)
  tickLoot(this)
  tickSpawns(this)
  this.lastTickMs = performance.now() - t0
}
  • Player and monster spatial hashes are rebuilt every tick; clear-and-refill beats incremental updates, and every range query becomes a grid lookup.
  • Tests build a World directly with no sockets. The Unmaker's phases, the tide, frostbite and arena tiles from six acts are all tested that way.

Commands are intents

A message is zod-validated, then its handler sets an intention for the tick:

server/game/sim/commands.tsTypeScript
attackTarget(w, p, m) {
  if (!alive(p)) return null
  const t = w.unit(m.id)
  if (!t || t.dead || t.team === p.team) return null
  if (p.intent && p.intent.kind === 'attack' && p.intent.targetId === t.id) {
    p.intent.holdUntil = w.now + HOLD_MS
    return null
  }
  if (p.channel) endChannel(w, p)
  p.intent = { kind: 'attack', targetId: t.id, skill: BASIC_ATTACK, holdUntil: w.now + HOLD_MS }
  return null
},

Diablo's hold-to-attack maps onto this directly:

  • An attack intent lives until holdUntil, 450 ms out
  • Holding the mouse resends attackTarget every ~250 ms, pushing holdUntil forward
  • Release, resends stop, intent lapses; meanwhile the tick walks into range and swings on cooldown

Casts out of range become approach intents; casts mid-animation queue instead of dropping. Handlers re-check what zod can't: death, team, range, mana, cooldowns, item ownership. A per-session token bucket (burst 40, refill 30/s) stops floods.

The tick and its budget

Every 50 ms: companion AI, World.tick, pet and endgame hooks, schema sync, event flush, saves, each phase profiled.

A 50 ms bar with 1.45 ms used, expanded below into World.tick 0.52 ms, syncWorld 0.18 ms, flushEvents 0.64 ms and the rest 0.11 ms
One tick, measured for this post: 40 bot clients and 300 monsters in the Scorched Dunes on a local server. Averages over the last 400 ticks from /api/status.

40 clients, 300 monsters: 1.51 ms average, 3.89 ms worst-window p95. The sim is the smallest part; events cost more, which is why that path was rebuilt after forty level-99 heroes pushed the tick past 200 ms (forty players).

Sync: plain objects into a schema

server/game/schema/index.tsTypeScript
// Positions are 16-bit quantized over [0, 256) tiles (1/256 tile steps),
// facings are 8-bit angles, so a moving entity costs ~5 bytes per patch instead of ~13.
const pos = () => t.quantized({ min: 0, max: 256, bits: 16 })
const angle = () => t.angle({ bits: 8 })
 
export const PlayerState = schema(
  {
    id: t.string().default(''),
    x: pos().default(0),
    y: pos().default(0),
    facing: angle().default(0),
    hp: t.uint16().default(1),
    /** 'idle' | 'move' | 'attack' | 'cast' | 'channel' | 'leap' | 'dash' | 'dead' */
    action: t.string().default('idle'),
    /** serverTime (ms) the action started — re-stamped on every swing so clients replay the animation */
    actionAt: t.uint32().default(0),
    /** final destination of the current path (equals x/y when idle) */
    moveTx: pos().default(0),
    moveTy: pos().default(0),
    speed: t.float32().default(5),
    // …
  },
  'PlayerState'
)

Schema v5 sends only changed fields, so sync rounds to wire precision before assigning. Standing still, or moving under 1/256 tile, costs zero bytes:

server/game/rooms/sync.tsTypeScript
/** 1/256 tile — matches the quantized wire precision; smaller moves are not worth a patch */
function q(v: number): number {
  return Math.round(v * 256) / 256
}
 
export function syncPlayer(s: PlayerState, p: SimPlayer): void {
  s.x = q(p.x)
  s.y = q(p.y)
  s.facing = Math.round(p.facing * 40) / 40
  // …
}
  • actionAt drives animation, not an event: late joiners see the right swing, and nothing is lost to a dropped message.
  • moveTx/moveTy let remote gait anticipate turns.
  • Private data (inventory, stats, skills, quests) goes in a self message to its owner only, at most every 200 ms, only on change.
  • Loot is per player via StateView: other players' drops never reach your socket.

Per client in the 40-client run: 11 KB/s including events, 29 messages/s.

Prediction: move now, argue later

The client has the server's nav grid (worlds from a seed), so a click runs the same A* and starts walking at the last reported speed while move goes out.

The server's position is about one round trip old, so comparing it with now always looks behind. The client keeps its last 64 positions and compares against RTT + half a patch ago:

src/game/net/prediction.tsTypeScript
/** Server snapshot for our own entity. */
onServer(now: number, sx: number, sy: number, serverMoving: boolean, speed: number): void {
  this.serverX = sx
  this.serverY = sy
  if (speed > 0) this.maxSpeed = speed
  // where were we ~RTT (+ half a patch) ago?
  const past = this.historyAt(now - this.rttMs - 25)
  const refX = this.moving || serverMoving ? past.x : this.x
  const refY = this.moving || serverMoving ? past.y : this.y
  const dx = sx - refX
  const dy = sy - refY
  const drift = Math.hypot(dx, dy)
  if (drift > SNAP_DIST) {
    // snap to the server; keep going toward the destination from there
    // …
    return
  }
  // ease out the remaining error (don't fight tiny numbers)
  this.corrX = drift > 0.05 ? dx : 0
  this.corrY = drift > 0.05 ? dy : 0
}
A path with a ring of past positions; the server position is compared with the position one round trip ago rather than the current one, with three outcomes: ignored, eased out, or snap and re-path
Reconciliation compares like with like. Normal latency produces no correction at all; only real disagreement does.
Drift Response
Normal latency none
Small (rounding, jitter) eased out exponentially, faster when standing
Large (knockback, slow, floor turned to abyss) snap to server, re-path

Speed changes (frostbite, wading) need nothing special: the predictor walks at the server's speed. Approach intents are predicted too, so the hero is in range by the time actionAt stamps the swing.

Everyone else, 100 ms in the past

Remote entities are interpolated from a fixed ring of timestamped snapshots in typed arrays, sampled 100 ms back:

src/game/net/snapshots.tsTypeScript
/** Interpolated state at render time `rt` (already delayed by the caller). Writes into `out`. */
sample(rt: number, out: Sample): Sample {
  if (this.count === 0) return out
  const newest = (this.head - 1 + CAP) % CAP
  const tNew = this.t[newest] ?? 0
  if (rt >= tNew || this.count === 1) {
    // Past the newest snapshot: hold (short extrapolation would overshoot corners).
    // …
  }
  // Walk back from newest to find the bracketing pair, then lerp.
  // …
}
  • 100 ms = two 50 ms patches, so a bracketing pair almost always exists
  • Past the newest: hold, never extrapolate; monsters turn corners constantly
  • Speed from the pair drives the walk/run blend, so slowed monsters visibly walk slower
Four players in one fight. Each client predicts its own hero, interpolates the other three and every monster 100 ms behind, and draws every spell from events.

Effects are events, not state

Each event carries everything needed to draw it:

shared/protocol.tsTypeScript
export interface FxEvent {
  /** skill id, monster ability id, or a bare fx key (e.g. 'levelup', 'portal_open', 'loot_beam') */
  kind: string
  x: number
  y: number
  tx?: number
  ty?: number
  /** server time ms when the effect starts (projectiles advance from here) */
  t: number
  /** projectile fan / strike count and deterministic seed for scatter visuals */
  count?: number
  seed?: number
  /** server projectile id: a launch with `count` n spawns ids pid..pid+n-1; an end/impact fx carries the id to remove */
  pid?: number
  /** projectile speed in tiles/s */
  speed?: number
  // …
}
  • A projectile is origin, target, speed and server start time; the client flies it from the right moment even if late. No per-frame positions.
  • An end event with pid removes the client's copy where the server's hit.
  • Eight arrows are one event with count: 8 and a seed.

Events are cheap but numerous, so they're encoded once per tick into a shared buffer and sent as one batched frame per client, with a byte budget for others' cosmetics.

Four heroes mid-fight around glowing rune circles, a column of light and scattered loot on the ground
A party fight. The loot on the ground is each player's own; nobody sees, or receives, anyone else's drops.

What authority buys

Standard toolkit: authoritative tick, intents, delta-compressed state, prediction with reconciliation, interpolation, timestamped events. It worked in a day because protocol, schema and nav grid were fixed early in shared/, and the server sim and client prediction were written by different agents against the same code.

Result: no teleport cheats, no client-side loot dupes, forty players at under 2 ms per tick, and your hero moves the moment you click.