Server authority: prediction, rollback, lag-compensated hits

Make Beacon Yard's wrench fair at 250 ms. Learn Roblox's Server Authority model (prediction, rollback, resimulation) in a branch place, then add a clamped one-second rewind buffer so CombatService checks swings against where the drone was.

Lab lesson, about 80 minutes, 9 steps

By the end you can

  • Explain why a fair swing misses at 250 ms of lag, and measure how far the target moved
  • Set up the engine's Server Authority model in a branch place and port the wrench to it
  • Reason about misprediction, rollback and the techniques that hide corrections
  • Build a clamped rewind buffer so CombatService judges a swing where the target was

Before this: The network budget: measure, batch, pack, Custom character controllers and physics

1What the server trusts today

Read how CombatService judges a swing at m14-ship:

	if (origin - head.Position).Magnitude > ORIGIN_MAX_STUDS then
		return "rejected"
	end
 
	local now = workspace:GetServerTimeNow()
	local previousSwing = lastSwing[player]
	if previousSwing ~= nil and now - previousSwing < SWING_GAP then
		return "rejected"
	end
	lastSwing[player] = now
 
	feedback(player, "swing", nil)
 
	local params = RaycastParams.new()
	params.FilterType = Enum.RaycastFilterType.Include
	local targets = CollectionService:GetTagged(DRONE_TAG)
	for _, crawler in CollectionService:GetTagged(CRAWLER_TAG) do
		table.insert(targets, crawler)
	end
	params.FilterDescendantsInstances = targets
 
	local result = workspace:Raycast(origin, direction.Unit * Config.WRENCH_RANGE, params)
Figure 1.1

The client sends two vectors: where the swing starts and which way it points. The server refuses an origin more than ORIGIN_MAX_STUDS = 8 from the head, refuses swings closer than SWING_GAP = 0.4 seconds apart, and casts its own 14-stud ray (WRENCH_RANGE) that can only see parts tagged Drone or Crawler. The client chooses the aim. The server decides the hit, against the world as it is right now on the server.

That last part is the problem this lesson solves.

At m14-ship, which part of a wrench swing does the client control?

  1. The aim: a swing origin near its head and a direction
  2. Whether the swing hit, through a hit flag in the Swing remote
  3. The damage, through WRENCH_DAMAGE on its own copy of Config
  4. The time of the swing, which the server uses to rewind the drone
Answer

The aim: a swing origin near its head and a direction. The client aims; the server checks the origin, the rate and the ray. Every decision that pays out stays on the server.

Open this step in lesson mode · Link to this step · This confused me

2Why a fair swing misses at 250 ms

Follow one swing from a phone with a 250 ms round trip, 125 ms each way. The drone is drawn from the 10 Hz stream of the The network budget: measure, batch, pack lesson, 0.1 s behind. So the drone on the player's screen is where the server had it 0.125 + 0.1 = 0.225 s ago. The player swings at that drone. The swing then takes another 125 ms to reach the server, and in all that time the real drone kept flying.

The drone you see is in the pastA copper server box shows the drone now; a cyan client box shows it 0.225 seconds earlier; a cyan swing box sends the swing back to the server, which checks it against the current drone.125 ms + 0.1 saimServerdrone nowScreendrone 0.225 s agoSwingaimed at old drone
Figure 2.1. The player aims at an old picture; without a rewind the server checks against the new one.

The drone flies at Config.DRONE_SPEED = 12 studs per second. The player's screen shows it 0.225 s in the past. How many studs has the real drone moved since the moment the player is looking at?

Answer

2.7 studs (within 0.01). 12 x 0.225 = 2.7 studs. By the time the swing reaches the server 125 ms later, it is 0.35 s, or 4.2 studs. The drone's hit sphere has a 2-stud radius, so a swing at its centre on screen can miss the real drone entirely.

Run the same situation as numbers. The swing is a 14-stud segment from the player; the test asks how close it passes to the drone.

Luau with roblox-lite (not Roblox)
local DRONE_SPEED, WRENCH_RANGE, HIT_RADIUS = 12, 14, 2
local origin = Vector3.new(0, 4, 0)
 
