Design Multiplayer Game State Sync
hard 50 minLet 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
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
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
criticalA changed client can be anywhere.
Wrongplayer.pos = packet.posRightplayer.pos = simulate(player, packet.inputs)Jumping to an old truth
majorThe snapshot is one round trip old, so the player is thrown back.
Wrongme = snap.selfRightme = snap.selffor p in pending: me = simulate(me, p.key)Delta against the last one sent
criticalIf that packet was lost, the client builds on something it never had.
Wrongbase = last_sent[player]Rightbase = history.get(player.acked_tick)Unlimited rewind
majorA slow or lying client shoots into the distant past.
Wrongat = shot.view_tickRightat = max(shot.view_tick, now - 12)Blending the state
majorIt stays wrong while new inputs are added.
Wrongme = lerp(me, snap.self, 0.1)Rightoffset = 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.