METABYTE
Back to articles

Multiplayer Game Server Architecture: Authoritative vs Peer‑to‑Peer

A pragmatic guide to choose and implement authoritative or peer‑to‑peer multiplayer architectures, with patterns, code, costs, and production pitfalls.

14 mai 202616 min readAI research draft
Multiplayer Game Server Architecture: Authoritative vs Peer‑to‑Peer

Choose the wrong multiplayer architecture and you’ll either drown in server bills or drown in cheaters. This matters now because your first network model decision locks in months of engineering, QA, and live‑ops costs.

If you’re skimming: use authoritative servers for competitive or economy‑bearing games (FPS, BR, MMO, survival). Use peer‑to‑peer with rollback for tight 1v1 and small co‑op if your cheat risk and live‑ops budget are low. Host‑migration or relayed P2P is fine for casual matches; dedicated servers are safer for ranked modes.

The two models in practice

Authoritative servers

  • Concept: A central game server is the single source of truth. Clients send inputs; the server validates and simulates, then replicates state back.
  • Why it exists: Prevents most active cheat vectors (speed, teleport, rate‑of‑fire, hitbox edits) because the client cannot “decide” outcomes.
  • Where it shines: Competitive PvP (FPS/BR), shared persistent worlds, real‑money economies, cosmetics tied to progression.
  • Typical stack: UDP/ENet/Steam Networking Sockets for transport; ECS simulation loop; interest management; snapshots + client‑side prediction + server reconciliation; Kubernetes/Agones for orchestration; Redis for lobbies/matchmaking; Postgres for accounts/economy.

Peer‑to‑peer (P2P)

  • Concept: Peers either simulate in lockstep (RTS) or independent timelines with rollback (fighters), sometimes with one peer as the “host”. No dedicated server per match.
  • Why it exists: Lower infra cost, potentially lower latency (shorter path), simpler to spin up matches.
  • Where it shines: 1v1/2v2 fighters with rollback, classic RTS lockstep, small co‑op where trust is acceptable.
  • Typical stack: UDP with NAT traversal; WebRTC DataChannels on web/console; STUN/TURN relays for tough NATs; deterministic simulation; host migration logic.

In our experience as builders, the question isn’t “which is better?” but “which failure mode can you afford?” With authoritative, you pay cash for servers; with P2P, you pay complexity and cheat exposure.

Architecture blueprints that actually ship

Blueprint A: Low‑latency authoritative shooter (10–60 players)

  • Transport: UDP or Steam Networking Sockets. Disable Nagle‑like coalescing; tune MTU to avoid fragmentation.
  • Tick model: Server tickRate=60, clients interpolate at render rate (120/144 ok). Prediction on clients, reconciliation via sequence numbers.
  • State replication: Delta‑compressed entity snapshots at 10–20 Hz; per‑client interest management (grid/quad‑tree buckets) to keep bandwidth within 30–80 KB/s per client.
  • Anti‑cheat: Server validates line‑of‑sight and rate limiting; optional kernel anti‑cheat for aim/ESP; weapon spread and recoil simulated server‑side.
  • Infra: Region‑pinned dedicated servers via Agones on GKE/EKS; Redis for matchmaking queues; Cloudflare for API and asset CDN; build pipeline outputs headless server images.

Data flow

  1. Client sends InputFrame {seq, press, delta} at 60 Hz.
  2. Server simulates, stamps authoritative stateSeq, stores last N states.
  3. Server sends Snapshot {stateSeq, entityDeltas, rttEst} at 15 Hz.
  4. Client reconciles: rewinds to stateSeq, reapplies pending inputs.

Blueprint B: Fighting game with P2P rollback

  • Transport: UDP/ENet or platform sockets; STUN first, TURN/relay fallback.
  • Netcode: Rollback with input delay (configurable 0–3 frames). Both peers run deterministic sim. If remote input for frame f arrives late, roll back to f, apply input, fast‑forward states.
  • Determinism: Fixed‑point math, integer time steps, PRNG seeded with agreed seed. Identical byte‑for‑byte replays across peers.
  • Host migration: Optional supervisor (matchmaker) to coordinate rematch handshakes.

Data flow

  1. Both peers exchange inputs each frame with sequence numbers.
  2. If late, trigger small rollback window (e.g., up to 6 frames) and re‑simulate.
  3. Visual smoothing: store animation deltas and re‑blend on correction.