local function droneAt(t: number): Vector3
	return Vector3.new(-8 + t * DRONE_SPEED, 4, -8) -- flying east
end
 
local function missDistance(o: Vector3, offset: Vector3, center: Vector3): number
	local s = math.clamp((center - o):Dot(offset) / offset:Dot(offset), 0, 1)
	return (center - (o + offset * s)).Magnitude
end
 
local now = 1.0
for _, lag in { 0, 0.1, 0.225, 0.35 } do
	local seen = droneAt(now - lag)
	local aim = (seen - origin).Unit * WRENCH_RANGE
	local gap = missDistance(origin, aim, droneAt(now))
	print(string.format("seen %.3f s ago: passes %.2f studs from the real drone, %s", lag, gap, if gap <= HIT_RADIUS then "hit" else "miss"))
end
Figure 2.2. Run it in the lesson view or in the Studio command bar.

Open this step in lesson mode · Link to this step · This confused me

3Two ways to stop the lag from deciding

Server sideLag-compensated hit checks with a rewind buffer is a referee who winds the replay back to the moment of the swing.
In the pictureIn Roblox
The replay footageThe server's own position history for each target
Winding back to the moment of the swingLooking up where the target was at the moment the client saw
The footage only goes back a short timeMAX_REWIND clamps every claimed moment
The referee picks the frame, not the playerThe server turns the client's claim into its own time and checks it

See the whole analogy cast

Think of a referee with a replay screen. A player swings at an opponent who was there on the player's own view. Instead of judging the moment the claim reaches the referee, the referee winds the footage back to the moment of the swing and judges it there. The footage only goes back a short time, and the referee, not the player, picks the frame.

Think of it as A referee who winds the replay back to the moment of the swing

Roblox gives you two ways to build that referee. With Server Authority, the engine runs the simulation on the server, and each client predicts ahead and corrects itself1. Without it, you keep today's design, where the server checks every request, and add a rewind buffer for the checks that depend on time, such as a hit. Beacon Yard's main game takes the second path, and you try the first in a separate branch place.

Other ways pros do this

OptionWhat it isWhen pros pick itTrade-offs
Plausibility checks plus a rewind bufferThe server checks every request (range, rate, shape) and judges hits against a short position history.Most Roblox games, including Beacon Yard's main game: Humanoid characters, tools, a few remotes.You write each check yourself; the rewind favours the attacker within its limit.
Server Authority (AuthorityMode Server)Engine netcode: the server simulates, clients predict and roll back.Competitive movement, vehicles and physics where speed and fly cheats must be impossible.Needs fixed-step simulation code, the Input Action System and rebuilt tools; corrections show on bad connections.
Client-decided hitsThe client reports what it hit and the server pays out.Never for anything that pays coins, damage or progress.Feels perfect on every connection and is trivially cheated.

Why does Beacon Yard's main game keep plausibility checks and add a rewind buffer, instead of switching straight to AuthorityMode Server?

  1. Switching means rewriting the wrench Tool, input and core logic around the simulation, while the rewind buffer fixes the lag problem with one module
  2. Server Authority is only available in beta places
  3. Server Authority cannot stop speed cheats
  4. A rewind buffer makes cheating impossible
Answer

Switching means rewriting the wrench Tool, input and core logic around the simulation, while the rewind buffer fixes the lag problem with one module. Server Authority is the bigger, future-proof move and is tried in a branch place. The rewind buffer is a contained fix that keeps today's checks.

Open this step in lesson mode · Link to this step · This confused me

4The engine's model: predict, roll back, resimulate

In the Server Authority model the server is the single source of truth, and clients are trusted only to report their inputs1. Waiting for the server on every key press would feel laggy, so each client predicts a few frames ahead of the last server state it knows. When the server's state for a frame arrives and differs from what the client predicted, that is a misprediction: the client resets to the server's state for that frame and resimulates the frames since, replaying its own inputs. The docs call mispredictions normal, because no client can predict other players' inputs.

Predict ahead, correct from behindA cyan client box predicting frame 7 sends inputs to a copper server box at frame 3; the server returns its state for frame 3, and the client resimulates frames 4 to 6 if it guessed wrong.inputsClientpredicting frame 7Serverat frame 3
Figure 4.1. The client runs ahead of the last server state it knows and replays from it when they disagree.

