TExcelTAD
Home › Multiplayer Game Networking › Snapshot Interpolation

Snapshot Interpolation

Other players' positions reach you in snapshots, 20 or 30 times per second, at irregular moments. Drawing each one as it arrives (as version 1 of the simulator does) makes everyone else stutter. Snapshot interpolation fixes that with a simple, slightly surprising idea: show other players a little in the past, so you always have two snapshots to blend between.

The idea

Keep the last few snapshots in a buffer, each stamped with the server time it describes. Every rendered frame, pick a render time:

text
renderTime = estimatedServerTime - interpolationDelay

then find the two snapshots on either side of renderTime and blend linearly between them. With snapshots every 50 ms and a delay of 100 ms (two snapshot intervals), there is almost always a snapshot after the render time, even if one packet is late or lost. Movement becomes perfectly smooth, at the price of showing others 100 ms further in the past than the network already does.

A model, frame by frame

A remote player moves right at a steady 60 units per second. The server sends a snapshot every 50 ms; each takes 60 ms ± 25 ms to arrive, and one is lost. We render at 100 Hz (every 10 ms) and compare two methods: raw (draw the newest snapshot) and interpolated (draw renderTime = now - 60 ms - 100 ms):

ts · try it yourself
function mulberry32(seed: number) {
  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(8);
type Snap = { t: number; x: number; arrive: number };

const snaps: Snap[] = [];
for (let t = 0; t <= 600; t += 50) {
  const arrive = t + 60 + Math.round((rnd() * 2 - 1) * 25);
  if (t === 300) continue;                              // this one is lost
  snaps.push({ t, x: t * 0.06, arrive });               // 60 units/s = 0.06 per ms
}

const ONE_WAY = 60, DELAY = 100;
let prevRaw = 0, prevInterp = 0;
const rawSteps: number[] = [], interpSteps: number[] = [];
console.log('  now   raw x  (step)   interp x  (step)');
for (let now = 300; now <= 560; now += 20) {
  const known = snaps.filter((s) => s.arrive <= now).sort((a, b) => a.t - b.t);
  const raw = known[known.length - 1].x;
  const rt = now - ONE_WAY - DELAY;                    // render time, in server time
  let interp = known[known.length - 1].x;              // fallback: hold the newest
  for (let i = known.length - 1; i > 0; i--) {
    const a = known[i - 1], b = known[i];
    if (a.t <= rt && rt <= b.t) { interp = a.x + (b.x - a.x) * (rt - a.t) / (b.t - a.t); break; }
  }
  rawSteps.push(raw - prevRaw); interpSteps.push(interp - prevInterp);
  console.log(`${String(now).padStart(5)}  ${raw.toFixed(1).padStart(6)}  (${(raw - prevRaw).toFixed(1).padStart(4)})   ${interp.toFixed(1).padStart(8)}  (${(interp - prevInterp).toFixed(1).padStart(4)})`);
  prevRaw = raw; prevInterp = interp;
}
const spread = (xs: number[]) => (Math.max(...xs.slice(1)) - Math.min(...xs.slice(1))).toFixed(1);
console.log(`step size varies by: raw ${spread(rawSteps)}, interpolated ${spread(interpSteps)} (ideal: 0, every step 1.2)`);
  now   raw x  (step)   interp x  (step)
  300    12.0  (12.0)        8.4  ( 8.4)
  320    15.0  ( 3.0)        9.6  ( 1.2)
  340    15.0  ( 0.0)       10.8  ( 1.2)
  360    15.0  ( 0.0)       12.0  ( 1.2)
  380    15.0  ( 0.0)       13.2  ( 1.2)
  400    21.0  ( 6.0)       14.4  ( 1.2)
  420    21.0  ( 0.0)       15.6  ( 1.2)
  440    21.0  ( 0.0)       16.8  ( 1.2)
  460    24.0  ( 3.0)       18.0  ( 1.2)
  480    24.0  ( 0.0)       19.2  ( 1.2)
  500    27.0  ( 3.0)       20.4  ( 1.2)
  520    27.0  ( 0.0)       21.6  ( 1.2)
  540    27.0  ( 0.0)       22.8  ( 1.2)
  560    27.0  ( 0.0)       24.0  ( 1.2)
step size varies by: raw 6.0, interpolated 0.0 (ideal: 0, every step 1.2)

The raw column moves in irregular jumps: 0, then 3, sometimes 6 when the lost snapshot leaves a gap. The interpolated column advances by exactly 1.2 every 20 ms, the true speed, despite jitter and the lost packet, because the render time trails far enough behind that the buffer never runs dry. It is also always further behind the truth. That's the trade.

Try it

This version of the simulator adds an interpolation checkbox. Watch the bot in your panel (cyan), first with interpolation off, then on. Then raise the jitter to 60 ms and the loss to 10%:

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: false, 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>

With interpolation on, the cyan circle glides, but it trails the dashed (true) position by noticeably more than before. Your own orange circle is still a round trip late and still steps: interpolation is for other entities. Your own needs prediction (next lessons).

Choosing the delay

Delay Effect
Less than one snapshot interval the buffer often runs dry: stutter returns
2 snapshot intervals (e.g. 100 ms at 20 Hz) survives one lost or late snapshot; a common default
3+ intervals survives bursts, but others look noticeably "behind", and shots feel unfair without lag compensation

Many games make the delay adaptive: measure how late snapshots arrive (jitter) and keep just enough buffer, or raise the snapshot rate to shrink the interval. Valve's Source engine, for example, exposes this as cl_interp/cl_interp_ratio, and the default ratio corresponds to two snapshot intervals.

When the buffer runs dry

During a burst of loss, renderTime passes the newest snapshot. You can hold the last position (safe, looks like a freeze) or extrapolate for a short while using the last velocity (Extrapolation & Dead Reckoning), then hold. Never extrapolate for long: a player who stopped would keep sliding into a wall.

Interpolating more than position

  • Rotations: interpolate angles along the shortest arc (wrap at 360°), quaternions with slerp or normalized lerp.
  • Teleports and respawns: send a "teleport counter" or flag and don't interpolate across it, or the player slides across the map.
  • Discrete state (animation state, weapon): switch at the snapshot whose time you passed, don't blend.
  • Events with a position (a shot fired, an explosion): play them at the render time too, so they line up with what the player sees.

Test yourself

Why does snapshot interpolation show other players slightly in the past?

  1. To save bandwidth
  2. So there is almost always a snapshot on each side of the render time to blend between
  3. Because the server is slow
  4. To make the game deterministic

Snapshots arrive at 20 Hz. Which interpolation delay is a common default?

  1. 5 ms
  2. 50 ms
  3. 100 ms
  4. 1 second

A player respawns on the other side of the map. What should interpolation do?

  1. Blend smoothly across the map
  2. Detect the teleport and jump directly instead of interpolating
  3. Extrapolate
  4. Freeze the player for a second