A light dry‑wit interlude: If rollback scares you, consider the alternative: arguing about floating‑point rounding in code reviews for a quarter.

Minimal authoritative loop: code you can reason about

Below is a stripped Node.js/TypeScript example of an authoritative movement server using UDP, snapshots, and reconciliation metadata. This is not production code (no interest management, no crypto), but it shows the moving parts.

// server.ts
import dgram from 'dgram';

const server = dgram.createSocket('udp4');

type Vec2 = { x: number; y: number };

interface PlayerState { id: string; pos: Vec2; vel: Vec2; lastInputSeq: number }
interface InputMsg { t: number; seq: number; ax: number; ay: number; dt: number }

const TICK = 60;
const SNAPSHOT_HZ = 15;
const players = new Map<string, PlayerState>();
const addrs = new Map<string, { address: string; port: number }>();
let stateSeq = 0;

function integrate(p: PlayerState, input: InputMsg) {
  const speed = 6; // units/sec
  p.vel.x = input.ax * speed;
  p.vel.y = input.ay * speed;
  p.pos.x += p.vel.x * input.dt;
  p.pos.y += p.vel.y * input.dt;
  p.lastInputSeq = Math.max(p.lastInputSeq, input.seq);
}

server.on('message', (msg, rinfo) => {
  // decode: [type(1), idLen(1), id, payload...]
  const view = new DataView(msg.buffer, msg.byteOffset, msg.byteLength);
  const type = view.getUint8(0);
  const idLen = view.getUint8(1);
  const id = Buffer.from(msg.subarray(2, 2 + idLen)).toString('utf8');
  addrs.set(id, { address: rinfo.address, port: rinfo.port });

  if (!players.has(id)) players.set(id, { id, pos: { x: 0, y: 0 }, vel: { x: 0, y: 0 }, lastInputSeq: 0 });

  if (type === 1) { // input
    const off = 2 + idLen;
    const seq = view.getUint32(off, true);
    const ax = view.getInt8(off + 4);
    const ay = view.getInt8(off + 5);
    const dt = view.getUint16(off + 6, true) / 1000;
    integrate(players.get(id)!, { t: Date.now(), seq, ax, ay, dt });
  }
});

setInterval(() => {
  stateSeq++;
  // simple broadcast snapshot of all players
  const payload: any = { s: stateSeq, p: [...players.values()].map(p => ({ id: p.id, x: p.pos.x, y: p.pos.y, l: p.lastInputSeq })) };
  const buf = Buffer.from(JSON.stringify(payload)); // Use a binary codec in production
  for (const [id, addr] of addrs) {
    server.send(buf, addr.port, addr.address);
  }
}, 1000 / SNAPSHOT_HZ);

server.bind(30000);
console.log('Authoritative UDP server listening on 30000');

Client‑side reconciliation sketch (pseudo‑TS):

// client.ts
let lastSeq = 0;
const pending: Map<number, Input> = new Map();
let localPos = { x: 0, y: 0 };

function sendInput(ax: number, ay: number, dt: number) {
  const seq = ++lastSeq;
  const input = { seq, ax, ay, dt };
  pending.set(seq, input);
  udp.send(encodeInput(input));
  // predict
  localPos.x += ax * 6 * dt;
  localPos.y += ay * 6 * dt;
}

function onSnapshot(s: { s: number; p: { id: string; x: number; y: number; l: number }[] }) {
  // find my state
  const me = s.p.find(e => e.id === myId);
  if (!me) return;
  // snap to authoritative
  localPos.x = me.x;
  localPos.y = me.y;
  // drop applied inputs
  for (const [seq] of pending) if (seq <= me.l) pending.delete(seq);
  // reapply remaining
  for (const input of pending.values()) {
    localPos.x += input.ax * 6 * input.dt;
    localPos.y += input.ay * 6 * input.dt;
  }
}

Yes, JSON snapshots are wasteful; switch to Protobuf/FlatBuffers/bit‑packing before scale. But start readable, then optimize with measurements.

