Lesson 6 of 11
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.
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)
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?
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 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.
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
Open this step in lesson mode · Link to this step · This confused me
3Two ways to stop the lag from deciding
| In the picture | In Roblox |
|---|---|
| The replay footage | The server's own position history for each target |
| Winding back to the moment of the swing | Looking up where the target was at the moment the client saw |
| The footage only goes back a short time | MAX_REWIND clamps every claimed moment |
| The referee picks the frame, not the player | The server turns the client's claim into its own time and checks it |
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
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Plausibility checks plus a rewind buffer | The 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 hits | The 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?
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.
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.
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?
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.
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))
live: f1 swing f4 blocked
replay with time(): f4 blocked
replay with os.clock(): f4 swingOpen 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:
-- 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.
- Build
m14-shipinto a local place file. Set Workspace > AuthorityMode to Server and inspect the five settings that go with it. - Add
ReplicatedStorage.InputswithWrenchContextand a BoolSwingaction bound toFandButtonR2. Use the docs' input setup script to clone the inputs into each player. - Weld a wrench model to the right hand in the bound simulation and record
WrenchEquippedas a character attribute. - Run
WrenchSimon both sides withBindToSimulation. On the rising edge ofSwing, check theLastSwingattribute againsttime()and enforce a 0.4 s cooldown. Run the hit check and health update on the server. - 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.

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?
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:SmoothDamponRenderStepped. A correction moves the invisible object at once; the visible one glides. - Effects outside the simulation: sounds and particles go in a
RenderSteppedfunction 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.
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

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))
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.
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))
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
src/shared/RewindBuffer.luausrc/server/DroneService.luausrc/client/DroneClient.luausrc/client/CombatClient.luausrc/server/CombatService.luausrc/server/RemoteGuard.luau
Record
RewindBuffer.push(drone.history, now, drone.position)after moving the drone onHeartbeat.RewindBufferdrops samples older than one second and interpolates between retained samples.You should see DroneService.histories returns per-drone samples from the last second.
Record the time and owning sequence in a 64-slot ring in
sendSnapshots. InsentTime, 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.
Use
DroneClient.seen()to translate the rendered pair into an adjacent send sequence and fraction even if a packet was skipped.CombatClientsends both extra arguments only when it has them.RemoteGuardaccepts the two-argument form too.You should see Swing sends origin and direction, with an optional sequence and fraction.
Keep the existing checks in
CombatService.trySwing. UseRewindBuffer.rewindTimeto 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 atConfig.WRENCH_DAMAGE. This version also clearslastSwingthrough 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?
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?
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
- Test > Device Simulator, then the Network pill. Set both directions to Custom 125 ms.
- 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?
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
- Check t <= samples[1].t and t >= samples[#samples].t first.
- a.position + (b.position - a.position) * alpha blends two positions.
Solution
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
- After inserting a sample, remove from the front while the oldest is older than t - HISTORY_SECONDS.
- Project the centre onto the swing: s = clamp(dot(center - origin, offset) / dot(offset, offset), 0, 1).
- 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
- 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.
- 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.
- 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.
- 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.
- 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.
Queued for review
- 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?
- Put a client's misprediction handling in order.
- 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?
- MAX_REWIND is 0.5. What does this print?
Open this step in lesson mode · Link to this step · This confused me