Worlds, AI and multiplayer · 5 MIN READ

Client prediction replays unacknowledged inputs; remote players are interpolated from the past

Hide round-trip latency by predicting local movement, reconcile with acknowledged server snapshots by replaying pending inputs, and draw remote players by interpolating a snapshot buffer.

The authoritative server from the previous lesson is fair but feels slow. With 50 ms of latency each way, a player presses right and nothing moves for a tenth of a second. Client-side prediction runs the same movement rule locally so the press responds at once, reconciliation fixes the prediction when the server disagrees, and interpolation shows other players smoothly, slightly in the past. They solve three different problems with three different pieces of state.

gamedev · A MAP OF THE IDEA

  1. Predict and buffer input
  2. Reset to server snapshot
  3. Replay inputs after ack
  4. Interpolate remote players

Useful when

  • Local movement responds on the same tick as the input.
  • Corrections are limited to real server disagreement.

Watch out

  • Prediction needs identical movement code on both sides.
  • Remote players are shown in the past; hits need lag compensation.

Implementation & operation cost: A pending-input buffer, a snapshot buffer and replay work proportional to the round-trip time on every snapshot.

01

Three techniques, three pieces of client state

Prediction needs the local player's predicted state and a buffer of inputs that were sent but not yet acknowledged. Reconciliation needs each snapshot to carry the server's state for this player plus the last input sequence the server applied, the ack. Interpolation needs a short buffer of snapshots of the remote entities, each tagged with its server tick. The local player is drawn at the predicted present; everyone else is drawn at a deliberate point in the past, where two real snapshots surround the render time. Mixing those up causes familiar bugs: predicting remote players makes them jitter and snap whenever they change direction, and interpolating your own character makes the controls feel delayed.

02

A deterministic network with fixed latency

The program simulates both ends in one loop, with a one-way latency of 3 ticks and a snapshot every 2 ticks. The client presses right for ten ticks. At server tick 5 a door at x = 6 closes, which the client cannot predict. A second player runs right for five ticks and then turns back. Each snapshot arrival prints the reconciliation, and the remote lines show what the client draws for the other player next to what was true at that moment and what is true now.

go
package main

import "fmt"

const (
	latency     = 3 // one-way delay in ticks, in both directions
	snapEvery   = 2 // the server sends a snapshot every second tick
	interpDelay = 2 // remote entities are drawn this far behind the newest server time
	doorX       = 6.0
)

type Input struct {
	Seq int
	DX  float64
}

type Snapshot struct {
	Tick       int
	X          float64 // this client's player, authoritative
	Ack        int     // last input sequence the server applied
	DoorClosed bool
	RemoteX    float64 // another player, for interpolation
}

// Move is the single movement rule compiled into both client and server.
func Move(x float64, in Input, doorClosed bool) float64 {
	next := x + in.DX
	if doorClosed && x <= doorX && next > doorX {
		next = doorX
	}
	return next
}

type Client struct {
	X          float64
	pending    []Input // sent but not yet acknowledged, oldest first
	doorClosed bool
	remote     []Snapshot
}

func (c *Client) Predict(in Input) {
	c.pending = append(c.pending, in)
	c.X = Move(c.X, in, c.doorClosed)
}

// Reconcile rewinds to the server's state and replays unacknowledged inputs.
func (c *Client) Reconcile(s Snapshot) (replayed int, before float64) {
	before = c.X
	c.X, c.doorClosed = s.X, s.DoorClosed
	keep := c.pending[:0]
	for _, in := range c.pending {
		if in.Seq > s.Ack {
			keep = append(keep, in)
		}
	}
	c.pending = keep
	for _, in := range c.pending {
		c.X = Move(c.X, in, c.doorClosed)
	}
	c.remote = append(c.remote, s)
	return len(c.pending), before
}

// RemoteAt interpolates between the two buffered snapshots around time t.
func (c *Client) RemoteAt(t float64) float64 {
	for len(c.remote) > 2 && float64(c.remote[1].Tick) <= t {
		c.remote = c.remote[1:] // older snapshots can never be needed again
	}
	a := c.remote[0]
	if len(c.remote) == 1 || t <= float64(a.Tick) {
		return a.RemoteX
	}
	b := c.remote[1]
	if t >= float64(b.Tick) {
		return b.RemoteX // no newer data: hold rather than guess
	}
	alpha := (t - float64(a.Tick)) / float64(b.Tick-a.Tick)
	return a.RemoteX + (b.RemoteX-a.RemoteX)*alpha
}

type Server struct {
	tick       int
	x          float64
	ack        int
	doorClosed bool
	remoteX    float64
}

func (s *Server) Step(arrived []Input) {
	s.tick++
	if s.tick == 5 {
		s.doorClosed = true // an event the client cannot predict
	}
	for _, in := range arrived {
		if in.Seq > s.ack {
			s.x = Move(s.x, in, s.doorClosed)
			s.ack = in.Seq
		}
	}
	if s.tick <= 5 {
		s.remoteX += 2 // the other player runs right, then turns back
	} else {
		s.remoteX -= 2
	}
}

func (s *Server) Snapshot() Snapshot {
	return Snapshot{Tick: s.tick, X: s.x, Ack: s.ack, DoorClosed: s.doorClosed, RemoteX: s.remoteX}
}

// packet is a message on a link with a fixed delivery tick.
type packet[T any] struct {
	at int
	v  T
}

