Client-Side Prediction
In the lag simulator's first version, your own character waited a full round trip before moving. Client-side prediction removes that wait: the client applies your input to your own character immediately, with the same movement code the server runs, and sends the input to the server as usual. If the simulation is the same on both sides, the server will arrive at the same position a round trip later, and the player never sees the delay.
It is the single most important trick for making an online game feel responsive, and every engine's netcode supports it in some form.
What makes prediction possible
- Shared, deterministic-enough movement code. The client must compute the same result as the server for the same inputs. Not bit-exact like lockstep, but close: small differences are corrected later.
- Inputs with sequence numbers. Every input gets an increasing number, so the server can say "I've processed up to input 41".
- Only predict what you control. Your own movement, your own weapon's muzzle flash and recoil. Not other players, not whether your shot killed someone, not pickups another player might grab first.
The catch: snapshots describe the past
The problem appears as soon as a snapshot arrives. It says "you are at x = 40", but that is where the server had you after the inputs it had received, which is half an RTT of inputs behind what you have already predicted. If the client simply accepts the server's position, the character jumps back, then moves forward again with the next local inputs, over and over. That's the classic rubber-banding of naive prediction:
const SPEED = 2; // units per tick
const ONE_WAY = 2; // ticks for a packet to cross, each way (RTT = 4 ticks)
type Snap = { arrive: number; x: number };
const inputsInFlight: { arrive: number; move: number }[] = [];
const snapsInFlight: Snap[] = [];
let serverX = 0, shown = 0, intended = 0;
for (let tick = 0; tick < 14; tick++) {
const move = tick < 9 ? 1 : 0; // hold Right for 9 ticks
let note = '';
// Client: apply any snapshot that arrived (naively), then predict this tick's input.
for (const s of snapsInFlight.filter((s) => s.arrive === tick)) {
note = `snapshot x=${s.x}, jump ${s.x - shown >= 0 ? '+' : ''}${s.x - shown}`;
shown = s.x; // accept the server's position as is
}
shown += move * SPEED;
intended += move * SPEED; // where the player expects to be
inputsInFlight.push({ arrive: tick + ONE_WAY, move });
// Server: apply inputs that arrived; send a snapshot every other tick.
for (const i of inputsInFlight.filter((i) => i.arrive === tick)) serverX += i.move * SPEED;
if (tick % 2 === 0) snapsInFlight.push({ arrive: tick + ONE_WAY, x: serverX });
console.log(`tick ${String(tick).padStart(2)}: key ${move ? 'held' : 'up '} shown x=${String(shown).padStart(2)} intended x=${String(intended).padStart(2)} ${note}`);
}tick 0: key held shown x= 2 intended x= 2
tick 1: key held shown x= 4 intended x= 4
tick 2: key held shown x= 2 intended x= 6 snapshot x=0, jump -4
tick 3: key held shown x= 4 intended x= 8
tick 4: key held shown x= 4 intended x=10 snapshot x=2, jump -2
tick 5: key held shown x= 6 intended x=12
tick 6: key held shown x= 8 intended x=14 snapshot x=6, jump +0
tick 7: key held shown x=10 intended x=16
tick 8: key held shown x=12 intended x=18 snapshot x=10, jump +0
tick 9: key up shown x=12 intended x=18
tick 10: key up shown x=14 intended x=18 snapshot x=14, jump +2
tick 11: key up shown x=14 intended x=18
tick 12: key up shown x=18 intended x=18 snapshot x=18, jump +4
tick 13: key up shown x=18 intended x=18
The first snapshots drag the character back (−4, then −2). While the key is held, every snapshot throws away the inputs still in flight, so the shown position settles about 6 units behind where the player intended: prediction bought almost nothing. After the key is released, the character lurches forward (+2, +4) as the server catches up. In a real game, with snapshots arriving at uneven times, that shows up as a character vibrating while it moves, worse at higher ping and higher speed.
Try it
This version adds a prediction checkbox (interpolation stays on for the bot). Turn prediction on, hold Right, and watch your orange circle. At 150 ms you'll see it shiver back and forth around the dashed server position. Raise the RTT to 400 ms and it becomes violent:
<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: false, 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 prediction on, the response to your keys is instant, which is exactly what we wanted. But the corrections ("last correction" in the panel) are large while you move, and zero when you stand still. The next lesson removes them without giving up the instant response.
What to predict, what not to
| Predict on the client | Wait for the server |
|---|---|
| your movement, jumping, crouching | damage, deaths, scores |
| camera and aim (never round-trip the camera!) | other players' actions |
| your weapon's animation, muzzle flash, sound, recoil | whether a hit counted (show a "hit marker" only on confirmation, or predict it and accept occasional false markers) |
| spending your ammo, starting a cooldown | picking up contested items, opening shared doors (or predict and roll back) |
| spawning a projectile locally (then match it to the server's) | anything random: unless the RNG seed is shared, the client can't know the result |
Predicting a little too much is fine if corrections are rare and cheap to undo. Predicting things the client can't know (a door another player is also opening) creates visible mistakes that feel worse than a short delay.
Test yourself
What does client-side prediction do?
- Guesses other players' positions in the future
- Applies the local player's input immediately with the same movement code the server runs
- Delays inputs so everyone has them
- Compresses snapshots
Why does naive prediction rubber-band when a snapshot arrives?
- The server uses different physics
- The snapshot reflects only the inputs the server had received, so it is behind the prediction by the inputs still in flight
- Snapshots are compressed
- The client clock is wrong
Which of these should usually NOT be predicted by the client?
- The local player's movement
- The local camera
- Whether another player died
- The local weapon's muzzle flash