TExcelTAD
Home › Multiplayer Game Networking › Deterministic Lockstep

Deterministic Lockstep

Strategy games have a problem shooters don't: thousands of units. Sending their positions 20 times a second would never fit in anyone's bandwidth. Deterministic lockstep sends no game state at all. Every machine runs the same simulation from the same starting state with the same inputs, in the same order, and therefore ends up in the same state. Only the inputs travel ("select units 4–9, move to (120, 44)"), so the bandwidth doesn't depend on the number of units.

It powered classic RTS games and is still used for RTS, many sports and fighting games (as the base for rollback) and some co-op games.

The rules of lockstep

  1. The simulation advances in numbered ticks.
  2. A tick can only be simulated when every player's input for that tick is known (an empty input counts, and must be sent too).
  3. To hide latency, input is scheduled with an input delay: what you do on tick t takes effect on tick t + D. That gives your input D ticks to reach everyone else.
  4. If someone's input still hasn't arrived, everyone waits (the game "stalls"). The slowest connection sets the pace for all.

Here two peers play with an input delay of 3 ticks. Each input packet takes 1 to 4 ticks to cross (seeded jitter). Watch when peer A has to wait:

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(21);
const DELAY = 3;

// inputs[peer] = map from sim tick to that peer's command, as known by peer A
const knownByA = [new Map<number, string>(), new Map<number, string>()];
const pendingFromB: { arrive: number; tick: number; cmd: string }[] = [];
for (let t = 0; t < DELAY; t++) { knownByA[0].set(t, '-'); knownByA[1].set(t, '-'); }  // the first D ticks are empty

let simTick = 0;
for (let frame = 0; frame < 12; frame++) {
  // Both peers sample input for tick frame + DELAY. A knows its own at once; B's travels.
  const target = frame + DELAY;
  knownByA[0].set(target, frame === 2 ? 'A:build' : '-');
  pendingFromB.push({ arrive: frame + 1 + Math.floor(rnd() * 4), tick: target, cmd: frame === 4 ? 'B:attack' : '-' });
  for (const p of pendingFromB.filter((p) => p.arrive === frame)) knownByA[1].set(p.tick, p.cmd);

  // A simulates as many ticks as it has complete inputs for (at most one per frame here).
  let line = `frame ${String(frame).padStart(2)}: `;
  if (knownByA[0].has(simTick) && knownByA[1].has(simTick)) {
    const cmds = [knownByA[0].get(simTick), knownByA[1].get(simTick)].filter((c) => c !== '-');
    line += `simulate tick ${simTick} ${cmds.length ? cmds.join(' ') : ''}`;
    simTick++;
  } else {
    line += `STALL waiting for B's input for tick ${simTick}`;
  }
  console.log(line.trimEnd());
}
frame  0: simulate tick 0
frame  1: simulate tick 1
frame  2: simulate tick 2
frame  3: simulate tick 3
frame  4: simulate tick 4
frame  5: simulate tick 5 A:build
frame  6: simulate tick 6
frame  7: simulate tick 7 B:attack
frame  8: STALL waiting for B's input for tick 8
frame  9: simulate tick 8
frame 10: simulate tick 9
frame 11: simulate tick 10

The input delay hides most of the latency, but whenever one packet takes longer than the delay, the whole game freezes for a frame. Real games pick the delay from the measured RTT and jitter, adjust it during the match, and show a "waiting for player" indicator if a stall lasts.

The other cost is feel: every command reacts D ticks late. That's fine for clicking on a map (RTS players accept 100–200 ms), and unacceptable for a fighting game, which is why fighting games add rollback on top.

Determinism is the hard part

Lockstep only works if the simulation is bit-for-bit identical on every machine. Anything that can differ will eventually desync the game:

