zense/rewind

Client prediction, server reconciliation, interpolation and lag compensation for Roblox, with safe buffer codecs for UnreliableRemoteEvent.

Rewind

Client prediction, server reconciliation, interpolation and lag compensation for Roblox.

The player's own movement responds instantly, the server stays the authority, and other players move smoothly. You write one deterministic simulate(state, input, dt) that both sides run. Rewind handles the rest:

ModuleSideWhat it does
Rewind.TickerbothFixed-timestep clock: turns frame times into whole simulation ticks
Rewind.PredictorclientSimulates inputs right away; when the server answers, rewinds and replays if the prediction was wrong
Rewind.AuthorityserverSimulates each player's inputs in tick order. Speed hacks can't run more ticks than the server, and lost packets don't stall the player
Rewind.TimelinebothTimestamped history: interpolate other players, or rewind hitboxes for lag compensation
Rewind.CodecbothCompact buffer encoding for UnreliableRemoteEvent. Decoding untrusted buffers never errors
Rewind.LerpbothDefault blending and comparison for states

Rewind doesn't own your remotes or your characters, and it has no dependencies. It suits custom character controllers and anything else you move yourself. It isn't for Humanoid physics, which the engine owns.

How it fits together

-- Shared: the same simulation on both sides.
local function simulate(state: State, input: Input, dt: number): State
	return { position = state.position + Vector3.new(input.moveX, 0, input.moveZ) * 16 * dt }
end

-- Client, every tick:
local tick = predictor:predict(Input:quantize(readInput()))
inputRemote:FireServer(InputPacket:encode(predictor:recentInputs(4)))
-- Client, when the server's state for a tick arrives:
predictor:reconcile(packet.tick, packet.state)

-- Server, when inputs arrive (repeats from redundant packets are ignored):
local packet = InputPacket:decode(data) -- nil if malformed
for _, entry in packet do
	authority:receive(entry.tick, entry.input)
end
-- Server, once per tick:
if authority:step() > 0 then
	ackRemote:FireClient(player, AckPacket:encode({ tick = authority.tick, state = authority.state }))
end

There's a complete, playable example in examples/: a kinematic character with walking, jumping, interpolated remote players and a lag-compensated hit check. Run rojo serve dev.project.json and start a local server with two players.

Install

Wally

[dependencies]
Rewind = "layfate/[email protected]"

pesde

pesde add zense/rewind

Manually: download Rewind.rbxm from the latest release and put it in ReplicatedStorage.

Requirements

  • Luau's new type solver, for the codec's inferred types. Rewind uses type functions, which the old solver doesn't support. At runtime it works either way.
  • Rewind's modules use string requires (require("./Lerp")), which Roblox supports.

Rules for simulate

  1. Deterministic. The same state and input give the same result on the client and the server. Don't read os.clock(), math.random() or the workspace; put everything the simulation needs in the state or the input.
  2. Return a new state. Don't change the one you're given: the predictor keeps old states to compare with the server's. Rewind errors if simulate returns the same table it got.
  3. Predict with quantized inputs. A codec may round values (Codec.ranged uses 2 bytes). Use Input:quantize(input) so the client simulates exactly what the server will decode.

Predictor

local predictor = Rewind.Predictor.new({
	state = spawnState,     -- the server must start from the same state
	simulate = simulate,
	tickRate = 60,          -- optional, default 60
	isClose = nil,          -- optional: compare predicted and server states (default: every field within 0.001)
	maxPending = 120,       -- optional: unconfirmed ticks to keep
})
predictor:predict(input)Simulates one tick now and returns its tick number
predictor:reconcile(tick, state)Applies the server's state. Returns true if the prediction was wrong and it rewound and replayed. Old or reordered acknowledgements are ignored
predictor:recentInputs(n)The newest n unconfirmed inputs. Send several per packet so one lost packet loses nothing
predictor:reset(tick, state)Starts again, for example after a server-side teleport
predictor.state, .tick, .ackTick, .corrections

Authority

