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

Step 1 of 9

What 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)

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.

Choose one

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

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

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 2 of 9

Why 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
The player aims at an old picture; without a rewind the server checks against the new one.
Work it out

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?

studs

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)
Ctrl Enter runs the cell.

Link to this step · This confused me

Step 3 of 9

Two 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.
Choose one

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

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

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 4 of 9

The 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
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 in order

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

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.

Choose one

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?

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?

Press 1 to 4 to choose, Enter to check.

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
Ctrl Enter runs the cell. Checked against the expected output

Link to this step · This confused me

Step 5 of 9

Port 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.

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

Choose one

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

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

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 6 of 9

When 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 the pairs

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

Link to this step · This confused me

Step 7 of 9

Lag-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

Goal At 150 ms or more, land a hit that only the rewound checks accept, then at 600 ms or more swing and see the clamp reject it.

The lag and rewind yard: a preview of the simulation
Predict the output

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))
MAX_REWIND is 0.5. What does this print?

Press 1 to 4 to choose, Enter to check.

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)
Ctrl Enter runs the cell. Checked by tests

Link to this step · This confused me

Step 8 of 9

Build 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

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.

Choose one

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

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

Press 1 to 4 to choose, Enter to check.

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.

Choose one

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?

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?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 9 of 9

Challenges 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

Meet the criteria above, then record your own result. No test grades this check.

Choose one

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?

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?

Press 1 to 4 to choose, Enter to check.

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; 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

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

The Course Runner prints this code when the test passes.

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

Link to this step · This confused me