Latency, sync, and netcode models

  • Lockstep: All peers (or clients + server) advance only when everyone’s input for frame N is received. Deterministic sim required. Great for RTS with many entities, terrible over lossy links.
  • Client‑side prediction + reconciliation: Clients don’t wait; they predict immediate outcomes and correct when server packets arrive. Essential for shooters/racers. Requires careful design to avoid “rubber‑banding”.
  • Rollback netcode: Peers simulate ahead with assumed inputs, then roll back when real inputs arrive late. Gold standard for 1v1 fighters. Requires deterministic sim and careful animation/audio re‑sync.
  • Snapshot interpolation: For remote actors, render interpolated positions from a two‑snapshot buffer to smooth network jitter.
  • Time sync: All models rely on a shared notion of time. Use monotonic clocks, send serverTime in packets, run client clocks with smoothing (e.g., linear regression) to avoid step jumps.

Authoritative vs P2P: the real trade‑offs

DimensionAuthoritative serverPeer‑to‑peer (hosted/rollback/lockstep)
Cheating surfaceLow for movement/combat; server validatesHigher; host advantage; memory cheats possible
Infra cost per matchMedium‑High (compute + egress)Low (no dedicated per‑match server; relays add some cost)
LatencyAdditional hop to server; mitigated by regionsPotentially lowest (shortest path); TURN relays add delay
Determinism needHelpful but not requiredEssential for lockstep/rollback
Scale complexityFleet orchestration, matchmaking, scalingNAT traversal, host migration, desync recovery
PersistenceNatural to centralize world stateNeeds out‑of‑band persistence services
Cross‑playEasier to normalize anti‑cheat + rulesHarder; platform P2P stacks vary
Content authorityServer can gate unlocks/economyClient can spoof; needs audit services

What breaks in production

  • Interest management misconfig: Broadcasting full snapshots melts bandwidth. Use spatial partitioning (grid, BVH, zones), per‑client relevance filters, and LOD for net entities.
  • Tick drift and clock skew: Clients and server drift apart over minutes. Add server time in packets, smooth with NTP‑like regression, and enforce fixed step on server.
  • MTU fragmentation: Oversized UDP packets get fragmented; loss of a fragment loses the whole packet. Keep below ~1200 bytes for safety over the public internet; packetize deltas.
  • GC pauses and stop‑the‑world: C# and Node servers can hitch if you allocate per tick. Pool objects, pre‑allocate buffers, use Span<T>/ArrayPool in .NET or Buffer pools in Node.
  • JSON everywhere: Easy early, expensive later. Move to Protobuf/FlatBuffers or custom bit‑packing once message schemas stabilize.
  • Determinism sneaks: Non‑deterministic functions (Math.random() without seeding, unordered map iteration, float non‑associativity) cause divergent sims in P2P/rollback. Enforce fixed‑point and canonical iteration.
  • NAT traversal edges: Symmetric NATs force you onto TURN/relay, which adds cost and latency. Have a relay fallback ready (Epic Online Services P2P relay, Steam Datagram Relay, or your own TURN).
  • Security blind spots: Even with authoritative servers, ESP‑style cheats (reading memory for enemy positions) require obscuring information and running visibility server‑side. Use signed tokens, rate limits, and never trust timestamps or cooldowns from clients.
  • Host migration pain (P2P): When the host drops, re‑election must be instant and state must be serializable. Keep a rolling deterministic save of the last N frames.
  • Platform quirks: Consoles may throttle background sockets; browsers cap UDP; mobile radios sleep. Test on target devices. If you care about hitting 60 FPS consistently, also mind render‑thread budgets — we’ve written separately about rendering at 60 FPS.

Cost and ROI: what you actually pay for

There’s no single number, but you can approximate. Change variables for your region/provider.

  • Compute per match (authoritative):
    • A 60‑tick, 32‑player shooter shard often runs fine on 1–2 vCPUs with 1–2 GB RAM if your sim is lean. Heavier physics or AI scale up.
    • With orchestration (Agones), you bin‑pack matches; aim for 50–70% CPU utilization to keep headroom.
  • Bandwidth:
    • Back‑of‑the‑envelope: 32 players × 20 Hz snapshots × ~200 bytes average per player visible ≈ 128 KB/s per client downstream from server; upstream inputs might be 2–5 KB/s per client. Tune interest management to push this down.
    • For 1,000 CCU at 60–150 KB/s egress each, that’s 60–150 MB/s, or 5–13 TB/day. Egress dominates cost at scale; CDN doesn’t help for real‑time sockets.
  • Egress pricing: Check your cloud region; plan for $0.05–$0.12/GB publicly peered. Private backbone or relay providers can reduce variance.
  • P2P relay cost: If 20–30% of matches fall back to relays (TURN or steam relays), you’ll shoulder egress roughly proportional to the same per‑client rates, but only for those hard NAT users.
  • Engineering cost:
    • Authoritative: More server code, DevOps, observability, anti‑cheat integration. Faster iteration on game logic once patterns settle.
    • P2P/rollback: Determinism effort, tooling for replays/rollback visualization, NAT traversal testing.

