🌿 CuriousWinds

Deterministic Physics & Rollback Netcode in Game Engines

Fixed-point collision integration, state checksum verification, and speculative frame simulation over WAN latency.

Executive Summary & Key Takeaways
Foundational Synthesis for Practitioners & Research Systems

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.

01 Speed-of-Light Limit

Fiber optics cap RTT at 40 ms; jitter extends it, disrupting 6, 9 frames at 60 Hz.

02 Delta-Predicted Rollback

Clients simulate remote actions locally, rolling back to deterministic snapshots on packet arrival.

03 Drift-Induced Cascades

Floating-point errors or variable timesteps trigger unbounded rollback resimulation costs.

04 Fixed-Point Snapshots

Store only delta-encoded inputs in ring buffers to enforce ±1-frame deterministic replay.

Technology & Real-Time Physics READING TIME: ~12 MINS
CuriousWinds Monograph Standard: Written from clean-room primary literature, formal physical derivations, and verified empirical telemetry under Constitution v2.0.
In This Article
2 Curated Inquiries • Computing Systems & Machine Cognition

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”


NOTE

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:

tmin,RTT = 2 · dcfiber = 8 × 106 m2 × 108 m/s = 40 ms

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.

SYSTEM ARCHITECTURE
Multiplayer Physics Architecture Comparison
Latency & Invariance Benchmark
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:

LATENCY BOTTLENECK: LOCKSTEP STALLING AT 60 HZ
66.6 ms Input Lag
Local Input Pressed ───▶ 4-Frame Network RTT Wait ───▶ Action Executes (Unresponsive Feel)

This delay destroys player motor coordination in precision mechanics. Rollback netcode resolves this by separating visual presentation from network confirmation:

  1. Immediate Local Execution: Local player inputs execute on the exact frame they are pressed ($t_0$).
  2. Speculative Remote Prediction: Remote player inputs are assumed to match their last confirmed frame:
ûremote(t) = uremote(tlast confirmed)
  1. 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.
SYSTEM TOPOLOGY & ARCHITECTURE
System Architecture & Operational Pipeline
System Architecture
Stage 01
Frame N: Speculative Prediction Active
Stage 02
Packet Ingestion: Remote Input Differs at Frame N-4
Stage 03
Rewind: Load Bitwise Snapshot of Frame N-4
Stage 04
Inject Verified Remote Input into Input Queue
Stage 05
Resimulate: Run 4 Physics Ticks (N-3, N-2, N-1, N)
Stage 06
Render: Draw Reconciled State at Present Frame N

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:

∀ t,    SA(t) ≡ SB(t) ⟺ SA(0) = SB(0) ∧ uA(\tau) = uB(\tau)    (\tau ≤ t)

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:
Error = |(a · b + c)FMA – ((a · b) + c)| ~ εmachine
  • 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:
(a + b) + c ≠ a + (b + c)
NUMERIC REPRESENTATION
Floating-Point Drift vs. Fixed-Point Bit-Exact Invariance
IEEE 754 vs Fixed-Point Math
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.

MEMORY ARCHITECTURE
Circular Ring-Buffer State Snapshot Arena (64 Frames)
O(1) Circular Modulo Indexing
Slot [0]
Frame N−7
Confirmed
Slot [1]
Frame N−6
Confirmed
Slot [2]
Frame N−5
Rollback Head
Slot [N % 64]
Frame N (Live)
Current Head
Zero Dynamic Allocation Invariant: The snapshot memory pool is statically pre-allocated as a single contiguous array (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:

  1. Contiguous Flat Structures: Isolate all stateful simulation variables into a single plain-old-data (POD) struct with zero pointer indirections:
deterministic-physic_tool.c
C11 · Hardware Architecture
typedef struct {
    uint32_t frame_index;
    FixedPoint32 position[MAX_ENTITIES];
    FixedPoint32 velocity[MAX_ENTITIES];
    uint8_t flags[MAX_ENTITIES];
    uint32_t checksum;
} SimulationState;
  1. 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}$).
  2. Hardware-Accelerated Memory Copy: Capturing a frame snapshot reduces to a single contiguous memory copy:
memcpy(&RingBuffer[t mod N], &CurrentState, sizeof(SimulationState))

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:

Resimulation Cost = K × \tausim

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.

PERFORMANCE BUDGET
Frame Execution Time Budget During Rollback (60 FPS)
Total Budget: 16.66 ms
Resimulation Phase: 6.0 ms
Rewind 5 Frames @ 1.2 ms/frame pure physics execution
Rendering & Audio: 8.0 ms
Interpolation, bone matrix transforms, GPU draw calls
Safety Headroom: 2.66 ms
Guarantees zero dropped frames or audio stuttering

If a single simulation tick requires $4\,\text{ms}$, rewinding 6 frames requires:

tresim = 6 × 4 ms = 24 ms

This immediately exceeds the $16.66\,\text{ms}$ frame deadline, dropping the visual frame rate and inducing cascading input lag.

SYSTEM TOPOLOGY & ARCHITECTURE
System Architecture & Operational Pipeline
System Architecture
Stage 01
Frame Time Evaluation
Stage 02
Trip Frame-Drop Counter
Stage 03
Dynamic Time Warp: Drift Local Clock by +1 ms/frame
Stage 04
Skip Visual Interpolation on Resimulated Ticks
Stage 05
Execute Normal Forward Presentation

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:

NETWORK WIRE PROTOCOL
Sliding Window Redundant UDP Payload Structure
Zero-Resend Packet Redundancy
Sequence Identifier Header uint32 SequenceID
Confirmed Remote ACK Frame Frame N − 8
Historical Input Array: [Frame N, Frame N−1, … Frame N−7]
8 consecutive frames of 16-bit input bitmasks packed into payload. Tolerates up to 7 consecutive dropped UDP packets with 0 ms retransmission stalling.

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:

Δ u(t) = u(t) ⊕ u(t-1)

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:

Checksum(t) = xxHash32(RingBuffer[t mod N])
INTEGRITY VERIFICATION
State Hash Verification & Desynchronization Detection Flow
xxHash32 Checksum Audit
Synchronous State Convergence (Nominal Flow)
Host A: Frame 120 Checksum = 0x8A7F2B01 ──▶ Exchanged via Packet Header
Host B: Frame 120 Checksum = 0x8A7F2B01 ──▶ Match Confirmed (In Perfect Sync)
Desynchronization Detection & Quarantine Protocol
Host A: Frame 121 Checksum = 0x9B1104C2
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-physic_tool.py
Python 3.11 · Diagnostic Framework
"""
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.

Curated Inquiry Series • 10 Investigations

Rollback Netcode Architecture

An empirical exploration through deterministic fixed-point math, circular snapshot buffers, sub-millisecond rollback, and desync verification.

Primary Scholarly Provenance & Empirical Attribution
Card, S. K., Moran, T. P., & Newell, A. (1983). The Psychology of Human-Computer Interaction. Lawrence Erlbaum Associates; ACM SIGCHI Model of Human Processor & Saccadic Latency Foundations.
DOI: 10.1145/358896.358899