AlgoViz

Design Multiplayer Game State Sync

hard 50 min

Let a hundred people share one moving world although their messages take 20 to 200 milliseconds.

See it run

Follow a key press, a snapshot, a shot and a wrong guess, then two snapshots and a delta.

Operations

A key press

Shown at once, decided by the server.

Step 1 of 6

Forward

Our systemClient AClient BMatch process60 ticks a secondHistory ring1 secondDelta coderper player

input

1234 forward

The client gives the input a number: 1234.

Step 1: Forward

def press(key):    seq += 1    me = simulate(me, key)                 # now    pending.append((seq, key))    udp.send(inputs=pending[-3:], ack=last_tick, view=view_tick)def server_tick():    for p in players: apply(p.inputs_in_order())    simulate_world(1 / 60)    send_snapshots(last_input_of_each_player)
Delay
0 on your screen
Bytes
95 B, 60 a second

Three copies of each input cost 34 bytes and replace a repeat request.

In the real world

The same design multiplayer game state sync doing real jobs. Pick one and step through it.

Nothing is asked for twice.

Step 1 of 4

An input packet is lost

Our systemClient AClient BMatch process60 ticks a secondHistory ring1 secondDelta coderper player

lost

1232, 1233, 1234

Inputs 1232, 1233 and 1234 were in it.

Step 1: An input packet is lost

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Accepting positions

    critical

    A changed client can be anywhere.

    Wrong
    player.pos = packet.pos
    Right
    player.pos = simulate(player, packet.inputs)
  • Jumping to an old truth

    major

    The snapshot is one round trip old, so the player is thrown back.

    Wrong
    me = snap.self
    Right
    me = snap.selffor p in pending: me = simulate(me, p.key)
  • Delta against the last one sent

    critical

    If that packet was lost, the client builds on something it never had.

    Wrong
    base = last_sent[player]
    Right
    base = history.get(player.acked_tick)
  • Unlimited rewind

    major

    A slow or lying client shoots into the distant past.

    Wrong
    at = shot.view_tick
    Right
    at = max(shot.view_tick, now - 12)
  • Blending the state

    major

    It stays wrong while new inputs are added.

    Wrong
    me = lerp(me, snap.self, 0.1)
    Right
    offset = shown - me   # drawn only

Interview tips

  • Name the problem first

    • Feel: prediction.
    • Smooth: buffer.
    • Fair: rewind.
    • Honest: authority.
  • Count bytes

    • With 28 bytes of headers.
    • 300 KB, then 9.6 KB a second.
    • Under 1,200 in a packet.
  • Say who pays

    • The victim, up to 200 ms.
    • The viewer, 100 ms of age.
    • The slow player, beyond the limit.
  • Choose by game

    • Huge state: lockstep.
    • Two players: rollback.
    • Cards: plain requests.