local authority = Rewind.Authority.new({
	state = spawnState,
	simulate = simulate,
	validateInput = nil, -- optional: reject malformed inputs
	maxCatchUp = 3,      -- optional: most ticks per step() after jitter
	maxBuffer = 32,      -- optional: how far ahead of the server inputs may be
	lossWait = 2,        -- optional: steps to wait for a lost input before repeating the last one
})
authority:receive(tick, input)Buffers an input. Returns false and "Old", "Duplicate", "TooFarAhead" or "Invalid" if refused
authority:step()Call once per server tick. Simulates the inputs that are due and returns how many it simulated
authority:reset(tick, state)Starts again. Tell the client so it resets its predictor
authority.state, .tick, .filled

Why it's safe: each step() earns one tick of credit, saved up to maxCatchUp, so a client sending inputs faster than real time gains nothing. Inputs are only ever simulated, never trusted as state. When a tick's input is lost but later ones have arrived, the server waits lossWait steps, then repeats the last input and moves on; the client corrects when the server's state arrives.

Timeline

local timeline: Rewind.Timeline<Vector3> = Rewind.Timeline.new({ duration = 1 })
timeline:push(serverTime, position)          -- times must increase; out-of-order pushes are ignored
local shown = timeline:sample(serverTimeNow - 0.1) -- blended between the two states around that time
  • Interpolation: draw other players about 100 ms in the past, so there are always two snapshots to blend between.
  • Lag compensation: keep a timeline per hitbox on the server and check a shot against timeline:sample(shotTime), where shotTime is what the shooter saw. Cap how far back you rewind.

sample holds the oldest or newest state outside the range; it doesn't extrapolate. Pass lerp to blend your own types. The default handles numbers, Vector3, CFrame, Vector2, Color3, UDim2 and tables of them.

Codec

local Codec = Rewind.Codec

local Input = Codec.struct({
	moveX = Codec.ranged(-1, 1), -- 2 bytes; -1, 0 and 1 are exact
	moveZ = Codec.ranged(-1, 1),
	jump = Codec.bool,
})
export type Input = typeof(Input.Type) -- { jump: boolean, moveX: number, moveZ: number }

local InputPacket = Codec.array(Codec.struct({ tick = Codec.u32, input = Input }), 4)
local data = InputPacket:encode(predictor:recentInputs(4)) -- 37 bytes
local packet, err = InputPacket:decode(data)               -- nil, reason if malformed
CodecBytesNotes
u8 u16 u32 i8 i16 i321–4Encoding refuses values that don't fit instead of wrapping
f32 f644, 8NaN and ±infinity are refused in both directions
bool1Any byte other than 0 or 1 is refused
vector312Three f32s
ranged(min, max)2Clamped. min, max and the midpoint are exact
string(maxBytes)1–2 + lengthValid UTF-8 only
enum(values)1Up to 256 values
optional(codec)1 + codec
array(codec, maxCount)1–2 + items
struct(fields)sum of fieldsFields go in sorted name order, with no names on the wire

codec:decode(data) never errors. A truncated, oversized or malformed buffer returns nil and a reason, so it's safe to call directly on whatever a client sends. codec:size(value) gives the encoded size. Unreliable events drop payloads over about 900 bytes, so check big packets.

Development

Install the toolchain with Rokit by running rokit install, then:

lune run tests/run                         # tests (or: luau tests/run.luau)
stylua --check src tests examples          # format
selene src tests examples                  # lint
scripts/check-types.sh globalTypes.d.luau  # types, including the tests that must fail
rojo serve dev.project.json                # the example in Studio

The tests include an end-to-end run: a client and a server over a simulated network with latency, jitter and 20% packet loss in both directions, using the real codecs. Across 10 seeds, the client must end up in exactly the server's state. check-types.sh needs the Roblox type definitions from luau-lsp. CI runs all of these on every push and pull request.

Releasing: bump the version in src/init.luau, wally.toml and pesde.toml, add a CHANGELOG.md section, and push a vX.Y.Z tag. The release workflow builds Rewind.rbxm, creates the GitHub release and publishes to Wally and pesde when the WALLY_TOKEN and PESDE_TOKEN secrets are set.

License

MIT