Setting Workspace.AuthorityMode to Server turns on what the model needs: NextGenerationReplication, PlayerScriptsUseInputActionSystem, SignalBehavior Deferred, UseFixedSimulation and StreamingEnabled. Core logic goes in functions bound with RunService:BindToSimulation(), in a module both the client and the server run. BindToSimulation calls them at a fixed rate, not once per rendered frame, and calls them again when the client resimulates2.

Put a client's misprediction handling in order.

  1. It compares that state with what it predicted for the same frame
  2. They differ, so it resets to the server's state for that frame
  3. The client receives the server's authoritative state for an earlier frame
  4. It resimulates the frames since, replaying its own inputs, back up to the present
Answer

1. The client receives the server's authoritative state for an earlier frame 2. It compares that state with what it predicted for the same frame 3. They differ, so it resets to the server's state for that frame 4. It resimulates the frames since, replaying its own inputs, back up to the present. Receive, compare, roll back, resimulate. If the prediction was right, nothing happens; most of the time it is.

Time matters inside the simulation. Under AuthorityMode Server, time() is fixed-step simulation time shared by client and server, and it rewinds during a resimulation. tick(), os.time() and os.clock() read local clocks and do not rewind, so the docs tell you not to use them for anything that affects the simulation.

Inside a function bound with BindToSimulation, the wrench's cooldown checks whether 0.4 s have passed since the last swing. Which clock should it use?

  1. time(), because it is shared simulation time that rewinds with resimulation
  2. os.clock(), because it is the most precise
  3. tick(), because it is the same on every device
  4. workspace:GetServerTimeNow(), because the server decides
Answer

time(), because it is shared simulation time that rewinds with resimulation. Replayed frames must see the same time they saw the first time, so simulation logic uses time().

Here is that proof as numbers. Swing is pressed on frames 1 and 4, 0.1 s apart, with a 0.4 s cooldown. Live, the swing on frame 4 is blocked. Then the server disagrees about frame 3, so the client restores the state it saved after frame 3 and replays frames 4 to 6 straight away. Then try COOLDOWN = 0.3: both replays agree with the live run, which is why this bug only shows up some of the time.

Luau
local COOLDOWN, STEP = 0.4, 0.1
local presses = { [1] = true, [4] = true } -- Swing is pressed on frames 1 and 4
 
local function simulate(first, last, lastSwing, clock)
	local log = {}
	for frame = first, last do
		local now = clock(frame)
		if presses[frame] then
			if now - lastSwing >= COOLDOWN then
				lastSwing = now
				table.insert(log, "f" .. frame .. " swing")
			else
				table.insert(log, "f" .. frame .. " blocked")
			end
		end
	end
	return table.concat(log, " ")
end
 
-- time(): the simulation's own clock, frame times that rewind with the replay.
local function simTime(frame)
	return frame * STEP
end
 
-- os.clock(): a local clock that kept running and is already past frame 6.
local wall = 0.65
local function wallClock()
	wall += 0.001
	return wall
end
 
print("live: " .. simulate(1, 6, -math.huge, simTime))
-- Rolled back to the state saved after frame 3: the last swing was at 0.1.
print("replay with time(): " .. simulate(4, 6, 0.1, simTime))
print("replay with os.clock(): " .. simulate(4, 6, 0.1, wallClock))
Figure 4.2. Expected output: live: f1 swing f4 blocked replay with time(): f4 blocked replay with os.clock(): f4 swing

Open this step in lesson mode · Link to this step · This confused me

5Port the wrench in a branch place

The main game stays as it is. Make a copy, a branch place, and see what the move costs. Two facts from the docs shape the port1. First, Tools are not fully supported yet: Humanoid:EquipTool() and UnequipTools() have no Simulation Access. To build an equippable item, clone and weld a model to the character inside the simulation and track whether it is equipped with an attribute. Second, every input that affects the simulation goes through the Input Action System, with the InputContext under the Player.

Try these steps in the separate branch place. The core of step 4 looks like this. It is a sketch built from the docs' patterns, not code from the tag, so test it in your branch:

