Everyone thinks a multiplayer game server is “open a socket, players send their position, broadcast everyone’s position to everyone else, done.” That works in a LAN party with four friends and zero lag. Then the interviewer piles on reality: the players are 80ms apart over the public internet, the connection drops 2% of packets and reorders the rest, one of the players is running a modified client that claims it is standing on the enemy’s head with 999 health, and the other players need the world to feel instant even though the server that decides what is true is a third of the world away. And you are running this at 64 ticks per second for dozens of players in the same match, for tens of thousands of concurrent matches.
A game state server is deceptive because it is not a throughput problem, it is a shared-mutable-state-under-adversarial-latency problem. There is one world, every player is mutating it at once, the mutations collide, the network lies to you about ordering and timing, and half the clients might be cheating. The entire design is a fight between three things that actively contradict each other: the server must be authoritative (never trust the client, or the game is instantly cheated to death), the game must feel instant to each player (so you cannot wait a round trip for the server to confirm every move), and the shared world must stay consistent across everyone (so two players agree on who shot whom). You cannot have all three naively. The whole design is the set of tricks - client-side prediction, server reconciliation via rollback and replay, and lag compensation - that let you fake all three at once.
Let me do it properly.
Functional Requirements (FR)
In scope:
- Authoritative world simulation. The server runs the one true copy of the game world - positions, velocities, health, physics, hit detection - and steps it forward at a fixed tick rate. The server’s state is the only state that counts. Clients render a view of it.
- Ingest player inputs. Each client sends a stream of inputs (move forward, turn, fire at this instant), not state. The server consumes inputs, applies them inside its simulation, and produces the resulting world. A client never says “I am at X”; it says “I pressed forward.”
- Broadcast world state. Every tick (or every few ticks), the server sends each player a snapshot of the relevant part of the world so their screen can render where everyone is. This must be compact enough to fit the tick budget.
- Client-side prediction. The client applies its own inputs immediately to a local copy of the simulation so the player sees instant response, before the server has confirmed anything. The player must not feel the round-trip delay on their own movement.
- Server reconciliation (rollback and replay). When the authoritative snapshot arrives and disagrees with what the client predicted, the client must smoothly correct to the server’s truth without the game jittering - by rewinding to the last acknowledged state and replaying its unconfirmed inputs.
- Lag compensation / hit registration. When a player fires at an enemy they see on their screen, the server must adjudicate the shot against where that enemy was at the moment the shooter saw them (rewinding the world to the shooter’s view), not where the enemy is on the server “now” - otherwise high-ping players can never hit anything.
- Interest management. A player only needs to know about entities near them. The server must not send every player the entire world; it sends each player their area of interest.
- Join / leave / reconnect. Players join a running match (full state sync), drop and reconnect (resync from a baseline), and leave cleanly.
Explicitly out of scope (name it so you own the scope):
- Matchmaking and lobby formation. Grouping players into a match by skill, region, and ping is a separate system. We assume a set of players has already been assigned to this match and this server. We receive a roster; we do not build the queue.
- The game design itself. Weapon balance, map layout, and game rules are content. We build the engine that simulates a world authoritatively; we do not design the gameplay.
- Persistent progression, inventory, leaderboards. Post-match stats, XP, ranked points, and global leaderboards are downstream services reading our match results. We emit a result; we do not rank.
- Voice chat. Real-time voice is an adjacent real-time stream, often peer-to-peer or a separate SFU, not part of the state server.
- Global orchestration of the fleet. How thousands of game-server instances are allocated, autoscaled, and placed on bare metal near players is a fleet-management concern. We design one match’s server and note how the fleet wraps it.
The one decision that drives everything: the server simulates authoritatively on a fixed tick, clients send inputs not state, and clients hide latency by predicting locally and reconciling against the server’s truth. Every hard part below - UDP reliability, prediction, rollback, lag compensation, cheat resistance, snapshot size - falls out of that single choice. Get the authority model right and the rest is engineering; get it wrong (trust the client, or make movement wait a round trip) and no amount of scaling saves you.
Non-Functional Requirements (NFR)
- Scale: tens of thousands of concurrent matches, each with up to ~64 players (we will design around a 64-player cap and note how smaller modes are cheaper). Per match: up to 64 inbound input streams and 64 outbound snapshot streams, 64 times a second. A single physical server hosts many matches; the fleet is horizontally huge but each match is a self-contained unit of simulation pinned to one process.
- Tick rate: 64 Hz authoritative simulation. That is a hard 15.625 ms budget per tick to ingest inputs, step physics, resolve combat, and serialize per-player snapshots. Blow the budget and the whole match stutters for everyone. This is a soft real-time deadline, the central constraint.
- Latency targets: the player’s own actions must feel instant - sub-16ms perceived input lag via client prediction, independent of network RTT. End-to-end, an input should reflect in authoritative state within one RTT plus a tick (typically 30-120ms depending on region), but the player should never feel that on their own movement. Other players’ positions are shown interpolated ~100ms in the past for smoothness.
- Availability: a match must survive transient packet loss and jitter without desync. If the server process dies mid-match that match is lost (acceptable, rare, and the fleet restarts/refunds), but a single dropped packet or a 200ms spike must not corrupt state. The design tolerates loss by construction (UDP + redundant state), not by retrying.
- Consistency: strong on the server, eventual on the clients. There is exactly one authoritative world; clients converge to it. Two clients may briefly disagree about where a third player is (they are rendering different moments in time), but the server’s ruling is final and clients reconcile to it within a few snapshots. No two clients can “win” a disagreement - the server decides.
- Durability: essentially none for world state. The live world is ephemeral and in-memory; when the match ends it is gone. We durably persist only the match result (scores, kills, duration) at the end, and optionally an input log for replays/anti-cheat review. Losing the live sim on a crash loses the match, not permanent data.
- Fairness and cheat resistance: a client must not be able to inject fraudulent state - teleport, shoot through walls, see through walls, or move faster than allowed. The server validates every input against the rules of the simulation and never accepts client-asserted positions or outcomes.
Back-of-the-Envelope Estimation (BoE)
Let me ground it in numbers, because the tick budget is where this design lives or dies.
Per-match traffic (worst case, 64 players, 64Hz):
Tick rate: 64 ticks/sec -> 15.625 ms per tick
Players per match: 64 (cap)
INBOUND (inputs), per player:
An input packet is tiny: buttons bitfield + look angles + a few
sequence/ack fields ≈ 20-40 bytes payload. Add UDP/IP headers (~28 B).
Clients send 1 input packet per client tick, often at the tick rate.
Per player inbound: 64 pkts/sec * ~60 B ≈ 3.8 KB/sec
Per match inbound: 64 players * 3.8 KB/s ≈ 245 KB/sec
OUTBOUND (snapshots), per player:
A full snapshot of 64 entities * ~40 B/entity ≈ 2.6 KB. Too big to send
raw at 64Hz (see below), so we DELTA-compress and INTEREST-filter it.
After delta + interest, a typical snapshot is ~300-800 B.
Server sends ~20-64 snapshots/sec per player (we often send at 20-30Hz
outbound while simulating at 64Hz - see deep dive).
Per player outbound (say 30Hz * 600 B): ≈ 18 KB/sec
Per match outbound: 64 * 18 KB/s ≈ 1.15 MB/sec
The asymmetry is the whole story: inputs are tiny, snapshots are the firehose. Outbound dominates by ~5x, and it scales with players-squared in the naive case (each player hears about every other player), which is exactly why interest management and delta compression are mandatory, not optional.
The naive snapshot cost (why we cannot just send everything):
Full world, no compression, 64Hz:
64 entities * 40 B = 2,560 B per snapshot
* 64 ticks/sec = 164 KB/sec PER PLAYER
* 64 players = 10.5 MB/sec PER MATCH just outbound
* 10,000 concurrent matches = 105 GB/sec of egress. Absurd.
That naive number is the trap. 105 GB/sec of egress for 10K matches is a nonstarter. The levers - delta compression (send only what changed), interest management (send only what is near you), and a lower outbound rate than tick rate - are what drag it down by 10-20x:
After delta + interest + 30Hz outbound:
~600 B/snapshot * 30/sec * 64 players ≈ 1.15 MB/sec per match
* 10,000 matches ≈ 11.5 GB/sec egress. Large but real.
Compute / tick budget (the actual scarce resource):
Per tick per match, the server must:
- ingest + validate up to 64 input packets
- step the simulation (movement, physics, collision) for ~64 entities
- resolve combat / hit detection (lag-compensated rewinds)
- build + delta-compress + serialize up to 64 per-player snapshots
ALL within 15.625 ms.
Serializing 64 per-player snapshots is the heavy part. Simulation of
64 entities is microseconds; the per-player outbound serialization
(interest query + delta vs each client's last ack) is the cost center.
How many matches fit on one physical server:
Say one match's simulation + serialization averages ~1 ms of CPU per tick
(across all cores it can use) and we want headroom under the 15.625ms wall.
A modern server has, say, 32-64 vCPU. If one match needs ~1 ms/tick and
ticks 64x/sec, that is ~64 ms of CPU-time/sec per match = ~0.064 of a core.
A 64-core box -> ~900-1000 matches of headroom, but memory, NIC egress
(1.15 MB/s/match * 1000 ≈ 1.15 GB/s, saturates a 10GbE NIC), and tail
latency pull the real number down to a few hundred matches per box.
So the binding constraints are, in order: the 15.625ms per-tick wall (soft real-time, cannot miss it), NIC egress (snapshots saturate the network card before the CPU), and memory (each match holds a ring buffer of recent world states for lag compensation). Size for those; raw QPS is not the problem.
Memory per match (for rollback and lag compensation):
We keep a ring buffer of recent authoritative world states so we can
rewind for lag compensation (up to ~1 sec of history at tick granularity):
64 states * 64 entities * ~64 B/entity ≈ 260 KB per match for history.
Plus per-client: last-acked baseline + unacked input buffer ≈ tens of KB.
Per match total ≈ under 1 MB of hot state. A few hundred matches/box = GBs.
High-Level Design (HLD)
The system is a fleet of stateful, single-process game-server instances, each owning the full authoritative simulation of exactly one match in memory, talking UDP to that match’s clients. Around each instance sits a thin control plane (allocation, health) and the match pins to one process on one machine - because the world is shared mutable state, you cannot spread one match’s simulation across machines without paying a coordination cost that blows the 15.625ms budget. One match = one authority = one process.
CONTROL PLANE (not in the tick hot path)
┌──────────────────────────────────────────────────────────────┐
│ Matchmaker --roster--> Session Allocator --> picks a region/ │
│ box with capacity│
│ Fleet Autoscaler <-- health/capacity -- Game Server Agents │
└───────────────────────────────┬──────────────────────────────-┘
│ "host match M, roster R, on port P"
▼
┌─────────────────────── ONE PHYSICAL BOX ───────────────────────┐
│ │
│ ┌───────────── Game Server Process: MATCH M (64 Hz) ────────┐ │
│ │ │ │
│ │ UDP socket <==== inputs ====== clients (64) │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌──────────────┐ per-client jitter buffer / input queue │ │
│ │ │ Net Ingest │ (reorders, dedups, drops old inputs) │ │
│ │ └──────┬───────┘ │ │
│ │ ▼ │ │
│ │ ┌────────────────── SIMULATION LOOP ──────────────────┐ │ │
│ │ │ every 15.625 ms: │ │ │
│ │ │ 1. pull latest input per player (validate) │ │ │
│ │ │ 2. step world: movement, physics, collision │ │ │
│ │ │ 3. resolve combat w/ LAG COMPENSATION (rewind) │ │ │
│ │ │ 4. advance tick number, write to STATE RING BUFFER│ │ │
│ │ └───────────────────────┬─────────────────────────────┘ │ │
│ │ ▼ │ │
│ │ ┌──────────────┐ per client: interest query + │ │
│ │ │ Snapshot / │ DELTA vs that client's last-acked │ │
│ │ │ Serializer │ baseline -> compact packet │ │
│ │ └──────┬───────┘ │ │
│ │ │ │ │
│ │ UDP socket ==== snapshots ====> clients (64) │ │
│ │ │ │
│ │ STATE RING BUFFER: last ~1s of world states (rewind) │ │
│ └───────────────────────────────────────────────────────────┘ │
│ (many such match processes share the box) │
└───────────────────────────────────────────────────────────────────┘
│ at match end
▼
┌──────────────────────────────┐
│ Match Result Sink (durable) │ scores, kills,
│ + optional input-replay log │ duration, MVP
└──────────────────────────────┘
CLIENT (each of the 64): predicts locally, reconciles to snapshots
┌───────────────────────────────────────────────────────────────┐
│ sample input -> apply LOCALLY (prediction) -> render instantly │
│ -> send input (seq#) to server │
│ on snapshot: RECONCILE (rollback to acked tick, replay unacked│
│ inputs); interpolate OTHER players ~100ms in past │
└───────────────────────────────────────────────────────────────┘
Request flow - the input path (client to server):
- The client samples local input each client-tick (buttons pressed, look angle), stamps it with a monotonically increasing input sequence number, and sends it over UDP. It also applies that input immediately to its own local simulation (prediction - see deep dive) so the player sees instant response.
- The client packs the last several inputs into each packet (redundant resend), so a single dropped UDP packet does not lose an input - the next packet re-carries it. Inputs are small, so this redundancy is nearly free.
- The server’s Net Ingest receives the UDP packet, drops inputs older than what it has already processed (dedup by sequence number), and places fresh inputs into a short per-client jitter buffer keyed by the tick they should apply on.
- On each server tick, the simulation pulls the appropriate input for each player. If a player’s input has not arrived (packet loss/jitter), the server repeats their last input (or applies a “no new input” default) rather than stalling - the sim never blocks on a missing packet.
Request flow - the simulation tick (the heart):
- The authoritative loop fires every 15.625ms. It validates each input against the rules (you can press “forward,” but the server computes the resulting position from your authoritative current position and the movement rules - the client’s claimed position is ignored entirely).
- It steps the world: applies movement and physics, resolves collisions, and runs combat/hit detection. Hit detection uses lag compensation: the server rewinds other entities to where the shooter saw them (deep dive 3).
- It increments the tick counter and writes the new world state into the state ring buffer (the last ~1 second of states), which lag compensation and snapshot deltas both read from.
Request flow - the snapshot path (server to client):
- For each connected client, the Serializer runs an interest query (which entities are near this player / visible to them), then delta-compresses the result against the last snapshot that client acknowledged receiving - sending only the fields that changed since that baseline.
- Each snapshot carries the server tick number and the client’s last-acked input sequence, so the client knows “the server has processed your inputs up to N, here is the resulting world.” It goes out over UDP. Snapshots are sent at the outbound rate (often 20-30Hz even while simulating at 64Hz, to save bandwidth).
Request flow - client reconciliation:
- When a snapshot arrives, the client finds the authoritative position of its own player at the acked tick, rolls back its local simulation to that state, then replays all inputs it has sent since that tick (which the server has not yet confirmed) on top of the authoritative state. If its prediction was right, nothing visibly changes; if it was wrong (it got shoved, or mispredicted), it smoothly corrects (deep dive 2).
- For other players, the client does not predict - it interpolates between the last two received snapshots, rendering them ~100ms in the past, which hides jitter and loss by always having two known states to tween between.
The key architectural insight: inputs flow up, authoritative snapshots flow down, and the client closes the perceived-latency gap entirely on its own via prediction and reconciliation. The server never waits for anyone and never trusts anyone’s claimed state; the client never waits for the server to feel responsive. The 15.625ms tick is the metronome everything hangs off.
Component Deep Dive
Four hard parts: (1) doing reliability over UDP without TCP’s head-of-line blocking, (2) client-side prediction and the rollback-replay reconciliation that corrects it, (3) lag compensation so hits register fairly across different pings, and (4) delta-compressed, interest-filtered snapshots that fit the budget. I will walk each from the naive approach to where it breaks and the design that survives.
1. Transport: why not TCP, and reliability over UDP
Approach A: Just use TCP (the naive instinct)
TCP is reliable and ordered - “let the transport handle lost packets, I will send state over a socket.”
Where it breaks: TCP’s reliability is exactly wrong for real-time state. TCP guarantees in-order delivery, which means if packet #100 is lost, packets #101-#110 are held in the kernel buffer until #100 is retransmitted and arrives - head-of-line blocking. For a game that is catastrophic: by the time the retransmit of a 150ms-old position arrives, that position is ancient and useless - you wanted the newest state, not the old one redelivered in order. TCP also has Nagle batching and congestion-control backoff that add unpredictable latency spikes. Reliable, ordered delivery of stale data is worse than unreliable delivery of fresh data. For a 64Hz stream of “here is the world now,” you never want yesterday’s snapshot redelivered.
Approach B: UDP with application-level reliability where it is needed
Use UDP - unreliable, unordered, no head-of-line blocking - and add reliability selectively in the application, only for the data that needs it.
The key realization: most game data does not need reliability at all. A dropped snapshot is irrelevant because another, newer one is 15-30ms behind it. So you split traffic into two classes:
UNRELIABLE (fire and forget), the bulk of traffic:
- Snapshots (server->client): if one is lost, the next newer one
supersedes it. Never retransmit a snapshot; it is already obsolete.
- Inputs (client->server): sent REDUNDANTLY instead of reliably -
each packet carries the last N inputs, so one loss self-heals on
the next packet. Cheaper and lower-latency than ack/retransmit.
RELIABLE-ORDERED (app-level acks + retransmit), the rare stuff:
- "Player joined/left", "match started/ended", "you picked up the flag",
chat, config. Low volume, must arrive, order matters.
- Implemented with sequence numbers + acks + retransmit on top of UDP,
like a mini-TCP for just these messages.
For snapshots we use a baseline-ack scheme instead of retransmission: each snapshot is a delta against the last snapshot the client confirmed receiving. The client acks the tick numbers it got; the server deltas against the newest acked baseline. If packets are being lost, the delta is simply computed against an older baseline and is a bit bigger - the system self-adjusts to loss by sending larger deltas, never by retransmitting stale data.
For inputs we use redundant encoding: packet for tick T carries inputs for ticks T, T-1, T-2. A single lost packet loses nothing because the next packet re-supplies it; only a burst of consecutive losses actually drops an input, at which point the server repeats the last-known input. Compared to acking every input, this halves latency (no wait for retransmit) at the cost of a few extra bytes per packet - a great trade when inputs are 40 bytes.
Approach C: Jitter buffer and clock sync to tame timing
Raw UDP arrival is jittery - packets bunch up and spread out. If the server applied each input the instant it arrived, movement would be jerky. So each client runs a tiny jitter buffer: inputs are tagged with the tick they are meant for, and the server holds them briefly so they apply on the right tick in the right order even when they arrive out of order or bunched. The buffer is kept as small as possible (1-2 ticks) because every ms of buffer is added latency - it is a direct jitter-vs-latency trade. Clients and server loosely sync clocks (the server tells each client the current tick and estimated RTT) so the client can timestamp inputs for the tick they will actually be processed on.
| Transport choice | Loss handling | Latency under loss | Verdict |
|---|---|---|---|
| TCP | retransmit in order | terrible (head-of-line block) | Rejected - stale data stalls fresh |
| UDP, retransmit snapshots | resend old snapshot | bad - redelivers obsolete state | Rejected - never want old snapshots |
| UDP, unreliable snapshots + redundant inputs + reliable channel for events | newer supersedes; redundancy self-heals | low and predictable | Right - fresh over complete |
2. Client-Side Prediction and Rollback-Replay Reconciliation
This is the core of the whole system: making the game feel instant while the server, one RTT away, is the only authority.
Approach A: Dumb client - wait for the server (the naive, unplayable design)
The client sends input, waits for the server to process it and send back the authoritative position, then renders. Pure “thin client.”
Where it breaks: the player presses forward and their character moves one full round trip later - at 80ms RTT, every keypress has 80ms+ of mush before anything happens. This is unplayable for anything twitchy; it feels like driving a boat. The authority model is correct (server decides everything) but the feel is destroyed. You cannot ship this.
Approach B: Client-side prediction + server reconciliation (rollback and replay)
The client predicts the result of its own inputs immediately, locally, using the same simulation code the server runs, and renders that prediction right away. Then it corrects against the server when the authoritative answer arrives.
CLIENT timeline (its own player):
tick 100: press FORWARD
-> apply forward to LOCAL sim immediately -> render at new pos
-> send input{seq:100, FORWARD} to server
-> remember input 100 in an "unacked inputs" buffer
tick 101: press FORWARD+RIGHT
-> apply locally, render, send input{seq:101,...}, buffer it
tick 102: press FORWARD
-> apply locally, render, send, buffer
...
(meanwhile the server is ~1 RTT behind, processing input 100)
SNAPSHOT arrives: "server processed up to input seq 100,
your authoritative position = P_server"
-> ROLLBACK: snap local player to P_server (the truth at seq 100)
-> REPLAY: re-apply buffered inputs 101, 102, ... on top of P_server
using the SAME movement code
-> result = corrected prediction for "now"
-> discard inputs <= 100 from the buffer (server has them)
The two halves:
- Prediction (make it feel instant): the client applies its own input the moment it happens, so there is zero perceived input lag on your own avatar. Crucially it uses the identical deterministic movement/physics code as the server, so its prediction usually matches what the server will compute.
- Reconciliation via rollback-replay (stay honest): when a snapshot confirms the server processed up to input N, the client discards its guess, snaps its player back to the server’s authoritative state at tick N (rollback), and then replays every input it has sent since N (which the server has not processed yet) on top of that authoritative state. Because the sim is deterministic, if the client predicted correctly the replayed result equals what it was already showing - the correction is invisible. If it predicted wrong (it got hit by something it did not know about, or ran into a wall the server placed differently), the replay produces a different, correct position, and the client smoothly eases to it over a few frames instead of snapping (to avoid a visible teleport).
The non-negotiable requirement that makes this work: determinism. Given the same starting state and the same inputs, client and server movement code must produce the exact same result, or every prediction mispredicts and the player jitters constantly. This forces fixed-timestep simulation (always step 15.625ms, never a variable frame delta) and care with floating point. The server’s authoritative tick and the client’s prediction tick must step identically.
Approach C: Mispredictions, and what you can and cannot predict
Prediction works great for your own movement because you know your own inputs. It fails for anything driven by information you do not have:
- Other players: you cannot predict their inputs, so you never predict them - you interpolate them from received snapshots (deep dive 4), rendering them slightly in the past for smoothness.
- Collisions with others / combat outcomes: whether your shot hit, or whether you got shoved, depends on authoritative state and other players’ positions you did not have - so these are server-confirmed, and the client shows a predicted effect only cautiously (e.g. a muzzle flash immediately, but the actual damage/kill only when the server confirms it, to avoid showing a kill that did not happen).
- Error smoothing: on a misprediction, snapping is jarring, so the client blends from its wrong position to the authoritative one over ~100ms. Small errors are smoothed invisibly; large ones (a big desync) are snapped because smoothing a huge gap would look worse.
The anti-cheat payoff of this model: because the client sends inputs, not positions, and the server recomputes the authoritative result from its own state, a hacked client that predicts itself onto the enemy’s head simply gets rolled back next snapshot - its local lie never touches the authoritative world. The client can only ever predict; it can never assert.
3. Lag Compensation (Fair Hit Registration Across Pings)
Prediction fixes your movement. It does not fix shooting a moving target when you and the target have different latencies.
Approach A: Resolve hits against “now” on the server (naive, and unfair)
The shooter fires; the server checks whether the ray hits the target at the target’s current authoritative position.
Where it breaks: the shooter is rendering the world ~100ms in the past (interpolation delay) plus their own ping. They aim perfectly at the enemy they see, pull the trigger - but by the time the input reaches the server, the enemy has moved. The server says “miss, nobody is there now.” High-ping players essentially cannot hit moving targets; they must lead by an amount that depends on their fluctuating ping, which is impossible to do consistently. The game feels broken and unfair to anyone not on a LAN.
Approach B: Rewind the world to the shooter’s view (lag compensation)
The server keeps a ring buffer of recent world states (every entity’s position for the last ~1 second, at tick granularity - the state history buffer from the HLD). When a fire input arrives, it is tagged with the client’s tick / the interpolation delay, so the server knows exactly which past moment the shooter was looking at.
SERVER state history (hitbox positions per tick):
tick: ... 936 937 938 939 940(now)
enemy: Px Py Pz Pw Pcurr
Shooter fires. Their packet says: "I fired seeing the world as of
tick 937" (their render time = now - interpolation - their RTT/2).
Lag-compensated hit test:
1. REWIND: look up every relevant entity's position at tick 937.
2. Rebuild the hitboxes as they were at tick 937.
3. Cast the shooter's ray against THAT rewound world.
4. If it hits -> the hit is valid; apply damage in the CURRENT tick.
5. RESTORE: continue the current tick normally.
So the server literally time-travels the world backward to the instant the shooter saw, adjudicates the shot there, and applies the consequences in the present. Now “if it was on your screen, it hits” holds regardless of ping. The shooter does not have to lead; they shoot what they see.
Approach C: Bound the rewind and accept the trade-off
Lag compensation has a cost that you must name in the interview: it creates the “shot around the corner” feeling for the victim. The high-ping shooter saw you 200ms ago, out in the open; you (on your screen) have already ducked behind a wall; the server rewinds, finds you in the open at that past tick, and you die “behind cover.” This is an inherent, unavoidable consequence of favoring the shooter - someone pays the latency, and the design chooses to make the target pay rather than make the shooter lead an impossible amount.
To keep it sane and cheat-resistant:
- Cap the rewind window (say 200-250ms). A client claiming it fired against a 2-second-old world is rejected - that bounds both the memory (ring buffer size) and the abuse (you cannot ask the server to rewind arbitrarily far to get free kills).
- Trust the server’s record of when the input arrived, not the client’s self-reported timestamp alone - clamp the client’s claimed view-time to what is physically consistent with its measured RTT, so a client cannot claim an artificially old view-time to shoot people who have long since moved.
- Memory cost: the ring buffer is the price. ~64 ticks * 64 entities * hitbox data ≈ a few hundred KB per match (from the BoE), which is why it is bounded to ~1 second, not kept forever.
| Hit resolution | Fair to high ping? | Side effect | Verdict |
|---|---|---|---|
| Against current server state | No - must lead by ping | none, but unplayable off-LAN | Rejected |
| Lag-compensated rewind, unbounded | Yes | “died behind cover”; abuse risk | Partial - unbounded is exploitable |
| Lag-compensated, rewind capped + RTT-clamped | Yes | “died behind cover” (accepted) | Right - favor shooter, bound abuse |
4. Delta-Compressed, Interest-Filtered Snapshots
From the BoE, sending full world state to everyone at 64Hz is 10.5 MB/sec per match - a nonstarter. This is the bandwidth deep dive.
Approach A: Full snapshot to every player every tick (naive)
Serialize all 64 entities (position, rotation, health, state) and send the whole blob to all 64 players, 64 times a second.
Where it breaks: the BoE already showed it - 10.5 MB/sec per match, ~105 GB/sec of egress across 10K matches, saturating NICs instantly. It is also wasteful: most of the world did not change between two 15.625ms ticks, and most entities are nowhere near any given player. You are paying to repeatedly send a player information that is both redundant (unchanged) and irrelevant (far away).
Approach B: Delta compression against the client’s acked baseline
Instead of a full snapshot, send only what changed since the last snapshot that specific client acknowledged. The server keeps, per client, the last baseline tick they confirmed; it diffs the current world against that baseline and serializes only changed fields.
Per client, per outbound tick:
baseline = last snapshot THIS client acked (say tick 930)
current = world at tick 940
delta = for each entity in this client's interest set:
send only fields that differ between 930 and 940
+ list of entities that left/entered interest
packet carries: current_tick=940, baseline_tick=930, <delta bytes>
Client applies delta onto its stored copy of tick 930 -> reconstructs 940.
This is why the baseline is the client’s acked tick, not the previous tick: under packet loss the client might not have the immediately-previous snapshot, so deltaing against “previous tick” would be undecodable. Deltaing against the last confirmed baseline means the delta is always decodable - and if acks are lagging due to loss, the delta just grows (covers more changed ticks) and self-heals, exactly the scheme from deep dive 1. An idle entity contributes zero bytes to the delta, which is where most of the savings come from - in a typical frame only a handful of entities moved meaningfully.
Further squeezing:
- Quantization / bit-packing: positions do not need full 32-bit floats; quantize to the map’s needed precision (say 16 bits per axis) and pack fields to the bit. Angles to 8-16 bits. This alone cuts per-entity bytes by half or more.
- Field-level dirty flags: a bitmask says which fields changed, so unchanged fields cost 1 bit, not their full width.
- Lower outbound rate than tick rate: simulate at 64Hz but send snapshots at 20-30Hz. The client interpolates between them, so it does not need a packet every single tick. This cuts outbound traffic by 2-3x for a barely perceptible smoothness cost (the client is interpolating anyway).
Approach C: Interest management (don’t send what they can’t see)
Delta compression handles “what changed”; interest management handles “what is relevant to this player.” A player in one corner of the map does not need updates about a fight across the map they cannot see.
Interest query per player per outbound tick:
- Spatial cull: entities within a radius / in the same spatial cell
(grid or BVH over the map) as the player.
- Visibility / PVS: optionally, entities in potentially-visible rooms
(precomputed visibility sets) - don't leak enemies through walls.
- Always-relevant set: teammates, objectives, the player themself.
Only entities in the interest set are candidates for the delta.
A uniform spatial grid over the map is the usual structure: bucket entities into cells, and a player’s interest set is their cell plus neighbors. This turns the naive O(players^2) “everyone hears about everyone” into “everyone hears about the handful near them,” which is what makes the per-match outbound land near 1.15 MB/sec instead of 10.5 MB/sec. It also has an anti-cheat benefit: if the server never sends a far-away or behind-a-wall enemy’s position to a client, a wallhack cannot reveal what was never transmitted - you cannot render an enemy whose coordinates you were never given. (This is imperfect for enemies just about to come into view, but it dramatically limits the information a cheating client holds.)
| Technique | What it removes | Typical saving | Note |
|---|---|---|---|
| Full snapshot (baseline) | nothing | 1x | 10.5 MB/s/match - nonstarter |
| Delta vs acked baseline | unchanged fields | ~5-10x | self-heals under loss |
| Quantize + bit-pack | float precision | ~2x | lossy within tolerance |
| Interest management | far/invisible entities | ~2-5x | also limits wallhacks |
| 30Hz outbound (interpolate) | half the packets | ~2x | client interpolates anyway |
Stacked, these take the naive 10.5 MB/sec per match down to the ~1.15 MB/sec the BoE used - the difference between a buildable system and one that melts the NIC.
API Design & Data Schema
This system’s “API” is mostly a binary UDP wire protocol inside a match, plus a small control-plane HTTP API around it. I will give both.
Control plane (HTTP, out of the hot path)
POST /v1/sessions # allocator asks a box to host a match
{
"match_id": "m_8f21",
"mode": "bomb_defusal_5v5",
"map": "dust_ii",
"roster": [ {"player_id":"p_1","team":"A"}, ... ], # up to 64
"tick_rate": 64
}
201 Created
{ "match_id":"m_8f21", "host":"gs-eu-west-14.example", "udp_port":30414,
"connect_tokens": { "p_1":"tok_...", ... } } # per-player auth token
GET /v1/sessions/{match_id} # control-plane health/status
200 { "match_id":"m_8f21", "phase":"live", "tick":48213,
"players_connected":10, "players_expected":10 }
DELETE /v1/sessions/{match_id} # force teardown (abandoned match)
204 No Content
# Emitted by the server at match end (to the result sink):
POST /v1/results
{ "match_id":"m_8f21", "duration_s":1842, "winner":"A",
"players":[ {"player_id":"p_1","kills":18,"deaths":11,...} ],
"replay_input_log_uri":"s3://.../m_8f21.inputs" } # optional
A player authenticates to the match with the short-lived connect_token (binds them to their roster slot), handshakes over UDP, and the session goes live. Tokens stop a stranger from UDP-spraying into someone else’s match.
In-match wire protocol (binary over UDP)
These are conceptual packet layouts, not JSON on the wire - every byte counts at 64Hz.
CLIENT -> SERVER : INPUT (unreliable, sent redundantly)
packet {
channel : u8 = INPUT
match_id : u32
client_tick : u32 # tick this input is for
last_recv_snap : u32 # ack: newest snapshot tick client got
input_count : u8 # how many redundant inputs follow (e.g. 3)
inputs[] : {
seq : u32 # input sequence number
buttons : u16 bitfield # fwd/back/left/right/jump/fire/...
view_yaw : u16 quantized
view_pitch : u16 quantized
view_tick : u32 # which world-tick they were seeing (lag comp)
}
}
SERVER -> CLIENT : SNAPSHOT (unreliable, delta-compressed)
packet {
channel : u8 = SNAPSHOT
server_tick : u32 # "world as of this tick"
baseline_tick : u32 # delta is vs this (client-acked) tick
acked_input_seq: u32 # "I have processed your inputs up to here"
changed_count : u16
entities[] : {
entity_id : u16
field_mask : u16 # which fields follow
(pos_x,pos_y,pos_z) quantized, yaw, health, state ... # only if dirty
}
left_interest[] : u16 # entities that dropped out of view
events[] : { ... } # kills/pickups confirmed this tick
}
CLIENT <-> SERVER : RELIABLE (acked + retransmitted mini-protocol)
join/leave, match_start, match_end, round transitions, chat.
seq + ack-bitfield + retransmit until acknowledged.
In-memory data model (the live world - ephemeral)
There is no database on the hot path. The world is plain in-memory structures sized for cache-friendliness, because at 64Hz you touch all of it every tick.
World (one per match, in RAM):
tick : u32
entities : Entity[] (struct-of-arrays for cache locality)
Entity:
id : u16
owner_player : u8 # or NONE for projectiles/pickups
pos : vec3 (f32) # authoritative position
vel : vec3 (f32)
yaw, pitch : f32
health : i16
state_flags : u32 # alive, crouched, reloading, ...
hitboxes : AABB[] # for lag-compensated hit tests
Per-client connection state:
player_id, team, udp_endpoint, auth_token
last_acked_snapshot_tick # baseline for delta compression
unprocessed input queue (jitter buffer)
last_processed_input_seq
interest_cell # spatial grid cell for interest mgmt
State ring buffer (per match, for lag compensation):
world_history : CircularBuffer<WorldSnapshot>[~64 entries] # ~1 sec
each entry: tick + all entities' positions/hitboxes at that tick
Spatial index (per match, for interest management):
grid : Cell[][] # map bucketed into cells; entity_ids per cell
Why no SQL/NoSQL in the loop: the data is tiny (under 1 MB/match), extremely hot (rewritten 64x/sec), and purely transient. A database round trip is ~milliseconds; the entire tick budget is 15.625ms. Any disk or network store on the hot path is instantly disqualified. The only durable write is the match result at the end (and an optional append-only input log for replays/anti-cheat), which goes to normal durable storage (object store for the input log, a relational/NoSQL store for the result row keyed by match_id) - a batch write per match, not per tick. The live simulation is deliberately a RAM-only, single-process affair; durability is for the outcome, not the process.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each:
1. The 15.625ms tick wall (breaks first, and hardest). If serializing 64 per-player snapshots plus simulating plus hit detection exceeds 15.625ms, the whole match stutters for everyone - this is a hard soft-real-time deadline. Fix: the serializer is the cost center, so delta compression + interest management shrink per-client work to “a handful of nearby changed entities,” and outbound at 20-30Hz instead of 64Hz halves the serialization frequency. Keep world data in struct-of-arrays for cache locality. Budget and profile per-tick; if a match cannot hold the budget, it is over-populated and should be a smaller mode.
2. NIC egress saturation. Snapshots are the firehose (~1.15 MB/sec/match); a few hundred matches per box approaches 10GbE limits. Fix: the same compression levers (delta, interest, quantization, lower outbound rate) are also the egress fix - they are what turns 10.5 MB/s/match into ~1.15. Then cap matches per box by NIC budget, not CPU, and spread matches across boxes/regions. Use multiple NICs / higher-bandwidth hosts for dense boxes.
3. Packet loss and jitter corrupting state. UDP drops and reorders; a naive design desyncs on loss. Fix: unreliable snapshots that newer supersedes (never retransmit stale state), redundant input encoding (last N inputs per packet, self-healing), delta vs acked baseline (self-grows under loss, always decodable), and a small jitter buffer to reorder inputs. Loss is tolerated by construction, not by retry.
4. A single match is pinned to one process (no horizontal split within a match). The shared mutable world cannot be spread across machines without coordination that blows the tick budget. Fix: accept it - one match = one authoritative process. Scale out across matches (the fleet is embarrassingly parallel at the match granularity), not within a match. For very large modes (hundreds of players, an MMR zone), shard the world spatially across processes with handoff at zone boundaries - but that is a different, harder design; for the dozens-of-players case here, one process is correct and simplest.
5. Server process death = match lost. The world is RAM-only and ephemeral. Fix: accept the blast radius is one match, keep it small. Health-check processes; on crash, the control plane tears the match down and refunds/aborts (rare, acceptable). Do not try to replicate live world state hot across machines for failover - the coordination cost is not worth it for a 15-30 minute ephemeral match. Durability is only for the end-of-match result, written once.
6. Lag compensation memory and abuse. The rewind ring buffer costs memory, and an unbounded rewind is exploitable. Fix: cap the history to ~1 second (bounds memory to a few hundred KB/match) and cap the rewind window to ~200-250ms, clamping the client’s claimed view-tick to its measured RTT so it cannot ask to rewind further than physically plausible.
7. Cheating (the adversarial bottleneck). Clients may lie. Fix: the authority model is the defense - clients send inputs, never state; the server recomputes everything and rolls back any client that predicted a lie. Input validation (you can press fire, but fire-rate, movement speed, and positions are server-computed and bounded) blocks speed/teleport hacks. Interest management withholds data a player should not see, blunting wallhacks. Residual stuff (aimbots) needs a separate client-side anti-cheat and server-side statistical detection - noted as adjacent, not solved here.
8. Hot regions / uneven fleet load. Players cluster by geography and time of day. Fix: the control-plane allocator places each match on a box in a datacenter near its roster (lowest aggregate ping), and the autoscaler pre-warms capacity in a region ahead of its peak hours. Matches are short and self-contained, so load naturally churns and rebalances as matches end.
9. Clock drift between client and server. Prediction and lag comp need a shared notion of “which tick.” Fix: the server periodically tells each client the current server tick and its estimated RTT; the client runs a smoothed clock estimate and timestamps inputs for the tick they will actually be processed on, nudging its local clock gradually rather than snapping.
Wrap-Up
The trade-offs that define this design:
- Authoritative server over trusted client. The server simulates the one true world and accepts only inputs, never state, so a hacked client can predict a lie locally but gets rolled back the next snapshot. This is the root decision that makes every other anti-cheat property fall out, at the cost of forcing prediction+reconciliation to hide latency.
- UDP over TCP. We take unreliability and add selective, application-level reliability only where it matters, because for a 64Hz state stream, fresh-but-lossy beats complete-but-stale - TCP’s in-order retransmit would stall fresh snapshots behind obsolete ones.
- Predict locally, reconcile via rollback-replay. The client applies its own inputs instantly (zero perceived input lag) and corrects against the server by rewinding to the acked tick and replaying unacked inputs, trading a requirement for deterministic, fixed-timestep simulation for the illusion of a zero-latency, fully-authoritative game.
- Lag-compensated hit registration. The server time-travels the world back to the shooter’s view to adjudicate shots, making the game fair across pings - and we knowingly pay for it with the “died behind cover” effect for victims, bounding the rewind to stop abuse.
- Delta + interest + quantization over full snapshots. We send each player only the nearby entities that actually changed, quantized and at a lower outbound rate, turning a 10.5 MB/sec-per-match firehose into ~1.15 MB/sec - the difference between buildable and NIC-melting - and incidentally starving wallhacks of data.
- One process per match, scale out not in. The shared mutable world stays on a single authoritative process (RAM-only, ephemeral) because splitting one match across machines would blow the 15.625ms tick budget; we parallelize across matches, not within one, and durably persist only the result.
One-line summary: a fleet of single-process, RAM-only authoritative simulations ticking at 64Hz over UDP, where clients send inputs and hide latency with client-side prediction and rollback-replay reconciliation, the server rewinds its state-history ring buffer for lag-compensated hit detection, and delta-compressed interest-filtered snapshots keep per-match egress near 1 MB/sec - trading deterministic fixed-timestep complexity and the “died behind cover” artifact for a game that feels instant, stays consistent, and never trusts a byte the client sends.
Comments