Source of desync Fix
Floating point differs between CPUs, compilers, optimization flags, or Math.sin implementations fixed-point math, or strictly controlled floats on one platform and compiler
Iterating a hash map or set whose order depends on memory addresses or insertion iterate in a defined order (sorted ids, arrays)
Unseeded or shared random numbers one seeded RNG for the simulation, never used by UI or audio
Reading the clock, frame time or deltaTime inside the sim fixed tick, no wall clock
UI or local-only code touching game state strict separation: the sim only changes from inputs

Even the order of additions changes a float result. Here is the same sum in two orders, as two peers iterating a set differently might compute it:

ts · try it yourself
const damage = [0.1, 0.2, 0.3];
const peerA = damage.reduce((s, d) => s + d, 0);
const peerB = [...damage].reverse().reduce((s, d) => s + d, 0);
console.log(peerA, peerB, peerA === peerB ? 'in sync' : 'DESYNC');

// The same in fixed point (thousandths stored as integers) is exact in any order.
const fixed = damage.map((d) => Math.round(d * 1000));
const fa = fixed.reduce((s, d) => s + d, 0), fb = [...fixed].reverse().reduce((s, d) => s + d, 0);
console.log(fa, fb, fa === fb ? 'in sync' : 'DESYNC');
0.6000000000000001 0.6 DESYNC
600 600 in sync

Detecting desyncs: checksums

Because a desync is silent at first (a unit is 0.0001 off, and ten minutes later a battle goes differently), peers exchange a checksum of the game state every few ticks. A mismatch is reported immediately with the tick number, which makes the bug reproducible from the input log.

csharp · try it yourself
using System;

// A tiny fixed-point simulation (Q16.16): positions and speeds are integers scaled by 65536.
const int One = 1 << 16;
static int Mul(int a, int b) => (int)(((long)a * b) >> 16);

static uint Checksum(int[] xs)
{
    uint h = 2166136261;                       // FNV-1a over the raw integers
    foreach (int x in xs)
        for (int i = 0; i < 4; i++) { h ^= (byte)(x >> (8 * i)); h *= 16777619; }
    return h;
}

int[] peerA = { 10 * One, 20 * One, 30 * One };
int[] peerB = { 10 * One, 20 * One, 30 * One };
int speed = One * 3 / 2, friction = One * 9 / 10;   // 1.5 and 0.9

for (int tick = 1; tick <= 4; tick++)
{
    for (int i = 0; i < 3; i++)
    {
        peerA[i] += Mul(speed, friction);
        peerB[i] += Mul(speed, friction);
    }
    if (tick == 3) peerB[1] += 1;               // a bug on peer B: off by 1/65536 of a unit
    uint a = Checksum(peerA), b = Checksum(peerB);
    Console.WriteLine(
quot;tick {tick}: A {a:X8} B {b:X8} {(a == b ? "ok" : "DESYNC at tick " + tick)}"); }
tick 1: A F05A633E  B F05A633E  ok
tick 2: A B6C48838  B B6C48838  ok
tick 3: A BC29E746  B 1493BC31  DESYNC at tick 3
tick 4: A 2787F8F6  B 3A89BBA7  DESYNC at tick 4

An error of 1/65536 of a unit is invisible on screen but caught by the checksum on the exact tick it happened.

Joining, replays and spectators

  • Late joining is hard: a new player needs the full state (or the whole input log replayed from the start).
  • Replays are almost free: store the inputs, replay them through the same simulation. That's why RTS replay files are tiny.
  • Spectators can receive the input stream with a delay, which also prevents "ghosting" (a spectator telling a player what the enemy is doing).

Test yourself

What does lockstep send over the network every tick?

  1. Every unit's position
  2. Only each player's inputs (commands) for that tick
  3. A full snapshot
  4. Nothing

Why can iterating a hash set cause a desync?

  1. Hash sets are slow
  2. Different peers may iterate in different orders, so floating-point results and event order differ
  3. Hash sets can't be serialized
  4. It can't

With an input delay of 4 ticks at 30 Hz, how much later does a command take effect?

  1. 4 ms
  2. about 33 ms
  3. about 133 ms
  4. 4 seconds