luau
-- ReplicatedStorage.WrenchSim, required and initialised by a Script and a LocalScript.
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
 
local COOLDOWN = 0.4
local WrenchSim = {}
 
function WrenchSim.Initialize()
	RunService:BindToSimulation(function(_deltaTime)
		for _, player in Players:GetPlayers() do
			local character = player.Character
			local inputs = player:FindFirstChild("Inputs")
			if character == nil or inputs == nil then
				continue
			end
			-- Read the action, and keep last frame's value in an attribute to find the rising edge.
			local held = inputs.WrenchContext.Swing:GetState() == true
			local wasHeld = character:GetAttribute("SwingHeld") == true
			character:SetAttribute("SwingHeld", held)
			if held and not wasHeld and character:GetAttribute("WrenchEquipped") == true then
				local last = character:GetAttribute("LastSwing") or -math.huge
				if time() - last >= COOLDOWN then
					character:SetAttribute("LastSwing", time())
					-- The hit check runs here; only the server changes health.
				end
			end
		end
	end)
end
 
return WrenchSim

InputAction:GetState has Simulation Access, and the docs suggest recording the previous frame's input in an attribute, as SwingHeld does1.

  1. Build m14-ship into a local place file. Set Workspace > AuthorityMode to Server and inspect the five settings that go with it.
  2. Add ReplicatedStorage.Inputs with WrenchContext and a Bool Swing action bound to F and ButtonR2. Use the docs' input setup script to clone the inputs into each player.
  3. Weld a wrench model to the right hand in the bound simulation and record WrenchEquipped as a character attribute.
  4. Run WrenchSim on both sides with BindToSimulation. On the rising edge of Swing, check the LastSwing attribute against time() and enforce a 0.4 s cooldown. Run the hit check and health update on the server.
  5. Open the visualizer with Ctrl+Shift+F6. Open Test > Device Simulator, choose Network on its toolbar and apply 125 ms each for Inbound and Outbound latency. Check prediction success, input acceptance and the client-server step delta3.
Roblox Studio
The server authority visualizer open over Beacon Yard's branch place during a drill with the drone hovering above the player, showing Instance prediction, Input accept, Step offset, Input latency and FPS.
Figure 5.1.

The server authority visualizer in the branch place, with 125 ms of latency each way.

Why does the branch place replace Beacon Yard's Wrench Tool with a welded model and an attribute?

  1. Tools are not fully supported under Server Authority: EquipTool and UnequipTools have no Simulation Access
  2. Tools cannot hold a mesh handle under Server Authority
  3. A welded model replicates fewer bytes than a Tool
  4. The Input Action System cannot read the F key
Answer

Tools are not fully supported under Server Authority: EquipTool and UnequipTools have no Simulation Access. Only members with Simulation Access may run inside bound functions. Equipping a Tool is not one of them yet, so the wrench becomes a welded model.

Open this step in lesson mode · Link to this step · This confused me

6When the client guesses wrong

Mispredictions happen, so the question is how they look. The techniques page lists the main tools4:

  • Position smoothing: simulate an invisible object and draw a visual-only clone that follows it smoothly, for example with TweenService:SmoothDamp on RenderStepped. A correction moves the invisible object at once; the visible one glides.
  • Effects outside the simulation: sounds and particles go in a RenderStepped function that reads the simulation's state, and must be able to undo an effect for an event the server never confirmed.
  • Designing around latency: an explosion after a short fuse hides a correction better than an instant one, because the resimulation lands on the fuse.
  • Instance stitching: an instance created inside the simulation appears on the client at once and merges with the server's copy when it arrives.

Match each symptom in the branch place to the technique that hides it.

  1. The drone snaps two studs sideways when the server corrects it
  2. A hit spark plays for a swing the server rejected
  3. A charge attack lands with a visible jump on bad connections
  4. A dropped scrap piece appears late, then pops in
Answer

The drone snaps two studs sideways when the server corrects it: Draw a smoothed visual clone of the simulated object; A hit spark plays for a swing the server rejected: Trigger effects from simulation state in RenderStepped, and undo them; A charge attack lands with a visible jump on bad connections: Add a short wind-up before the effect lands; A dropped scrap piece appears late, then pops in: Create it inside the simulation so it is stitched. Smoothing hides position snaps, undoable effects hide wrong guesses, wind-ups move corrections to a less visible moment, and stitching shows created instances at once.

