Real-Time & Streaming From Zero · Episode 06
State Sync & Interpolation
State Sync & Interpolation is Episode 06 of Real-Time & Streaming From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Here is the dirty secret of every multiplayer game you've ever played: the other players are not where you see them. They're a little bit in the past, faked forward with math, smeared between two snapshots that arrived late and out of order. Naive networking — "send my position, draw yours the instant it arrives" — feels awful: a stuttering, teleporting mess that gets worse the further away your friend sits. Good netcode takes that exact same stream of laggy packets and makes it feel buttery smooth. The difference is about thirty lines of code, and this episode is those thirty lines.
We'll do it with zero network. A host object orbits on the left —
that's the ground truth. We pump its state through a simulated-latency
channel (a setTimeout with jitter — the whole "network" is one
function) and try to reconstruct it on the right. Crank the latency slider to 200ms
and watch the raw remote turn into a strobing nightmare. Then flip on the
interpolation buffer and watch it go glassy-smooth at the same latency. By the
end you'll have built snapshots-at-a-tick-rate, an interpolation buffer that renders in
the past, and dead reckoning that extrapolates the future — the core of real netcode,
running entirely in one tab.
What you're looking at
The left half of the canvas is the host: a glowing dot steered along a wandering orbit, updated every animation frame at full 60fps. This is the "real" object — on a real game it would live on the authoritative server, or on the machine of the player who controls it. It never lags, because there's no network between you and it.
The right half is the remote: what a different player sees
of that same object, reconstructed only from the snapshots that dribble across our fake
network. The host packs its state into a tiny snapshot —
{x, y, vx, vy, t} — at the tick rate (5–30 times a
second, not 60), and each snapshot is delayed by the latency slider
plus a dash of random jitter before the remote is allowed to see it. A faint trail and
a dashed line show the error between where the remote draws the object and where it
truly is. Step the stage dropdown through all six and watch the
reconstruction go from broken to indistinguishable.
Stage 1 — The host (truth)
Nothing networked yet — just the source of truth, so you know what "correct" looks like. The host follows a slow Lissajous-ish wander so its velocity is always changing direction; that matters later, because direction changes are exactly where naive extrapolation falls on its face. Note the dot moves smoothly: it's a continuous function of time, sampled 60 times a second. The whole problem of netcode is that the remote never gets to see this continuous signal — only a handful of stale samples per second.
Stage 2 — Snapshots over a laggy channel
Now we start sending. At the tick rate, the host serializes its current state into a
snapshot and hands it to laggyChannel, which holds onto it for
latency + jitter milliseconds and then delivers it to the remote.
On screen you'll see the snapshots arrive as little pips on the right — sparse, late,
and slightly irregular in spacing because of the jitter. We haven't decided how to
draw the remote yet; this stage just shows the raw material we have to work
with. It's not much: at 10Hz with 120ms of lag, the remote is always reasoning about a
world that's at least an eighth of a second old, with gaps of 100ms between updates.
Stage 3 — Raw remote (the problem)
The obvious thing — and the wrong thing — is to draw the remote at the position of the latest snapshot you've received, the instant it arrives. Try it. Even at modest latency the remote teleports: it sits frozen between ticks, then snaps to the next snapshot's position, then freezes again. Crank latency to 300ms and drop the tick rate to 5Hz and it becomes a strobing horror. Nothing is technically "wrong" — every position it shows is a real position the host actually had — but the motion between them is gone, and motion is what your eye reads. This is naive multiplayer. This is why it feels bad.
Stage 4 — Interpolation buffer (the fix)
The trick is counter-intuitive: to look smooth, render in the past.
Instead of chasing the newest snapshot, we deliberately render what the world looked
like ~100ms ago — a time for which we usually have snapshots on both sides. We
keep a small buffer of recent snapshots, compute renderTime = now - delay,
find the two snapshots that straddle that time, and linearly interpolate
between them. The remote is now always moving toward a real position it has
already received, so it glides. Flip the interpolate checkbox on and off
at 200ms latency: same packets, same lag, but one is a slideshow and the other is
liquid. That little buffer is the single most important idea in netcode.
Stage 5 — Dead reckoning (hiding the delay)
Interpolation buys smoothness by paying ~100ms of lag — the remote is always a beat
behind the truth (watch the dashed error line in Stage 4; it's small but never zero).
Dead reckoning spends some of that back. Because each snapshot carries
velocity, we can extrapolate: take the most recent state and project it forward
by position + velocity × dt to guess where the object is right now.
When the host moves in a straight line, this is nearly perfect and the error collapses.
But watch what happens at the corners of the orbit: the prediction overshoots
and has to be yanked back when the next snapshot disagrees. That overshoot-and-correct
is the fundamental tension of extrapolation, and why real games clamp it.
Stage 6 — The lab
All the knobs, live. Host on the left, your reconstructed remote on the right, with the running position error printed in the badge. Slide latency from 0 to 400ms with interpolation on and watch the error stay bounded and the motion stay smooth. Turn interpolation off and the same latency shatters it. Toggle extrapolation and watch the error shrink on the straights and spike on the turns. Drop the tick rate to 5Hz and see how interpolation papers over the gaps that wreck the raw remote. This is the playground where netcode intuition actually forms — there are no wrong settings, only tradeoffs to feel.
How the code works
Four small pieces do all the work. None of them know anything about WebRTC, sockets, or servers — they operate on a stream of snapshot objects, so the same code runs identically over our fake channel or a real data channel from Episode 04. Swapping the transport changes nothing about the netcode.
(a) The simulated-latency channel
The entire "network" is this function. It takes a handler (the remote's
receive callback) and a getLatency getter wired to the slider, and returns
a send function. Every message is delivered after latency plus
up to 30% extra random jitter — because real networks don't deliver at
a fixed delay, they wobble, and that wobble is half of what makes raw rendering ugly:
// A fake network in one function: delay + jitter, no server.
function laggyChannel(handler, getLatency) {
return function send(msg) {
const base = getLatency(); // slider value, ms
const jitter = Math.random() * base * 0.3; // up to +30%
setTimeout(() => handler(msg), base + jitter);
};
}
// remote.receive pushes each snapshot into its buffer (sorted by t)
const send = laggyChannel(remote.receive, () => latencyMs);
(b) The snapshot send loop (fixed tick rate)
Crucially, we do not send a packet every frame. We send at a fixed
tick rate — a real server might tick 20 or 64 times a second while
clients render at 60, 120, or 144fps. Tick rate and frame rate are different clocks. We
drive the tick off accumulated time so it's independent of how fast
requestAnimationFrame happens to be running:
// Called every animation frame; only emits at the tick rate.
let tickAcc = 0;
function maybeSendSnapshot(dt) {
tickAcc += dt;
const tickInterval = 1 / tickRateHz; // e.g. 0.1s at 10Hz
while (tickAcc >= tickInterval) {
tickAcc -= tickInterval;
send({ // the whole snapshot
x: host.x, y: host.y,
vx: host.vx, vy: host.vy, // velocity → enables dead reckoning
t: performance.now(), // timestamp → enables interpolation
});
}
}
(c) The interpolation buffer
This is the heart of it. We render the world as it was delay ms ago,
where delay is comfortably larger than one tick interval (so two snapshots
have almost always arrived). We scan the buffer for the pair that straddle
that render time and lerp between them by the fraction of the way renderTime
sits between their timestamps:
// Render ~100ms in the PAST and lerp between the two surrounding snapshots.
function sampleBuffer(buf, now, delay) {
const renderTime = now - delay; // deliberately behind
// find a, b such that a.t <= renderTime <= b.t
for (let i = 0; i < buf.length - 1; i++) {
const a = buf[i], b = buf[i + 1];
if (a.t <= renderTime && renderTime <= b.t) {
const u = (renderTime - a.t) / (b.t - a.t); // 0..1
return {
x: a.x + (b.x - a.x) * u, // straight lerp
y: a.y + (b.y - a.y) * u,
};
}
}
return buf[buf.length - 1]; // fell off the end → newest
}
(d) Dead reckoning
When you want to hide the interpolation delay (or you've run out of buffered
snapshots to interpolate between), extrapolate from the newest snapshot using its
velocity. The math is a one-liner — the discipline is in the clamp, which
caps how far into the future you're willing to guess so a stale packet can't fling the
object off into the distance:
// Project the latest known state forward by its velocity.
function deadReckon(latest, now) {
let dt = (now - latest.t) / 1000; // seconds since that snapshot
dt = Math.min(dt, 0.25); // CLAMP: never guess >250ms ahead
return {
x: latest.x + latest.vx * dt, // pos + vel·dt
y: latest.y + latest.vy * dt,
};
}
Real engines blend these: interpolate when you have snapshots straddling render time, dead-reckon past the newest one, and smooth the seam between them (and the correction when a prediction was wrong) so the player never sees a pop. But the two primitives above — lerp the past, extrapolate the future — are the whole vocabulary.
Common pitfalls
- Rendering raw packets = jitter. Drawing the latest snapshot the instant it lands (Stage 3) guarantees teleporting, because snapshots are sparse and jittery. Always buffer and interpolate (or extrapolate) — never snap the visible object straight to a received packet.
- Interpolation delay is a tradeoff, not free. Rendering in the past buys smoothness by adding latency — your remote is always ~100ms behind truth. Too small a delay and the buffer underruns (you have nothing to lerp toward and stutter anyway); too large and the world feels sluggish. Tune the delay to a bit more than one tick interval plus expected jitter.
- Extrapolation overshoots on direction changes. Dead reckoning
assumes constant velocity, so it sails straight through every corner and must be
snapped back when reality disagrees (watch Stage 5's turns). Always
clamphow far ahead you predict, and smooth the correction so the snap-back isn't a visible pop. - Tick rate ≠ frame rate. You render at 60–144fps but the network
ticks far slower (often 10–64Hz). Drive the send loop off accumulated time, not off
requestAnimationFrame, or your packet rate will silently scale with the client's monitor. - The buffer must hold ≥2 snapshots. Interpolation needs a
snapshot on each side of
renderTime. If the buffer ever holds fewer than two valid samples around that time you can't lerp — handle the underrun (hold last, or fall back to extrapolation) instead of jumping to the newest. - Clock skew between peers. We cheat here by using one
performance.now()for both ends. Across real machines, two clocks disagree, so you can't compare a remote timestamp to your localnowdirectly — estimate the offset (and round-trip time) during a handshake and convert remote timestamps into your own clock before sampling.
Exercises
- Packet loss. In
maybeSendSnapshot, drop a snapshot randomly (if (Math.random() < lossRate) return;) before callingsend. Add a 0–30% loss slider. Watch how interpolation tolerates loss gracefully (it just spans a wider gap) while the raw remote freezes longer — then push loss high enough to starve the buffer and see the underrun. - Visualize the buffer. Draw every snapshot currently in the
remote's buffer as a faint dot, mark
renderTimeon the timeline, and highlight the two snapshots being interpolated between. Seeing the "render head" trail the newest packet makes the past-rendering idea click instantly. - Server reconciliation. Add a locally-controlled object: move it with the arrow keys, predict its motion immediately (client-side prediction), but also send your inputs through the laggy channel to the "server" copy. When the authoritative position comes back, reconcile — snap to the server state and replay any inputs newer than it. This is how shooters make your own movement feel zero-latency while staying server-authoritative.
What's next
Episode 07 — Broadcast & Recording: build your own OBS. We leave
netcode behind and turn the camera on ourselves: compositing multiple sources onto a
canvas, capturing that canvas as a MediaStream, mixing in audio, and
recording the whole thing to a downloadable file with MediaRecorder — a
miniature streaming studio in the browser, no server required.