TExcelTAD
Home › Multiplayer Game Networking › The Lag Simulator

The Lag Simulator

Reading about latency is one thing; feeling 150 ms is another. This lesson introduces the tool we use for the rest of the section: a complete, tiny multiplayer game running inside one page. There are two clients and an authoritative server, connected by simulated network pipes whose latency, jitter and loss you control with sliders. In the next lessons, the same simulator gains switches for interpolation, prediction and reconciliation, so you can turn each technique on and off and see exactly what it fixes.

What is in the page

text
 Client 1 (you)            Server (the truth)          Client 2 (bot)
 keyboard -> inputs  ──up──▶  applies inputs   ◀──up──  bot -> inputs
 draws what it knows ◀─down── 20 snapshots/s ──down──▶  draws what it knows
  • Client 1 is you: arrows or WASD. Client 2 is a bot that walks a square, pausing at the corners, so you always have someone else to watch.
  • The server runs the game at 60 ticks per second. It applies each client's inputs with the shared move() function and sends a snapshot of both positions 20 times per second.
  • Each client sends one packet per tick containing its last three inputs, so a single lost packet doesn't lose an input (TCP vs UDP for Games).
  • Every packet goes through a Pipe that drops it with the loss probability or delivers it after RTT/2 ± jitter. A seeded generator decides, as in the deterministic models.
  • The dashed circles in the client panels show where the server has the players right now. A real client can never know that; the simulator cheats so you can see the error.

Version 1: no tricks at all

In this first version each client simply draws the last snapshot it received, for itself and for the other player. This is the "dumb terminal" model: correct, secure, and awful to play. Click the left panel and move:

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; color: #cfd8dc; font: 12px system-ui, sans-serif; overflow: hidden; }
  #ui { display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: center; padding: 5px 8px; height: 46px; box-sizing: border-box; align-content: center; }
  #ui label { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
  #ui input[type=range] { width: 64px; }
  #ui b { color: #fff; font-weight: 600; min-width: 3.2em; display: inline-block; }
  canvas { display: block; margin: 0 auto; height: min(calc(100vh - 50px), calc(100vw * 230 / 600)); aspect-ratio: 600 / 230; outline: none; }
</style>
<div id="ui"></div>
<canvas width="600" height="230"></canvas>
<script>
// Lesson settings: true/false = show the checkbox with that starting value, null = hidden and off.
const TOGGLES = { interp: null, predict: null, reconcile: null };