func deliver[T any](queue []packet[T], now int) (rest []packet[T], due []T) {
	for _, p := range queue {
		if p.at == now {
			due = append(due, p.v)
		} else {
			rest = append(rest, p)
		}
	}
	return rest, due
}

func main() {
	srv := &Server{remoteX: 10}
	cl := &Client{}
	var toServer []packet[Input]
	var toClient []packet[Snapshot]
	var remoteLines []string
	history := []float64{srv.remoteX} // server-side truth per tick, for comparison only

	for tick := 1; tick <= 17; tick++ {
		var inputs []Input
		toServer, inputs = deliver(toServer, tick)
		srv.Step(inputs)
		history = append(history, srv.remoteX)
		if tick%snapEvery == 0 {
			toClient = append(toClient, packet[Snapshot]{tick + latency, srv.Snapshot()})
		}

		var snaps []Snapshot
		toClient, snaps = deliver(toClient, tick)
		for _, s := range snaps {
			replayed, before := cl.Reconcile(s)
			door := "open"
			if s.DoorClosed {
				door = "closed"
			}
			fmt.Printf("t=%d snapshot@%d x=%.1f ack=%d door %s: replay %d -> %.1f (was %.1f, corrected %.1f)\n",
				tick, s.Tick, s.X, s.Ack, door, replayed, cl.X, before, before-cl.X)
		}
		if tick <= 10 {
			in := Input{Seq: tick, DX: 1}
			cl.Predict(in)
			toServer = append(toServer, packet[Input]{tick + latency, in})
		}
		if tick >= 8 && tick <= 11 {
			renderAt := float64(tick - latency - interpDelay)
			remoteLines = append(remoteLines, fmt.Sprintf("t=%d remote drawn at server time %.0f: %.1f (true then %.1f, live now %.1f)",
				tick, renderAt, cl.RemoteAt(renderAt), history[int(renderAt)], srv.remoteX))
		}
	}
	for _, line := range remoteLines {
		fmt.Println(line)
	}
	fmt.Printf("after the last ack: client %.1f, server %.1f, pending %d\n", cl.X, srv.x, len(cl.pending))
}
Read the code

Predict appends the input to pending and moves immediately with the shared Move function. Reconcile resets to the snapshot's position and door state, keeps only inputs after the ack and replays them. Until the door closes the replay lands exactly on the prediction, so the correction is 0.0. At t=9 the snapshot from server tick 6 reports x=3.0, ack 3 and a closed door; replaying inputs 4 to 8 stops at the door, so the predicted 8.0 is corrected by 2.0 and later predictions stay at 6.0. The remote player is drawn at server time t - latency - interpDelay. At t=10 that is time 5, between the snapshots for ticks 4 and 6, which are both 18.0, so the true peak of 20.0 never appears: interpolation smooths over events that fall between snapshots. After the last ack, pending is empty and client and server agree.

03

Reconcile by replaying, then smooth what the player sees

Snapping to the server position without a replay would discard every input still in flight and pull the character back by a full round trip on every snapshot. Replaying pending inputs on top of the authoritative state keeps corrections small: only the part the server actually disagreed with changes. That works only if client and server run the same movement code, which is easy in Go when both binaries import one simulation package. Bound the pending buffer to a few hundred milliseconds of inputs and treat overflow as a broken connection. Ignore any snapshot older than one already applied; this program never needs that check because its link never reorders. Keep the simulation state snapped to the corrected value, but let the rendered position chase it over a few frames, so a 2-unit correction looks like a slight drift rather than a teleport, and snap the rendered position too when the error is large, such as after a respawn.

04

Remote players live in the past on purpose

The client never sees other players' inputs, so it cannot predict them well. Instead it draws them at a render time behind the newest snapshot and interpolates between the two snapshots that bracket it. The delay must cover the snapshot interval plus network jitter; many games use two intervals so that one lost packet does not empty the buffer, while this program uses one to keep the output short. When the buffer runs dry, hold the last position or extrapolate for a short, capped time, then hold. The delay has a visible cost: you see opponents where they were, so a shot aimed at them would miss on the server unless the server performs lag compensation, rewinding other players to the moment the shooter saw before testing the hit. That decision is a fairness trade-off between shooter and target, and it belongs on the server, never in the client.

05

How much determinism you need, and how to test it

Prediction tolerates small divergence because reconciliation corrects it. Lockstep networking, where peers exchange only inputs, does not: it needs bit-identical simulation on every machine, which in Go means iterating slices instead of maps, avoiding goroutine-dependent order and remembering that floating-point fusion can differ between arm64 and amd64 builds. Test netcode the way this program runs: a simulated link with configurable latency, jitter, loss and reordering driven by a seeded generator, with no sockets and no sleeps. Assert convergence, meaning that after inputs stop and messages drain, client and server agree and pending is empty; assert zero corrections when no server-only event happens; and assert bounded corrections when one does. Then add adversarial schedules: a snapshot lost right before the door event, two snapshots arriving in one tick and a snapshot older than one already applied.

TAKE THIS WITH YOU

Predict the local player with shared movement code, keep unacknowledged inputs, reconcile by resetting to the server state and replaying inputs after the ack, and draw remote players interpolated between buffered snapshots at a fixed delay.

Check your understanding

A snapshot arrives with the server position and ack = 3 while the client has already sent inputs up to 8. What should the client do?

Go to the source

Progress stays in this browser. No account needed.