Open this step in lesson mode · Link to this step · This confused me

7Lag-compensated hits in the main game

Back in the main game. The server keeps a rewind bufferRewind buffer (lag compensation)A short server-side history of where each target was, used to judge a hit at the moment the attacker saw it.Think of it as a referee's replay screen that only goes back half a second. for each target: a list of (time, position) samples covering the last second, added on every Heartbeat. When a swing arrives, the client also says which moment it was looking at. The server clamps that claim, looks up where the target was then, and tests the swing against that position.

Server sideRemember: Lag-compensated hit checks with a rewind buffer is a referee who winds the replay back to the moment of the swing.

Three rules keep the replay honest. The referee picks the footage: the server keeps the history, and the client only names a moment. The replay has a limit: MAX_REWIND = 0.5 s, so nobody claims a hit from long ago. And a claim that is not a finite number, or is in the future, means now.

Watch the rewind work in the simulator below. Raise the ping and swing at the drone, then compare the three checks: the server's current position, the position you saw, and the position clamped to MAX_REWIND. Notice where the clamp starts to reject a swing that the full rewind would accept.

The lag and rewind yard

The lag and rewind yard: a still of the simulation
Figure 7.1.

MAX_REWIND is 0.5. What does this print?

local MAX_REWIND = 0.5
local function rewindTime(now, claimed)
	if typeof(claimed) ~= "number" or claimed ~= claimed or math.abs(claimed) == math.huge then
		return now
	end
	return math.clamp(claimed, now - MAX_REWIND, now)
end
print(rewindTime(100, 99.8), rewindTime(100, 97), rewindTime(100, 0/0))
  1. 99.8 99.5 100
  2. 99.8 97 100
  3. 99.8 99.5 nan
  4. 100 100 100
Answer

99.8 99.5 100. Clamping turns any claim into a time inside the last half second. A cheater can still choose a moment, but only a recent one, and the server's own history decides where the target was.

Write the lookup. at(history, t) blends the two samples around t, holds the oldest before it and the newest after it.

Luau with roblox-lite (not Roblox)
type Sample = { t: number, position: Vector3 }
 