// ---- play kit (from canvas-games): click to focus, keep game keys inside the frame, fixed-step loop ----
// Adapted: the simulation keeps running without focus (so you can drag sliders); only the keyboard needs focus.
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();
let active = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (!active) return;
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault();
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function run(update, draw) {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    acc += dt;
    while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
    draw();
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

function mulberry32(seed) {
  return () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const rnd = mulberry32(42);

// ---- settings and UI ----
const cfg = { rtt: 150, jitter: 20, loss: 2, interp: !!TOGGLES.interp, predict: !!TOGGLES.predict, reconcile: !!TOGGLES.reconcile };
const ui = document.getElementById('ui');
function slider(key, label, max, unit) {
  const l = document.createElement('label');
  l.innerHTML = `${label} <input type="range" min="0" max="${max}" value="${cfg[key]}"> <b>${cfg[key]}${unit}</b>`;
  const [input, out] = [l.querySelector('input'), l.querySelector('b')];
  input.addEventListener('input', () => { cfg[key] = +input.value; out.textContent = input.value + unit; });
  ui.appendChild(l);
}
function toggle(key, label) {
  if (TOGGLES[key] === null || TOGGLES[key] === undefined) return;
  const l = document.createElement('label');
  l.innerHTML = `<input type="checkbox" ${cfg[key] ? 'checked' : ''}> ${label}`;
  l.querySelector('input').addEventListener('change', (e) => { cfg[key] = e.target.checked; });
  ui.appendChild(l);
}
slider('rtt', 'RTT', 500, ' ms');
slider('jitter', '± jitter', 100, ' ms');
slider('loss', 'loss', 20, '%');
toggle('predict', 'prediction');
toggle('reconcile', 'reconciliation');
toggle('interp', 'interpolation');

// ---- shared game rules: the SAME code runs on the clients (prediction) and the server ----
const ARENA = 100, SPEED = 40, R = 4, DT = 1 / 60;
function move(p, inp) {
  p.x = Math.max(R, Math.min(ARENA - R, p.x + inp.dx * SPEED * DT));
  p.y = Math.max(R, Math.min(ARENA - R, p.y + inp.dy * SPEED * DT));
}
const START = [{ x: 25, y: 50 }, { x: 75, y: 50 }];

// ---- the simulated network: one pipe per direction per client ----
let now = 0;                                  // simulated clock, ms
const stats = { sent: 0, lost: 0 };
class Pipe {
  q = [];
  send(msg) {
    stats.sent++;
    if (rnd() * 100 < cfg.loss) { stats.lost++; return; }
    const jitter = (rnd() * 2 - 1) * cfg.jitter;
    this.q.push({ at: now + Math.max(0, cfg.rtt / 2 + jitter), msg });
  }
  receive() {
    const due = this.q.filter((p) => p.at <= now).sort((a, b) => a.at - b.at);
    this.q = this.q.filter((p) => p.at > now);
    return due.map((p) => p.msg);
  }
}
const up = [new Pipe(), new Pipe()], down = [new Pipe(), new Pipe()];

// ---- the authoritative server ----
const SNAP_EVERY = 3;                         // 60 Hz simulation, 20 Hz snapshots
const server = {
  tick: 0,
  players: START.map((p) => ({ ...p })),
  lastSeq: [-1, -1],
  step() {
    for (let c = 0; c < 2; c++) {
      for (const msg of up[c].receive()) {
        for (const inp of msg.inputs) {       // each packet repeats the last 3 inputs
          if (inp.seq <= this.lastSeq[c]) continue;
          move(this.players[c], inp);
          this.lastSeq[c] = inp.seq;
        }
      }
    }
    if (++this.tick % SNAP_EVERY === 0) {
      for (let c = 0; c < 2; c++) {
        down[c].send({ t: now, pos: this.players.map((p) => ({ ...p })), ack: this.lastSeq[c] });
      }
    }
  },
};

// ---- a client ----
const INTERP_DELAY = 100;                     // ms: two snapshot intervals
class Client {
  constructor(id) {
    this.id = id; this.other = 1 - id; this.seq = 0;
    this.self = { ...START[id] };
    this.pending = [];                        // inputs not yet acknowledged by the server
    this.snaps = [];                          // recent snapshots, sorted by server time
    this.latest = null;
    this.delay = null;                        // smoothed (receive time - server time)
    this.correction = 0;
  }
  step(dx, dy) {
    for (const s of down[this.id].receive()) this.onSnapshot(s);
    const inp = { seq: this.seq++, dx, dy };
    this.pending.push(inp);
    if (cfg.predict) move(this.self, inp);    // prediction: apply our own input immediately
    up[this.id].send({ inputs: this.pending.slice(-3) });
  }
  onSnapshot(s) {
    this.snaps.push(s);
    this.snaps.sort((a, b) => a.t - b.t);
    if (this.snaps.length > 30) this.snaps.shift();
    if (this.latest && s.t <= this.latest.t) return;          // late snapshot: only useful for interpolation
    this.latest = s;
    const d = now - s.t;
    this.delay = this.delay === null ? d : this.delay + (d - this.delay) * 0.05;
    this.pending = this.pending.filter((i) => i.seq > s.ack); // the server has applied these
    const auth = { ...s.pos[this.id] };
    if (!cfg.predict) { this.self = auth; return; }           // no prediction: show what the server says
    if (cfg.reconcile) for (const i of this.pending) move(auth, i);  // replay inputs the server hasn't seen
    this.correction = Math.hypot(auth.x - this.self.x, auth.y - this.self.y);
    this.self = auth;
  }
  remote() {                                   // where we draw the OTHER player
    if (!this.latest) return START[this.other];
    if (!cfg.interp) return this.latest.pos[this.other];
    const t = now - this.delay - INTERP_DELAY;  // render the past, in server time
    const s = this.snaps;
    if (t <= s[0].t) return s[0].pos[this.other];
    for (let i = s.length - 1; i > 0; i--) {
      if (s[i - 1].t <= t && t <= s[i].t) {
        const a = s[i - 1].pos[this.other], b = s[i].pos[this.other];
        const k = (t - s[i - 1].t) / (s[i].t - s[i - 1].t);
        return { x: a.x + (b.x - a.x) * k, y: a.y + (b.y - a.y) * k };
      }
    }
    return this.latest.pos[this.other];        // buffer ran dry: hold the newest
  }
}
const clients = [new Client(0), new Client(1)];

// ---- the bot that plays client 2: walks a square, pausing at the corners ----
function botInput(seq) {
  const phase = Math.floor(seq / 60) % 10;
  return [[1, 0], [1, 0], [0, 0], [0, 1], [0, 0], [-1, 0], [-1, 0], [0, 0], [0, -1], [0, 0]][phase];
}

function update() {
  now += 1000 / 60;
  const dx = (keys.has('ArrowRight') || keys.has('KeyD') ? 1 : 0) - (keys.has('ArrowLeft') || keys.has('KeyA') ? 1 : 0);
  const dy = (keys.has('ArrowDown') || keys.has('KeyS') ? 1 : 0) - (keys.has('ArrowUp') || keys.has('KeyW') ? 1 : 0);
  clients[0].step(dx, dy);
  const [bx, by] = botInput(clients[1].seq);
  clients[1].step(bx, by);
  server.step();
}

// ---- drawing ----
const COLORS = ['#ff9e40', '#4dd0e1'];
const PANEL = 190, TOP = 22, S = PANEL / ARENA;
function circle(ox, p, color, ghost) {
  ctx.beginPath();
  ctx.arc(ox + p.x * S, TOP + p.y * S, R * S, 0, Math.PI * 2);
  if (ghost) { ctx.setLineDash([3, 3]); ctx.strokeStyle = color; ctx.stroke(); ctx.setLineDash([]); }
  else { ctx.fillStyle = color; ctx.fill(); }
}
function panel(i, title, lines, drawFn) {
  const ox = 5 + i * (PANEL + 10);
  ctx.fillStyle = '#16213e'; ctx.fillRect(ox, TOP, PANEL, PANEL);
  ctx.strokeStyle = '#22305a';
  for (let g = 0; g <= ARENA; g += 20) {
    ctx.beginPath(); ctx.moveTo(ox + g * S, TOP); ctx.lineTo(ox + g * S, TOP + PANEL); ctx.stroke();
    ctx.beginPath(); ctx.moveTo(ox, TOP + g * S); ctx.lineTo(ox + PANEL, TOP + g * S); ctx.stroke();
  }
  ctx.fillStyle = '#fff'; ctx.font = 'bold 12px system-ui, sans-serif'; ctx.textAlign = 'left';
  ctx.fillText(title, ox, 15);
  drawFn(ox);
  ctx.fillStyle = '#9aa3b5'; ctx.font = '10px ui-monospace, monospace';
  lines.forEach((t, k) => ctx.fillText(t, ox + 4, TOP + 12 + k * 12));
}
function draw() {
  ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
  clients.forEach((c, i) => {
    const pi = i === 0 ? 0 : 2;
    panel(pi, i === 0 ? 'Client 1 (you)' : 'Client 2 (bot)',
      [`pending inputs ${c.pending.length}`, `last correction ${c.correction.toFixed(1)}`],
      (ox) => {
        circle(ox, server.players[c.other], COLORS[c.other], true);   // ghost: the server's truth
        circle(ox, server.players[c.id], COLORS[c.id], true);
        circle(ox, c.remote(), COLORS[c.other], false);
        circle(ox, c.self, COLORS[c.id], false);
      });
  });
  panel(1, 'Server (the truth)', [`tick ${server.tick}`, `lost ${stats.lost}/${stats.sent} packets`], (ox) => {
    server.players.forEach((p, i) => circle(ox, p, COLORS[i], false));
  });
  if (!active) {
    ctx.fillStyle = 'rgba(0,0,0,0.55)'; ctx.fillRect(5, TOP + PANEL - 22, PANEL, 22);
    ctx.fillStyle = '#fff'; ctx.font = '11px system-ui, sans-serif'; ctx.textAlign = 'center';
    ctx.fillText('Click here, then arrows/WASD', 5 + PANEL / 2, TOP + PANEL - 7);
  }
}
run(update, draw);
</script>

Things to try:

  1. Default settings (150 ms, ±20 ms, 2%). Tap Right once. Your circle starts moving about 150 ms after the key goes down and keeps going for 150 ms after you release it. Your filled circle trails the dashed one (the server) by a constant gap while you move.
  2. RTT 0, jitter 0, loss 0. Now it feels almost local, but look closely at the bot in your panel: it moves in steps, 20 times per second, because that's how often snapshots arrive. Your own circle steps too.
  3. RTT 300. Try to stop exactly on a grid line. You can't; you will always overshoot.
  4. Jitter 80. Snapshots now arrive bunched and out of order. This version ignores snapshots older than the newest one ("newest wins"), so instead of moving backwards, the circles freeze and then jump ahead.
  5. Loss 20%. Movement still arrives (thanks to the redundant inputs) but the picture is jerky, with gaps where snapshots were dropped.

The code that matters

Most of the page is drawing and sliders. The networking part is short. The pipe:

js
class Pipe {
  q = [];
  send(msg) {
    if (rnd() * 100 < cfg.loss) return;                            // dropped
    const jitter = (rnd() * 2 - 1) * cfg.jitter;
    this.q.push({ at: now + Math.max(0, cfg.rtt / 2 + jitter), msg });
  }
  receive() {                                                       // everything that has arrived by now
    const due = this.q.filter((p) => p.at <= now).sort((a, b) => a.at - b.at);
    this.q = this.q.filter((p) => p.at > now);
    return due.map((p) => p.msg);
  }
}

The server applies every input it hasn't seen yet, then broadcasts a snapshot every third tick. It includes ack, the newest input sequence it applied for that client, which the reconciliation lesson will need:

js
for (const inp of msg.inputs) {
  if (inp.seq <= this.lastSeq[c]) continue;    // duplicate from the redundancy
  move(this.players[c], inp);                  // the SAME function the clients use
  this.lastSeq[c] = inp.seq;
}
if (++this.tick % SNAP_EVERY === 0) {
  for (let c = 0; c < 2; c++) down[c].send({ t: now, pos: this.players.map((p) => ({ ...p })), ack: this.lastSeq[c] });
}

Note: This server applies inputs as soon as they arrive, possibly several in one tick after a jitter spike. A production server would buffer them by tick number (The Authoritative Server); applying immediately keeps the simulator short, and the techniques work the same way.

What we have to fix

Symptom (version 1) Cause Fixed by
Your own character reacts a full RTT late waiting for the server Client-Side Prediction
Other players move in 20 Hz steps, freeze and jump with jitter drawing raw snapshots Snapshot Interpolation
(after adding prediction) your character snaps back snapshots describe the past Server Reconciliation
Shots at moving players miss even when aimed well you see others in the past Lag Compensation

Test yourself

In version 1 at 150 ms RTT, why does your character keep moving after you release the key?

  1. The server predicts it
  2. The 'key up' input needs half an RTT to reach the server and the result another half to come back, while earlier inputs are still being applied
  3. The bot pushes it
  4. Packets are lost

With 0 ms latency, why does the bot still move in visible steps?

  1. The bot is slow
  2. Snapshots arrive only 20 times per second, and the client draws each one as is
  3. The canvas can't draw faster
  4. Loss is still 2%

Why does each client packet carry its last three inputs?

  1. To triple the speed
  2. So that one or two lost packets don't lose inputs; the server ignores the ones it has already applied
  3. Because UDP requires it
  4. For encryption