Fiber-optic latency (40 ms RTT) and floating-point drift break deterministic physics in real-time multiplayer, but rollback netcode mitigates lag via state rewinds, contrasting perceived delay with empirical replay precision.
Fiber optics cap RTT at 40 ms; jitter extends it, disrupting 6, 9 frames at 60 Hz.
Clients simulate remote actions locally, rolling back to deterministic snapshots on packet arrival.
Floating-point errors or variable timesteps trigger unbounded rollback resimulation costs.
Store only delta-encoded inputs in ring buffers to enforce ±1-frame deterministic replay.
id: 134
title: “Rollback Netcode: 5 Empirical Rules for Physics”
slug: “deterministic-physics-rollback-netcode”
canonical_url: “https://curiouswinds.com/technology/deterministic-physics-rollback-netcode/”
domain: “technology”
cluster: “T1”
reading_time: 12
word_count: 2210
stage: “clean_room_v2”
rubric_score: “8.87/10”
Executive Summary: Real-time multiplayer simulations face an immutable physical constraint: the finite speed of light through terrestrial optical fiber. In high-precision physical interactions—such as fighting games, racing simulators, and networked rigid-body physics—traditional lockstep delay architectures introduce intolerable input lag. Rollback netcode eliminates client-perceived latency by executing local inputs instantly and predicting remote player inputs. When packet arrivals reveal mispredictions, the engine executes a rapid state rollback, rewinding historical simulation frames, applying corrected inputs, and fast-forwarding to the present frame. Implementing rollback physics requires absolute fixed-point determinism, zero-allocation ring-buffer snapshots, delta-compressed input queues, and bounded resimulation budgets.
Ledger Identity: `ART-P4-POST134`
Curation Standard: Peer-Reviewed Simulation Engineering & Network Protocols
01. The Network Latency Trilemma in Interactive Physics
Every networked simulation operates across non-zero physical distance. Light travels through standard telecommunications silica fiber at approximately $200\,\text{km/ms}$ ($c_{\text{fiber}} \approx 2 \times 10^8\,\text{m/s}$). A transcontinental connection across $4{,}000\,\text{km}$ imposes an absolute theoretical round-trip latency floor:
Accounting for router queue delays, packet inspection, and transit jitter, real-world cross-continent ping times fluctuate between $60\,\text{ms}$ and $120\,\text{ms}$. At a standard simulation frequency of $60\,\text{Hz}$ ($\Delta t = 16.66\,\text{ms}$ per frame), a $100\,\text{ms}$ round-trip delay spans six complete simulation frames.
| Architecture Paradigm | Input Latency | Visual Artifacts | State Authority Model |
|---|---|---|---|
| Deterministic Lockstep | High (Tied to RTT) | Zero (Perfect Sync) | Peer Consensus |
| Client-Side Prediction | 0 ms (Immediate) | Snapping / Teleport Rubberbanding | Dedicated Server Absolute |
| Deterministic Rollback (GGPO) | 0 ms (Immediate) | Smooth Visual Resimulation | Deterministic Shared Core |
In a traditional lockstep delay architecture, the simulation stalls local execution until confirmation of the remote player’s input arrives:
This delay destroys player motor coordination in precision mechanics. Rollback netcode resolves this by separating visual presentation from network confirmation:
- Immediate Local Execution: Local player inputs execute on the exact frame they are pressed ($t_0$).
- Speculative Remote Prediction: Remote player inputs are assumed to match their last confirmed frame:
- Reconciliation Resimulation: When late packets arrive indicating that remote player input changed at frame $t_{\text{past}} < t_{\text{current}}$, the engine rewinds simulation state to $t_{\text{past}}$, injects the verified input $u_{\text{remote}}(t_{\text{past}})$, and re-integrates all physical bodies forward to $t_{\text{current}}$ within a single hardware frame budget.
02. Rule 1: Enforce Strict Fixed-Point Mathematical Determinism
Rollback netcode functions if and only if two independent hardware execution environments running identical input sequences produce mathematically identical states down to the last bit:
A single bit of divergence in position, velocity, or collision normals compounds exponentially over time, causing irreversible simulation desynchronization.
The IEEE 754 Floating-Point Non-Determinism Trap
The primary hazard in cross-platform simulation is reliance on standard hardware floating-point operations (`float` / `double`). The IEEE 754 floating-point standard permits implementation divergences that break bitwise determinism:
- Fused Multiply-Add (FMA): Modern x86 and ARM processors support FMA instructions ($a \cdot b + c$) that compute intermediate products with infinite precision before a single rounding step. If Host A compiles with FMA enabled while Host B compiles without FMA (performing separate multiply and add rounding), results diverge on the least significant bit of the mantissa:
- Transcendental Instructions: The trigonometric and square root implementations across CPU microarchitectures (Intel AVX-512 vs AMD Zen 4 vs Apple Silicon NEON) exhibit varying ulp (unit in the last place) error profiles.
- Compiler Optimizations: Reordering floating-point operations via `-O3` or `-ffast-math` violates associativity:
| Numeric Type | Precision Range | Cross-Arch Consistency | Hardware Execution Cost |
|---|---|---|---|
| IEEE 754 Float32 | ~7 Decimal Digits | Non-Deterministic (FMA / SIMD) | Native ALU/FPU Single-Cycle |
| IEEE 754 Double64 | ~16 Digits | Non-Deterministic (Arch Bias) | Native 64-bit FPU |
| Q16.16 Fixed-Point | 1/65,536 Sub-Pixel Unit | 100% Bit-Exact Invariant | Integer ALU Only |
| Q32.32 Fixed-Point | 1/4.29B Unit | 100% Bit-Exact Invariant | 64-bit Integer Operations |
To guarantee determinism, all physical simulation variables—spatial coordinates, velocities, angular momentums, bounding box dimensions, and trigonometric lookup tables—must be implemented in fixed-point arithmetic ($Q16.16$ or $Q32.32$ format), operating purely on integer arithmetic logic units (ALUs).
For related low-level memory constraints in deterministic runtimes, see our analysis in Fast Compilers & Memory Arenas and the hardware principles in Cost of Abstraction & CPU Cycles.
03. Rule 2: Zero-Allocation Ring-Buffer State Snapshots
During a rollback event, the game engine must restore a complete snapshot of historical simulation state. If the engine executes state capture or restoration via dynamic heap allocations (`malloc`, `new`, or standard garbage-collected objects), performance collapses.
Allocating heap memory during a 6-frame rewind triggers memory fragmentation, cache misses, and garbage collection pauses, causing frame time to spike beyond the $16.66\,\text{ms}$ budget.
64 × sizeof(SimulationState)). When a late-arriving packet from Frame N−5 is received, the engine rewinds head = (N−5) % 64, loads the pristine historical snapshot, injects the new input, and re-simulates forward to Frame N within 1.2 ms.
Architectural Snapshot Standards:
- Contiguous Flat Structures: Isolate all stateful simulation variables into a single plain-old-data (POD) struct with zero pointer indirections:
typedef struct {
uint32_t frame_index;
FixedPoint32 position[MAX_ENTITIES];
FixedPoint32 velocity[MAX_ENTITIES];
uint8_t flags[MAX_ENTITIES];
uint32_t checksum;
} SimulationState;
- Ring Buffer Geometry: Pre-allocate a contiguous memory arena holding exactly $N$ slots (typically $N = 64$ frames, providing over one full second of historical buffer at $60\,\text{Hz}$).
- Hardware-Accelerated Memory Copy: Capturing a frame snapshot reduces to a single contiguous memory copy:
On modern memory controllers, copying a $32\,\text{KB}$ simulation state struct takes less than $1.8\,\mu\text{s}$, consuming under $0.01\%$ of the frame budget.
04. Rule 3: Bound the Resimulation Loop Budget
When a rollback occurs, the engine must execute multiple simulation steps within the current frame:
Where $K$ is the number of rewound frames (typically 1 to 8 frames), and $\tau_{\text{sim}}$ is the computational execution time of one full physics step.
If a single simulation tick requires $4\,\text{ms}$, rewinding 6 frames requires:
This immediately exceeds the $16.66\,\text{ms}$ frame deadline, dropping the visual frame rate and inducing cascading input lag.
Decoupling Physics from Presentation
During resimulation, the engine must disable all visual presentation overhead:
- Suppress Visual Side-Effects: Particle spawning, skeletal mesh skinning, sound effect triggering, and UI updates must be strictly skipped during intermediate resimulation frames ($t_{\text{past}} \dots t_{\text{current}-1}$).
- Headless Step: Run the physics integrator in headless mode, calculating purely spatial collisions and bounding box updates.
- Dynamic Time Warping: If one client consistently lags behind by more than 4 frames, the peer client slightly slows its local clock (stretching frame duration by $1\,\text{ms}$ to $17.66\,\text{ms}$) over several frames until network equilibrium is restored, preventing permanent drift.
05. Rule 4: Compress Network Input Deltas via Bitmask Ring Streams
Sending raw input state packets over UDP can consume significant bandwidth if multiple players transmit dense controller inputs 60 times per second. Furthermore, network packet loss creates missing input holes that force catastrophic deep rollbacks.
High-efficiency rollback netcode employs sliding window input redundancy:
Every outgoing UDP packet contains not only the current frame’s input $u(t)$, but also the preceding 7 to 15 frames of input history:
- If a packet containing Frame 100 drops, the arrival of the packet for Frame 101 automatically contains the inputs for Frame 100.
- The receiving peer experiences zero effective packet loss unless 8 consecutive network packets drop in a row—an event with probability under $10^{-6}$ on stable broadband connections.
Delta Compression Formulation
Because human player inputs (button presses and analog stick positions) change infrequently between $16\,\text{ms}$ ticks:
The engine serializes only the XOR difference bitmask and a run-length encoded counter. This compresses the per-packet payload to under 40 bytes, easily fitting within the standard internet MTU ($1{,}500\,\text{bytes}$) without fragmentation.
06. Rule 5: State Checksum Verification and Desynchronization Traps
Even with rigorous fixed-point arithmetic, subtle implementation oversights can compromise determinism:
- Reading from uninitialized struct padding bytes.
- Iterating through hash maps (`std::unordered_map` or dictionary sets) where bucket iteration order depends on heap memory pointer addresses.
- Accidental invocation of non-deterministic random number generators without synchronized seeds.
To detect desynchronization instantly, the engine computes a 32-bit cyclic redundancy check (CRC32) or xxHash over the simulation state snapshot at each frame:
Host B: Frame 120 Checksum = 0x8A7F2B01 ──▶ Match Confirmed (In Perfect Sync)
Host B: Frame 121 Checksum = 0x9B1104C3 ──▶ DESYNC DETECTED!
└──▶ Immediate Memory Dump: Binary diff of SimulationState exported to Diagnostic Ledger
When a mismatch is detected, both clients immediately write a diagnostic memory dump containing the binary diff of their states. This allows engine architects to pinpoint the exact variable that diverged.
07. Operational Resimulation Engine & Benchmark
To verify rollback execution budgets and state integrity, simulation engineers execute deterministic loop verification:
"""
Deterministic Rollback Physics Simulator & State Engine
Demonstrates fixed-point ring-buffer snapshot, rewind, and resimulation.
"""
import math
class FixedPointPhysics:
"""Fixed-point coordinate math (Scale: 1000 = 1.0 unit)."""
SCALE = 1000
@staticmethod
def from_float(val: float) -> int:
return int(val * FixedPointPhysics.SCALE)
@staticmethod
def to_float(val: int) -> float:
return val / FixedPointPhysics.SCALE
class RollbackEngine:
def __init__(self, buffer_size: int = 64):
self.buffer_size = buffer_size
self.state_buffer = [{} for _ in range(buffer_size)]
self.input_history = {}
self.current_frame = 0
# Initial simulation state
self.pos_x = FixedPointPhysics.from_float(0.0)
self.vel_x = FixedPointPhysics.from_float(5.0) # 5.0 units / tick
def step_simulation(self, player_input: int):
"""Pure deterministic physics integration."""
# Input: -1 (left), 0 (none), +1 (right)
accel = player_input * FixedPointPhysics.from_float(1.0)
self.vel_x += accel
self.pos_x += self.vel_x
def save_snapshot(self, frame: int):
slot = frame % self.buffer_size
self.state_buffer[slot] = {
"frame": frame,
"pos_x": self.pos_x,
"vel_x": self.vel_x
}
def load_snapshot(self, frame: int):
slot = frame % self.buffer_size
saved = self.state_buffer[slot]
if saved.get("frame") != frame:
raise RuntimeError(f"Snapshot for frame {frame} overwritten in ring buffer!")
self.pos_x = saved["pos_x"]
self.vel_x = saved["vel_x"]
def execute_rollback(self, corrected_frame: int, corrected_input: int):
"""Executes rewind, input injection, and forward resimulation."""
if corrected_frame > self.current_frame:
return
rewind_depth = self.current_frame - corrected_frame
# 1. Rewind to past confirmed state
self.load_snapshot(corrected_frame)
# 2. Inject verified input
self.input_history[corrected_frame] = corrected_input
# 3. Fast-forward resimulation to present frame
for f in range(corrected_frame, self.current_frame):
inp = self.input_history.get(f, 0)
self.step_simulation(inp)
self.save_snapshot(f + 1)
return rewind_depth
engine = RollbackEngine()
for f in range(10):
engine.input_history[f] = 0
engine.save_snapshot(f)
engine.step_simulation(0)
engine.current_frame += 1
initial_pos = FixedPointPhysics.to_float(engine.pos_x)
rewound_frames = engine.execute_rollback(corrected_frame=4, corrected_input=1)
reconciled_pos = FixedPointPhysics.to_float(engine.pos_x)
print(f"Rollback Depth: {rewound_frames} frames | Initial Pos: {initial_pos} | Reconciled Pos: {reconciled_pos}")
The Invariant Law of Interactive Latency
You cannot accelerate the speed of light through optical fiber, but you can build architectures that render latency imperceptible. By enforcing strict fixed-point arithmetic, allocating immutable ring-buffer snapshots, and bounding resimulation budgets, rollback netcode transforms physical distance into deterministic simulation truth.
Rollback Netcode Architecture
An empirical exploration through deterministic fixed-point math, circular snapshot buffers, sub-millisecond rollback, and desync verification.