TExcelTAD
Home › Multiplayer Game Networking › Server Reconciliation

Server Reconciliation

Client-side prediction makes your character respond instantly, but naive prediction rubber-bands, because every snapshot describes the past. Server reconciliation fixes it with one more piece of bookkeeping:

  1. The client keeps a list of the inputs it has sent but the server hasn't confirmed yet (pending inputs).
  2. Each snapshot includes the sequence number of the last input the server processed for this client.
  3. When a snapshot arrives, the client:
    • drops all pending inputs up to and including that number (the server has applied them);
    • sets its character to the server's position, which is correct as of that input;
    • replays the remaining pending inputs on top, with the same movement code.

If nothing unexpected happened, the replay lands exactly where the prediction already was, and the player sees no correction at all. If something did happen (the server's version of the world differed, for example another player blocked the way), the client ends up at the corrected position plus its newer inputs.

It is the same idea as rollback, applied to a single entity with the server as the authority.

Tick by tick

The same scenario as the prediction lesson: RTT 4 ticks, snapshots every other tick, Right held for 9 ticks. This time the snapshot carries ack, and the client replays. And to make it interesting, the server knows something the client doesn't: a puddle at x ≥ 12 that halves the speed (say, it was just created and the client hasn't heard about it yet):

ts · try it yourself
const SPEED = 2, ONE_WAY = 2;
type Input = { seq: number; move: number };
type Snap = { arrive: number; x: number; ack: number };

const serverMove = (x: number, move: number) => x + move * (x >= 12 ? SPEED / 2 : SPEED);  // server knows the puddle
const clientMove = (x: number, move: number) => x + move * SPEED;                            // client doesn't (yet)

const inFlight: { arrive: number; input: Input }[] = [];
const snaps: Snap[] = [];
let serverX = 0, lastProcessed = -1;
let shown = 0;
let pending: Input[] = [];

for (let tick = 0; tick < 14; tick++) {
  const input: Input = { seq: tick, move: tick < 9 ? 1 : 0 };
  let note = '';

  for (const s of snaps.filter((s) => s.arrive === tick)) {
    pending = pending.filter((i) => i.seq > s.ack);          // the server has applied these
    let x = s.x;
    for (const i of pending) x = clientMove(x, i.move);       // replay what it hasn't seen yet
    const correction = x - shown;
    note = `snapshot x=${s.x} ack=${s.ack}, replay ${pending.length} -> ${x}` + (correction ? `  CORRECTION ${correction}` : '');
    shown = x;
  }
  shown = clientMove(shown, input.move);                      // predict this tick
  pending.push(input);
  inFlight.push({ arrive: tick + ONE_WAY, input });

  for (const p of inFlight.filter((p) => p.arrive === tick)) {
    serverX = serverMove(serverX, p.input.move);
    lastProcessed = p.input.seq;
  }
  if (tick % 2 === 0) snaps.push({ arrive: tick + ONE_WAY, x: serverX, ack: lastProcessed });

  console.log(`tick ${String(tick).padStart(2)}: shown x=${String(shown).padStart(2)}  server x=${String(serverX).padStart(2)}  ${note}`);
}
tick  0: shown x= 2  server x= 0
tick  1: shown x= 4  server x= 0
tick  2: shown x= 6  server x= 2  snapshot x=0 ack=-1, replay 2 -> 4
tick  3: shown x= 8  server x= 4
tick  4: shown x=10  server x= 6  snapshot x=2 ack=0, replay 3 -> 8
tick  5: shown x=12  server x= 8
tick  6: shown x=14  server x=10  snapshot x=6 ack=2, replay 3 -> 12
tick  7: shown x=16  server x=12
tick  8: shown x=18  server x=13  snapshot x=10 ack=4, replay 3 -> 16
tick  9: shown x=18  server x=14
tick 10: shown x=17  server x=15  snapshot x=13 ack=6, replay 3 -> 17  CORRECTION -1
tick 11: shown x=17  server x=15
tick 12: shown x=15  server x=15  snapshot x=15 ack=8, replay 3 -> 15  CORRECTION -2
tick 13: shown x=15  server x=15

While the client's and server's rules agree (until x = 12), every snapshot reconciles to exactly the predicted position: no correction, no rubber-banding, even though each snapshot is old. When the puddle slows the server's character, the snapshots start to disagree, and each one corrects the client by a little (−1, then −2), until the client ends where the server says, at x = 15 instead of 18. The correction happens once per disagreement, not on every snapshot.

Try it: the complete simulator

This version has all three switches. Turn on prediction and reconciliation (and interpolation for the bot), set 150 ms and 2% loss, and move around: your circle responds instantly and sits exactly on the dashed server position once you stop. Then try:

  • Reconciliation off: the rubber-banding from the previous lesson comes back.
  • Loss 20%: occasionally all three copies of an input are lost; the server never applies it, so the next snapshot carries a small correction (watch "last correction").
  • RTT 500, jitter 100: prediction keeps your movement instant; the bot looks sluggish, because interpolation shows it in the past.
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: true, predict: true, reconcile: false };

// ---- 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>

Making corrections invisible

Even with reconciliation, corrections happen: lost inputs, collisions with other players, server-side effects (knockback, slows). Snapping the character by a few units is jarring. Common remedies:

  • Smooth the visual error: keep the simulated position exact, but draw the character at simulated + offset, where offset starts at the size of the correction and decays to zero over 100–200 ms (as in extrapolation). The camera, often attached to the character, must follow the smoothed position.
  • Ignore tiny errors: if the correction is below a threshold (a centimetre), keep the prediction; quantization noise otherwise causes constant micro-corrections.
  • Predict more of the world: if other players' collisions cause most corrections, predict collisions with their (interpolated) positions too, or simply make players not collide with each other (many games do this for exactly this reason).

Costs and gotchas

  • Replay cost: with 150 ms RTT at 60 Hz there are about 9 pending inputs, so each snapshot replays ~9 ticks of movement for the local player. Cheap for a character controller, expensive if "movement" means a full physics step. Engines with physics prediction (Unity's Netcode for Entities, Photon Fusion, Unreal's newer networked physics) roll back and re-simulate the physics scene, which has to be budgeted.
  • The movement code must be a pure function of (state, input). If it reads Time.deltaTime, the frame rate, or a random number, replay produces a different result and you get corrections every snapshot. Pass the fixed tick length in.
  • Everything that affects movement must be in the replayed state: velocity, "is grounded", dash cooldown, jump buffer timers. Reconcile the whole movement state, not just the position.

Test yourself

When a snapshot arrives, what does a reconciling client do with its pending inputs?

  1. Discards all of them
  2. Drops those the server has acknowledged and replays the rest on top of the server's position
  3. Sends them all again reliably
  4. Applies them to other players

Client and server agree on all movement rules. How large is the correction when a snapshot arrives?

  1. One RTT of movement
  2. Zero: replaying the pending inputs reproduces the predicted position
  3. Half an RTT of movement
  4. It depends on the snapshot rate

Why does movement code that reads the frame's delta time break reconciliation?

  1. It is slower
  2. Replays happen within one frame, so they would use a different delta than the original ticks and diverge
  3. The server can't read delta time
  4. It uses too much memory