local function at(samples: { Sample }, t: number): Vector3?
	-- Blend the two samples around t. Hold the ends. nil when empty.
	local newest = samples[#samples]
	return if newest then newest.position else nil
end
 
local samples = {}
for i = 0, 10 do
	local t = i / 10
	table.insert(samples, { t = t, position = Vector3.new(t * 12, 4, 0) })
end
print(at(samples, 0.25))
Figure 7.2. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

Open this step in lesson mode · Link to this step · This confused me

8Build it: rewind the drone

The drone is now drawn from your own stream, so the client knows exactly which two packets it was blending, and how far between them. It converts the pair to an adjacent sequence and blend fraction. When that pair is available, it sends both values with the swing. The server resolves them against its own send times.

local function droneHit(origin: Vector3, direction: Vector3, seenSeq: unknown, alpha: unknown): (number?, number)
	local now = workspace:GetServerTimeNow()
	local at = RewindBuffer.rewindTime(now, DroneService.sentTime(seenSeq, alpha))
	local offset = direction.Unit * Config.WRENCH_RANGE
	local bestId: number? = nil
	local bestDistance = math.huge
	for id, history in DroneService.histories() do
		local position = RewindBuffer.at(history, at)
		if position ~= nil and RewindBuffer.rayHitsSphere(origin, offset, position, DroneService.HIT_RADIUS) then
			local distance = (position - origin).Magnitude
			if distance < bestDistance then
				bestId = id
				bestDistance = distance
			end
		end
	end
	return bestId, bestDistance
Figure 8.1

Build along

m14-ship to m15-scale

  • src/shared/RewindBuffer.luau
  • src/server/DroneService.luau
  • src/client/DroneClient.luau
  • src/client/CombatClient.luau
  • src/server/CombatService.luau
  • src/server/RemoteGuard.luau
  1. Record RewindBuffer.push(drone.history, now, drone.position) after moving the drone on Heartbeat. RewindBuffer drops samples older than one second and interpolates between retained samples.

    You should see DroneService.histories returns per-drone samples from the last second.

  2. Record the time and owning sequence in a 64-slot ring in sendSnapshots. In sentTime, require a finite integer sequence and an alpha from 0 through 1. The newest send can resolve at alpha 0, and a sequence whose slot has been overwritten returns nil.

    You should see sentTime returns the time between adjacent sends when both are available.

  3. Use DroneClient.seen() to translate the rendered pair into an adjacent send sequence and fraction even if a packet was skipped. CombatClient sends both extra arguments only when it has them. RemoteGuard accepts the two-argument form too.

    You should see Swing sends origin and direction, with an optional sequence and fraction.

  4. Keep the existing checks in CombatService.trySwing. Use RewindBuffer.rewindTime to clamp the claimed send time to the past 0.5 s, or use the current time when it cannot be resolved. Compare the nearest qualifying drone centre with the crawler raycast distance, and keep damage at Config.WRENCH_DAMAGE. This version also clears lastSwing through the player scope. Apply 125 ms each way in the Network Simulator and record the results.

    You should see The test compares swings at the visible drone with swings away from it.

Why does the client send the sequence number and blend fraction it was drawing, instead of its own os.clock() time?

  1. The server recorded when it sent each packet, so it can turn seq and fraction into its own time without trusting the client's clock
  2. os.clock() cannot be sent through a RemoteEvent
  3. Sequence numbers make the swing travel faster
  4. It lets the client choose how far back to rewind
Answer

The server recorded when it sent each packet, so it can turn seq and fraction into its own time without trusting the client's clock. The client names a picture, the server knows when it sent that picture, and the clamp limits how far back that can be. Crawlers are still replicated by the engine, so the client cannot name the moment it saw them; their check stays as it is until they move to a stream of their own.

Players' characters are the harder case, for PvP or co-op hits. The engine replicates them, so there is no packet to name. The usual approach is for the server to keep a short position history for each character's root part, just like RewindBuffer, and estimate the moment the attacker saw. That is roughly now minus the attacker's one-way latency, about half of Player:GetNetworkPing(), which returns the round trip, minus the engine's interpolation delay. Ping jitters, so studios smooth that estimate over several samples and still clamp the result to MAX_REWIND, so that a spike cannot buy a longer rewind.

Where does it break?“A referee who winds the replay back to the moment of the swing” is a good picture of lag-compensated hit checks with a rewind buffer. Where does it stop being true?

It breaks here. The target saw a newer moment: judging at the attacker's moment overrules the target, who can be hit after reaching cover on their own screen.

The true model. Rewinding favours the attacker within the limit. The limit is a fairness trade-off between laggy attackers and targets, set a little above the rewind amounts honest players need.

Two players: A at 250 ms, B at 20 ms. On B's screen, B ducks behind a scrap stack. A swings at where B was 0.2 s ago, and the rewind says it hit. What does B experience?

  1. B is hit after reaching cover on their own screen, because the rewind favours the attacker
  2. Nothing; the rewind only affects A's screen
  3. B is pulled back out from behind the stack
  4. The hit is refused because B's ping is lower
Answer

B is hit after reaching cover on their own screen, because the rewind favours the attacker. A referee with a replay judges one player's moment, and the other player lives with it. The MAX_REWIND limit is the trade-off: bigger is fairer to laggy attackers, smaller is fairer to targets.

Open this step in lesson mode · Link to this step · This confused me

9Challenges and recap

Level 1, Apprentice

Challenge

Measure the problem before fixing it: test the m14-ship wrench with 250 ms of added round trip.

Start from
The game at milestone m14 (download)

Done means

  • You swung 20 times at a drone flying across you with 125 ms inbound and 125 ms outbound latency applied
  • You recorded how many swings landed
  • You wrote one sentence on how far ahead of the drone you had to aim

Hints

  1. Test > Device Simulator, then the Network pill. Set both directions to Custom 125 ms.
  2. Stand still and let the drone cross in front of you so every swing is the same.

Your logs show honest players' rewind amounts cluster between 0.05 s and 0.3 s. A teammate wants MAX_REWIND at 2 s, 'to be safe'. What is the strongest objection?

  1. Every player could then claim hits up to 2 s back, which hurts targets far more than it helps the rare very laggy attacker
  2. The history would use too much memory
  3. GetServerTimeNow cannot represent 2 s
  4. Clamping only works for values under 1
Answer

Every player could then claim hits up to 2 s back, which hurts targets far more than it helps the rare very laggy attacker. Set the limit from data: a little above the honest cluster. A larger limit hands every attacker more power over targets.

Level 2, Builder

Challenge

Fix at in the rewind-at Run above.

Start from
The game at milestone m14 (download)
Check it here
Run the code cell in the lesson view; the challenge completes when it passes. No Studio needed.

Done means

  • at blends the two samples around t
  • It holds the oldest sample before the history and the newest after it
  • It returns nil for an empty history and every test in rewind-at passes

Hints

  1. Check t <= samples[1].t and t >= samples[#samples].t first.
  2. a.position + (b.position - a.position) * alpha blends two positions.
Solution
luau
type Sample = { t: number, position: Vector3 }
 
local function at(samples: { Sample }, t: number): Vector3?
	local first, last = samples[1], samples[#samples]
	if first == nil then
		return nil
	end
	if t <= first.t then
		return first.position
	end
	if t >= last.t then
		return last.position
	end
	for i = 1, #samples - 1 do
		local a, b = samples[i], samples[i + 1]
		if t >= a.t and t <= b.t then
			local alpha = (t - a.t) / (b.t - a.t)
			return a.position + (b.position - a.position) * alpha
		end
	end
	return last.position
end
 
local samples = {}
for i = 0, 10 do
	local t = i / 10
	table.insert(samples, { t = t, position = Vector3.new(t * 12, 4, 0) })
end
print(at(samples, 0.25))

Level 3, Professional

Challenge

Write the rewind buffer in the game repo's challenges/work/rewind_buffer.luau, then run the server-authority challenge through the Course Runner.

Start from
The game at milestone m14 (download)
Grade it
In Studio, press Play, then run game.ServerScriptService.RunGameTests:Invoke("server-authority") in the server command bar. Copy the pass code from Output.

Done means

  • challenges/work/rewind_buffer.luau keeps one second of samples and blends between them
  • rewindTime clamps to MAX_REWIND, refuses future times and treats NaN, infinity and non-numbers as now
  • rayHitsSphere tests the whole swing segment, not just its end
  • The server-authority challenge prints TEST PASS for all nineteen checks, including lag_rewound_hits

Hints

  1. After inserting a sample, remove from the front while the oldest is older than t - HISTORY_SECONDS.
  2. Project the centre onto the swing: s = clamp(dot(center - origin, offset) / dot(offset, offset), 0, 1).
  3. typeof(claimed) == "number" and claimed == claimed rules out non-numbers and NaN.

Retiring the analogy

You no longer need “a referee who winds the replay back to the moment of the swing”. Rewinding favours the attacker within the limit. The limit is a fairness trade-off between laggy attackers and targets, set a little above the rewind amounts honest players need.

Recap

  1. At 250 ms a player sees the drone about 0.225 s in the past, 2.7 studs behind the real one, so a fair swing misses unless the server rewinds.
  2. Server Authority makes the server the only truth: clients send inputs, predict ahead, and roll back and resimulate on a misprediction. AuthorityMode Server sets five more Workspace properties with it.
  3. Under Server Authority, core logic runs in BindToSimulation using time(); Tools need rebuilding as welded models, and effects run in RenderStepped and must be undoable.
  4. A rewind buffer keeps one second of positions per target; the server clamps the claimed moment to MAX_REWIND and tests the swing as a segment against a sphere there.
  5. Rewinding favours the attacker; the limit is a fairness trade-off set from real ping data.

Lag-compensated hit checks with a rewind buffer is a referee who winds the replay back to the moment of the swing, until the target saw a newer moment: judging at the attacker's moment overrules the target, who can be hit after reaching cover on their own screen.

Next Big worlds: streaming, LOD and interest management

Open this step in lesson mode · Link to this step · This confused me