When to spend:

  • If you have ranked modes, skins, and battle passes: spend on authoritative now. The first big cheating scandal costs more than servers.
  • If you’re testing a prototype fighter with Discord communities: ship rollback P2P and avoid infra until product‑market fit is clear.

Rough planning heuristics (sanity, not promises):

  • 10k CCU authoritative shooter: expect a low five‑figure monthly infra bill primarily from egress, assuming solid interest management and reasonable tick rates.
  • 10k CCU P2P fighter: near‑zero compute, but plan for relays and telemetry; infra often in the low four figures, dominated by storage/telemetry and relay egress.

Choosing by genre and constraints

  • FPS/BR/Extraction shooters: Authoritative, period. Use client prediction + reconciliation, server‑side hit validation, region scaling.
  • RTS (classic lockstep): P2P lockstep can work if you guarantee determinism; if you want spectators, replays, and cheat resistance, consider a thin authoritative referee server.
  • Fighting (1v1/2v2): Rollback P2P for best feel. Add relays and optional dedicated servers for tournaments.
  • Co‑op PvE (4–8 players): P2P with host or lightweight dedicated. If you sell cosmetics/progression, centralize the progression service.
  • Social sandbox/UGC: Often mixed. Authoritative for economy/ownership actions; P2P or relayed rooms for ephemeral presence.
  • Mobile casual: Relayed P2P (WebRTC) or authoritative micro‑instances. Tight on data plans; send tiny deltas.

Tools, transports, and orchestration

  • Transports:
    • UDP + ENet or custom reliability layer for PC/console.
    • Steam Networking Sockets for Steam ecosystem cross‑NAT and relays.
    • Epic Online Services P2P for consoles/PC cross‑play.
    • WebRTC DataChannels for browser/mobile (with STUN/TURN fallback).
    • For web: avoid plain WebSockets for high‑rate state; OK for turn‑based or chat.
  • Server frameworks:
    • Unity: Netcode for GameObjects/DOTS; Fish‑Networking or Mirror for alternatives.
    • Unreal: Gameplay Ability System with replication; dedicated server build.
    • Open‑source backends: Nakama (Go), Colyseus (Node), Godot Multiplayer API.
    • Managed: Photon (PUN/Fusion), PlayFab Multiplayer Servers + Party.
  • Orchestration:
    • Agones + Kubernetes for game server fleets; sidecars for health/alloc. Matchmaker services (Open Match) with Redis queues.
    • Observability: Prometheus + Grafana, distributed tracing on RPCs, per‑match logs shipped to object storage for replay/debug.
  • State and services:
    • Redis for ephemeral state/lobbies; Postgres for accounts/economy; S3/GCS for replays.
    • Auth via OAuth2/JWT; entitlements via platform SDKs (Steam, Sony, Microsoft, Apple, Google).

A reference production topology (authoritative)

  • Edge/API: Cloudflare in front of REST and matchmaking gRPC. Rate limit and token‑gate session creation.
  • Control plane: Matchmaker service pulls MMR buckets from Redis, allocates a pod (Agones), writes allocation ticket back.
  • Game pods: Headless dedicated servers in multiple regions, exposing UDP and a narrow gRPC control port for health and metrics.
  • Data plane: UDP real‑time traffic bypasses API gateways; only control messages go through TLS.
  • Persistence: After match end, stats written to Postgres; anti‑cheat events queued to Kafka for review.

A reference production topology (P2P with rollback)

  • Edge: A lightweight coordinator service issues signed session tokens containing peer addresses and relay credentials.
  • NAT traversal: Clients attempt STUN hole‑punch; on failure, fall back to TURN/relay. Keep a heartbeat to detect path failures.
  • Deterministic lock: Game build enforces fixed seed, fixed‑point math library, and replay serialization of all inputs.
  • Observability: Store per‑match input logs for desync analysis. Hash and compare state snapshots every N frames to catch divergence early.

