Multiplayer netcode

From j4flmao/agent-skills · View interactive version

Multiplayer netcode is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about multiplayer netcode, client-side prediction and server reconciliation, entity interpolation, rollback netcode, GGPO, lag compensation for a shooter or choosing a transport. Produces gameplay netcode design and code. Not for server tick and fleet design (use authoritative

How to use this skill

Skill file

Multiplayer Netcode — Deep Guide

Purpose

Building robust multiplayer requires understanding latency, jitter, bandwidth, and how to hide them. This guide covers the full stack: transport, protocol design, client-server architecture, prediction, reconciliation, interpolation, lag compensation, rollback, and scalability.

Agent Protocol

Trigger

"multiplayer", "netcode", "client prediction", "server reconciliation", "entity interpolation", "rollback netcode", "lag compensation", "GGPO".

Input Context

Output Artifact

Netcode design and code. No file unless requested.

Response Format

Model: {client-server | rollback}
Tick/send rates: {Hz}
Latency hiding: {technique}
Code: {snippet}

1. The Problem: The Network Is the Enemy

Typical round-trip times (RTT):
LAN:                 < 5 ms
Same region:         20-60 ms
Cross-continent:     100-200 ms (+ Wi-Fi/mobile jitter and loss)

Every client sees the world at least RTT/2 old; netcode decides who pays for that delay (the shooter, the target, or nobody via prediction).

Netcode turns "what happened at t" into "what each client believes happened at t".

2. Transport Layer

2.1 UDP vs TCP

| Aspect | TCP | UDP |

|--------|-----|-----|

| Delivery | guaranteed, ordered | best-effort |

| Use | HTTP auth, file sync, chat | game state every frame |

| Problem | head-of-line blocking, retransmit stalls | reordering, loss |

Rule: game-critical state on UDP (custom reliable layer or RakNet-like reliable-UDP).

2.2 Reliable & Unreliable Channels

Split messages into channels:

Reliable-UDP: every packet carries its sequence number plus the latest received sequence and a 32-bit ack bitfield for the previous 32 packets, so each packet acknowledges many; lost reliable messages are re-sent in a later packet (not the same packet retransmitted).

2.3 Packet Layout

[Magic][Seq#][Ack#][AckBits][MessageCount][Message0][Message1]...

Header + per-message headers with bitpacking. Aim <1200B (Ethernet MTU 1500 minus IP/UDP headers); fragment bigger messages.

3. Architectures

3.1 Server-Authoritative (Mostly Standard)

Client ----inputs----> Server ----authoritative state----> Clients
        <----snapshots (30-60Hz)----

3.2 P2P with Host Migration

3.3 P2P Lockstep (RTS)

3.4 Client/Server vs P2P decision

| Game | Type |

|------|------|

| Competitive FPS/MOBA | server-authoritative + prediction |

| Top-down RTS/co-op | lockstep deterministic |

| Small co-op party | listen server with a client |

| Battle royale (40+ players) | dedicated server clusters |

4. Core Algorithms

4.1 Client-Side Prediction (Input-Based)

Client runs a local simulation of its controlled entity:

struct InputState { bool forward, back, left, right, fire; uint16_t seq; };

void ClientFrame() {
    InputState in = CaptureInput();
    pending.push_back({in, localTick});
    ApplyToLocalSimulation(in);            // PREDICT immediately
    SendInputToServer(in);                 // UNRELIABLE channel
}

4.2 Server Reconciliation

Authoritative snapshots from server; client compares against its own predicted saved state at that point in time:

Server sends: tick, position, velocity, HP
Client: find the local state saved under same tick (input seq)
        if position differs by > threshold -> snap BACK correction,
        then re-apply all pending inputs up to now (fast-forward)
void OnSnapshot(tick, serverState) {
    Saved& saved = history[tick];
    if (distance(saved.pos, serverState.pos) > tolerance) {
        world.state = serverState;                    // correct
        for (pending input after tick) ApplyToLocalSimulation(input); // re-simulate
    }
}

4.3 Interpolation (Visual Smoothing for Remote Entities)

Render other players via interpolation, not prediction:

Never mix interpolation with prediction on the same entity without buffers — jerky or doubled.

5. Lag Compensation (Hit Detection Fairness)

Server-hit detection at the shooter's perceived time:

  1. Client fires; sends aim plus the server tick (and interpolation fraction) it was rendering remote players at.
  2. Server rewinds the world state back to the client's send time (revert positions of all dynamic objects).
  3. Raycast/sweep against rewound state → decide hit.
  4. Allow even if the target moved already since then (client was seeing the past).

Implementation notes:

6. Bandwidth & Snapshot Compression

6.1 Delta Compression

6.2 Optimizations

| Technique | Gain |

|-----------|------|

| Quantize + bitpack (positions to a grid, angles to N bits, smallest-three quaternions) | large; measure per game |

| Skip unchanged actors (only send those changed) | huge |

| Encode relative to the acked baseline (delta) | large for slow-changing state |

| Interleave (send each entity at 15-30Hz instead of 60) | bandwidth/priority control |

| Contact-rate based interest management | scalability |

6.3 Interest Management

Don't send everything to everyone. Send only what's "interesting":

7. RTT / Clock Synchronization

Client needs a server-relative clock:

Client sends: t_client (its clock at send)
Server replies with t_server + server timestamp
RTT ≈ (t_nowClient - t_client)
Clock offset ≈ t_server - ((t_nowClient + t_client)/2)

Use smoothed RTT (EWMA) so snapshots' timestamps convert into client time reliably. Sync at load + periodically.

8. Rollback (Fighting / Racing Games)

Opposite of prediction-with-snapshots: keep a rolling buffer of the last N ticks of world state. When input arrives for a past tick:

  1. Rewind world to that tick.
  2. Apply the new input.
  3. Re-simulate forward to the current tick.
  4. Present the corrected state; small corrections are usually invisible, large ones appear as a short visual snap.

The simulation must be deterministic (same inputs, same results on every peer), and saving/loading state must be cheap enough to re-simulate several ticks in one frame. Use input delay of a few frames to reduce how far you roll back (GGPO-style).

9. Replication & Ownership

10. Anti-Cheat Considerations (Practical)

11. Load & Scaling

12. Project Plan: Steps to a Working Prototype

  1. UDP transport with reliable/unreliable channels + seq/ack.
  2. Server-authoritative simulation at fixed tick; client prediction for the local player.
  3. Snapshot stream (unreliable, prioritized) + interpolation buffer on client.
  4. Reconciliation: history buffers + correction when mismatch.
  5. Lag compensation for hit detection.
  6. Delta compression + interest management for scaling.
  7. Lobby/matching, NAT traversal (STUN/TURN), spectator mode.

13. Quality Checklist

14. Engine Mapping and Web Transports

References

Merged Material

Content folded in from overlapping skills and notes.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.