Implementation details that save you weeks

  • Sequence numbers and ACKs: For state replication, use running sequence numbers and include ack for last received input; this powers client reconciliation and drop detection.
  • Compression: Q‑pack vectors (e.g., 3D positions) to 16‑bit fixed‑point when scale allows; use zstd on batched snapshots if CPU permits and you’re not latency‑bound.
  • Replay system: Build it early. For authoritative servers, record inputs and seeds to deterministically re‑run server sim for bug triage.
  • Rate control: Measure per‑client send budget; if exceeded, degrade gracefully: cull distant entities, reduce update frequency, or send “impostor” LODs.
  • Versioning: Protocol version and feature flags in every packet. Drop mismatched clients fast.
  • Testing: Bots that produce deterministic inputs across latency profiles (0/50/100/250 ms, 0–5% loss). CI runs desync detection on replays.

When a hybrid makes sense

  • Referee servers for P2P: Clients simulate locally, but a thin server verifies critical actions (damage, economy) asynchronously. You still get near‑P2P feel with some anti‑cheat guarantees.
  • Relayed P2P as default, dedicated for ranked: Casual matches P2P, ranked on servers. Share code paths to avoid divergent game logic.
  • Edge compute for hotspots: Use relay nodes close to players to reduce RTT if you can’t afford full dedicated in all regions.

Business guardrails

  • Milestone plan: Prototype P2P in three weeks; if you validate retention/DAU, invest in authoritative before launch for PvP. If you’re a small team, don’t build orchestration from scratch — use Agones/PlayFab/Photon first.
  • Expensive mistakes:
    • Building a custom unreliable transport badly — you’ll reinvent ENet and miss a decade of edge cases.
    • Betting on non‑deterministic physics for rollback — months of “why did this desync?”
    • Ignoring egress in the budget — bandwidth is the silent killer.

FAQ

Is authoritative always more secure?

It’s more secure for gameplay outcomes (movement, hit reg, cooldowns). It doesn’t stop information cheats (ESP) alone. For that, compute visibility server‑side and only replicate what a player could legitimately perceive.

Can I mix P2P for gameplay with a central economy?

Yes. Keep gameplay P2P (rollback/lockstep) but route unlocks, XP, and purchases through a central HTTPS API with server‑side validation. Sign and verify match results before granting rewards.

What tick rate should I use?

Start at 30–60 Hz server tick for shooters; 15–20 Hz snapshot send rate is often enough with prediction/interp. For fighters/rollback, frame‑locked at your render frame (typically 60 FPS) with configurable input delay.

Do I need Protobuf or FlatBuffers from day one?

Not necessarily. Start with JSON for velocity if you’re pre‑alpha; switch once message schemas stabilize and bandwidth becomes material. Plan for it early to avoid protocol lock‑in.

How do I handle host migration in P2P?

Elect a secondary host at match start, keep rolling deterministic state (e.g., inputs of last N frames). On host drop, peers re‑connect to the new host using pre‑issued tokens. Expect a brief pause; design UX accordingly.

What about cross‑play?

For authoritative: run the same server rules for all platforms; integrate platform auth providers. For P2P: lean on platform relays (Steam/EOS). Watch out for controller vs mouse balance in ranked modes.

Key takeaways

  • Authoritative servers are the default for competitive or economy‑bearing games; P2P/rollback shines for 1v1 and trusted small co‑op.
  • Bandwidth, not CPU, dominates cost at scale; interest management and binary encoding matter.
  • Determinism is non‑negotiable for P2P lockstep/rollback; enforce fixed‑point and seeded PRNGs.
  • Build replay/rollback tooling early; it’s your debugger for all netcode.
  • Plan for NAT traversal failures; always provide a relay fallback.
  • Measure before optimizing; start simple, switch to binary protocols and bit‑packing when schemas settle.

If you’re deciding between authoritative and P2P or want to pressure‑test your netcode design, MTBYTE can help—from prototype net loops to Agones fleets and rollback toolchains. Reach out at /contact and let’s ship a multiplayer stack that won’t collapse under your first 10k CCU.

NEXT STEP

Liked the approach?

We apply the same principles to client projects: AI, automation, products that don't die after launch.