Lesson 3 of 11
One source of truth: replicated state
Give Beacon Yard one source of truth: a server-owned PlayerState sent as numbered diffs with a snapshot for late joiners, one client store for the HUD, shop and settings, the costs of attributes and remotes, and Charm, Replica and Reflex compared.
By the end you can
- Find where Beacon Yard's player state travels today and why a player who joins mid-drill sees the wrong phase
- Keep one server-owned state per player and send it as small numbered diffs, with a snapshot for late joiners
- Feed the HUD, shop and settings from one client store, and keep events separate from state
- Choose between attributes, remotes, a hand-rolled store, Charm, Replica and Reflex
Before this: Lifetimes: signals, Trove and leak hunting, Remotes: events, functions, unreliable, buffers, UI frameworks, part 2: the React-lua shop, Fusion, Vide and when to use one
Step 1 of 10
Join mid-drill and the HUD says Idle
This is how the round reaches clients, in RoundService:
local function publish(phase: RoundPhase, endsAt: number)
Remotes.get("RoundState"):FireAllClients(phase, endsAt)
workspace:SetAttribute("RoundPhase", phase)
workspace:SetAttribute("RoundEndsAt", endsAt)
The HUD starts with phase = "Idle" and endsAt = 0, and this is the only code that changes them:
local roundState = remoteEvent("RoundState")
roundState.OnClientEvent:Connect(function(...: unknown)
local values: { unknown } = { ... }
local nextPhase: RoundPhase? = parsePhase(values[1])
local nextEndsAt = values[2]
if nextPhase == nil or typeof(nextEndsAt) ~= "number" then
return
end
phase = nextPhase
endsAt = nextEndsAt
renderClock()
end)
FireAllClients delivers to the players who are in the server at that moment. A player who joins during a drill missed the Active message, so the HUD keeps its starting value until the next phase change. The workspace attributes carry the right value, because an attribute is part of the instance and arrives with it, but the HUD never reads them.
A player joins 10 seconds into a 40-second drill. What does their HUD show, and until when?
Press 1 to 4 to choose, Enter to check.
Step 2 of 10
Five channels for one player's state
Here is everything a Beacon Yard client shows about its player, and how each reaches it at m14-ship:
| State | Travels as | Read by |
|---|---|---|
| Coins | leaderstats.Coins IntValue | Hud, ShopApp (each waits for it and subscribes) |
| Shield | ShieldCharges attribute on the Player | the shop and damage code |
| Speed Pass | SpeedPass attribute on the Player | ShopApp |
| Settings | ReducedMotion, LargeText attributes on the Player | Accessibility, SettingsGui |
| Round | RoundState remote, plus workspace attributes | Hud (remote only) |
Each channel has its own rules. An attribute holds one simple value (a string, number, boolean, Vector3, Color3 and a few more), never a table1, and a late joiner gets its current value. A RemoteEvent carries tables but only reaches who is there. And between channels there is no order: if the server changes an attribute and then fires a remote, the client may see either one first. Two changes of the same kind, such as two attribute changes, generally arrive in order2.
ShopService sets ShieldCharges to 1 and then fires Feedback("buy", "Shield") to the same player. On the client, a toast handler reads ShieldCharges when the Feedback message arrives. What can it see?
Press 1 to 4 to choose, Enter to check.
Step 3 of 10
One state, owned by the server
The design studios use has three parts:
- The server owns one state table per player:
{ coins, round, settings, items }. Only server code changes it, through one module,PlayerState. - Changes travel as numbered diffs on one RemoteEvent: only the fields that changed, each message with a sequence number one higher than the last.
- A player who joins gets a snapshot first: the whole table and its current number. Diffs after that continue from it.
| In the picture | In Roblox |
|---|---|
| The official scorer, the only one who writes in the book | PlayerState on the server, the only code that changes a player's state |
| The radio reading out "play 41: home team scores" | A diff with seq 41 and only the fields that changed |
| A late fan reading the scoreboard before following the radio | The snapshot a player gets on join, with its seq |
| Hearing play 43 right after 41 and checking the board again | The store answering gap and asking for a fresh snapshot |
Think of a stadium. The official scorer keeps the scorebook, and only the scorer writes in it. The radio reads out each change with a play number: "Play 41: home team scores." A fan who arrives in the third quarter first looks at the scoreboard for the whole picture, then follows the radio from the next play. If they hear play 43 right after 41, they know they missed one and look at the board again.
Think of it as A stadium's official scorebook, a radio that reads out each numbered play, and a late fan who checks the scoreboard first
Should the client be allowed to change its store and send the change back, for example when the player toggles Large text?
Press 1 to 4 to choose, Enter to check.
Step 4 of 10
Send only what changed
A coin pickup changes one number. Sending the whole state each time wastes bandwidth and makes every listener re-check everything. A diff compares the old and new tables and lists the changes, going inside nested tables so a setting change names its full path:
The real version returns ops as tables, { path = "coins", value = 105 } and { path = "items.Speed", remove = true }, in an array. At m15-scale the module is src/shared/StateDiff.luau, and PlayerState requires it as State. StateDiff.diff replaces a changed array as one value and descends into dictionaries, and StateDiff.copy makes deep copies. The op shape works on the wire because RemoteEvents turn non-string keys into strings, drop functions and metatables, and lose data in mixed tables or arrays with nil holes3.
Why not send changes as one dictionary keyed by path, such as { coins = 105, ["items.Speed"] = nil }?
Press 1 to 4 to choose, Enter to check.
Step 5 of 10
Numbered diffs and the late joiner
RemoteEvents are reliable and ordered, even across different RemoteEvent instances, on one connection in one direction3. So why number the diffs? Because the client can still get them out of step with its base. The snapshot a late joiner asks for and the diffs fired around the same moment can cross, and when nothing is connected yet, the engine queues messages only up to a limit before dropping them. A number turns those cases from silent corruption into something the client can detect.
The client store follows three rules: a snapshot newer than what it has replaces everything; a diff numbered exactly one more than the last applies; anything older is stale and ignored; anything that skips a number, or arrives before the first snapshot, is a gap and changes nothing. Run it:
Server sideRemember: Server-owned state replicated as numbered diffs is a stadium's official scorebook, a radio that reads out each numbered play, and a late fan who checks the scoreboard first.
The store just answered gap for diff 10 (it is at 8). What should the client do?
Press 1 to 4 to choose, Enter to check.
Step 6 of 10
One store for every screen
On the client, one Store module holds the copy, answers get("coins"), and lets screens subscribe("coins", fn). A subscriber hears only the key it asked for, so toggling Large text does not redraw the coin label.
Today ShopApp has four effects that subscribe to the outside world. With a store, a small useStore(key) hook replaces the ones that read state:
-- Coins live in leaderstats, which may arrive after the shop does.
React.useEffect(function()
local connection: RBXScriptConnection? = nil
local cancelled = false
task.spawn(function()
local stats = player:WaitForChild("leaderstats", 15)
local value = if stats then stats:WaitForChild("Coins", 15) else nil
if cancelled or value == nil or not value:IsA("IntValue") then
return
end
setCoins(value.Value)
connection = value:GetPropertyChangedSignal("Value"):Connect(function()
setCoins(value.Value)
end)
end)
return function()
cancelled = true
if connection then
connection:Disconnect()
end
end
end, {})
Not everything belongs in the store. ShopOpen says "open the shop now" and Feedback says "play the coin sound now": they are events, moments that matter once. Coins and the round phase are state: they have a current value a late joiner needs. Events stay on their remotes; state moves into the store. And leaderstats stays too, because Roblox's built-in player list reads it.
Which of these should move into the client store as state? Pick every one.
Press 1 to 5 to choose, Enter to check.
Step 7 of 10
What it costs on the wire
Each diff is one RemoteEvent message to one player. Changes that happen in the same frame should go together: collect them and send one diff per player per frame at most. When a drill ends, for example, the survival bonus and the phase change land in the same moment.
Attributes are not free either: every change replicates on its own, and a value that changes every frame (a timer, a position) costs bandwidth for every player who can see the instance. That is why the round sends endsAt once and each client computes the countdown from workspace:GetServerTimeNow(), instead of a seconds-left value ticking down. The network budget: measure, batch, pack measures these costs per system.
A drill ends. In the same frame the server adds the 10-coin survival bonus to a player and the round moves to Cooldown with a new endsAt. With per-frame batching, how many ops are in that player's one diff?
Ways to replicate state
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Attributes and values | SetAttribute or IntValues on the Player and workspace, as Beacon Yard does today. | A handful of simple values, no tables. | One channel per value, no tables, no order with remotes; late joiners do get current values. |
| Hand-rolled PlayerState | A diff, a numbered remote and a client store, about 200 lines, like this lesson's challenge. | You want to read every line and control the wire format. | You own the edge cases and the tests. |
| Charm with charm-sync | Reactive signals and atoms; charm-sync sends delta-compressed patches of the signals you choose to each client on an interval. MIT, actively maintained (v0.11.1, October 2026). | Teams that want reactive state on both sides with little code. | A new mental model; mind its remote-argument caveats. |
| Replica | Server-created replicas that chosen players subscribe to, with change listeners on the client. Apache-2.0, maintained quietly (last change August 2025). | Per-player or per-group state with fine control over who sees what. | Its own API to learn; slower release cadence. |
| Reflex | Producers and actions, Rodux-style, usable on server and client. MIT, maintained (last change December 2025). | roblox-ts teams that like actions and selectors. | TypeScript-first documentation; you add the syncing layer. |
A teammate proposes putting the whole player state in one attribute as a JSON string. What is the main problem?
Press 1 to 4 to choose, Enter to check.
Step 8 of 10
Build along: PlayerState and the client store
You build this in your own copy of the finished game. First pass the level 3 challenge below, then copy challenges/work/player_state.luau to src/shared/StateDiff.luau.

Select a numbered pin, or a row below, to read what it marks.
A client that joined mid-drill (right) shows the same Active countdown as one that was there from the start (left).
src/shared/StateDiff.luausrc/shared/Types.luausrc/server/PlayerState.luausrc/server/DataService.luausrc/server/Remotes.luausrc/server/RemoteGuard.luausrc/client/Store.luausrc/client/Hud.luausrc/client/ShopApp.luausrc/client/SettingsGui.luausrc/client/init.client.luau
Register
StateandStateSync. UseStateDiff.diffin thePlayerStateflush, with the last-sent copy and the current table. Leave a player out of that flush untilsendSnapshothas established a baseline. Clean the per-player tables throughPlayerScopes.You should see Each dirty player with a snapshot can receive at most one diff per Heartbeat.
Send the snapshot after the profile loads and on a permitted, argument-free
StateSyncrequest.DataServicewrites coins and speed ownership directly.PlayerStatemirrors settings, shield, pass and round attributes, and keeps the existingleaderstatsfor the player list.You should see The snapshot includes coins, speedOwned, speedPass, shieldCharges, settings, round and zone.
Start
Storeon the client. Have it requestStateSyncat startup and on a sequence gap. Exposegetandsubscribeplusread,watch,viewandsubscribeMany. Change the HUD, shop and settings to read the store.RoundStatestill fires. The HUD readsState, andShopOpenandFeedbackstay on their own remotes.You should see The HUD watches round and coins. The shop watches coins and speedPass.
Start a Server & Clients test with one client and start a drill. While it is active, add a second client and compare the phase and countdown.
You should see A second client joining mid-drill should show Active and the same countdown.
Step 9 of 10
Where the scorebook picture breaks
In a stadium everyone hears one broadcast in one order. Why does Beacon Yard still need to move every piece of player state onto the one State remote, instead of numbering only the RoundState messages?
Press 1 to 4 to choose, Enter to check.
Where does it break?“A stadium's official scorebook, a radio that reads out each numbered play, and a late fan who checks the scoreboard first” is a good picture of server-owned state replicated as numbered diffs. Where does it stop being true?
It breaks here. A stadium has one broadcast in one order; a Roblox client hears attribute changes, property changes and several remotes with no order between them, so the play numbers only mean something when all related state travels on one channel. And a fan's notes are harmless, while a client's copy can be edited by an exploiter, so the server never reads it back.
The true model. The server owns one state table per player and changes it only in server code; changes leave as numbered diffs on one RemoteEvent, a snapshot starts each client, and the client store applies only the next number, ignores stale ones and resyncs on a gap. Events that matter once stay on their own remotes.
There is a second break. A fan's notes are harmless; nobody acts on them. The client's store is a copy an exploiter can edit at will, which is fine only because the server never trusts it: purchases, damage and rewards all check PlayerState on the server.
Step 10 of 10
Challenges and recap
This apply treats every path as one flat key and ignores remove ops. Fix it so nested paths reach inside tables and a remove op deletes the key.
Level 1, Apprentice
Challenge
Fix apply in the apply-fix cell.
- 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
- string.split(op.path, ".") walks into nested tables
- A remove op sets the last key to nil; any other op sets the value
- All four assertions in apply-fix pass
Put a mid-drill join in order once the build-along is done.
- The player joins and DataService loads their profile
- The client store applies the snapshot and the HUD shows the countdown
- PlayerState sends a snapshot with round.phase = Active and its seq
- A coin pickup sends a diff numbered one higher, which the store applies
- The drill ends and the next diff moves round.phase to Cooldown
Level 2, Builder
Challenge
Prove the late-joiner bug is gone and the store recovers from a gap. There is no Luau test for this one: the proof is the two-client test and the recovery in the Output.
- Start from
- The game at milestone m14 (download)
Done means
- The build-along is done in your copy: PlayerState, the State and StateSync remotes, and the client Store
- In a Server & Clients test, a client added during an Active drill shows Active and the right countdown within a second
- Forcing a gap (skip one seq on the server for a test) makes the client fire StateSync and recover
- Hud and ShopApp no longer read leaderstats or the RoundState remote
Meet the criteria above, then record your own result. No test grades this check.
Level 3, Professional
Challenge
Write diff, apply and newStore in challenges/work/player_state.luau. The written solution is challenges/solutions/state-and-replication.md. In Play, run game.ServerScriptService.RunGameTests:Invoke("state-and-replication", "state-diff-store") and paste the pass code here.
- Start from
- The game at milestone m14 (download)
- Grade it
- In Studio, press Play, then run
game.ServerScriptService.RunGameTests:Invoke("state-and-replication", "state-diff-store")in the server command bar. Copy the pass code from Output.
Done means
- diff sends only changes, with dotted paths, remove ops without a value, copied values and sorted output
- apply(old, diff(old, new)) equals new, including tables replaced by numbers and the other way round
- The store applies a newer snapshot, then only the next seq; older is stale, a skipped seq or a diff before any snapshot is a gap, and neither changes anything
- subscribe calls a listener only when its key changed and stops after unsubscribing
- challenges/state-and-replication.luau prints TEST PASS for every check
Retiring the analogy
You no longer need “a stadium's official scorebook, a radio that reads out each numbered play, and a late fan who checks the scoreboard first”. The server owns one state table per player and changes it only in server code; changes leave as numbered diffs on one RemoteEvent, a snapshot starts each client, and the client store applies only the next number, ignores stale ones and resyncs on a gap. Events that matter once stay on their own remotes.
Recap
- At m14-ship the HUD learns the round only from FireAllClients, so a player who joins mid-drill sees Idle until Cooldown.
- Player state travels five ways today; attributes reach late joiners but hold no tables, remotes carry tables but only reach who is there, and there is no order between channels.
- One server-owned state per player, changed only by server code; clients send requests, never writes.
- Send numbered diffs on one remote and a snapshot on join; the client store ignores stale diffs and resyncs on a gap.
- One client store feeds every screen; events such as ShopOpen and Feedback stay events. Batch diffs per frame.
- Charm with charm-sync, Replica and Reflex package the same ideas; pick by team language and how much you want to own.
Server-owned state replicated as numbered diffs is a stadium's official scorebook, a radio that reads out each numbered play, and a late fan who checks the scoreboard first, until a stadium has one broadcast in one order; a Roblox client hears attribute changes, property changes and several remotes with no order between them, so the play numbers only mean something when all related state travels on one channel. And a fan's notes are harmless, while a client's copy can be edited by an exploiter, so the server never reads it back.
Queued for review
- A player joins 10 seconds into a 40-second drill. What does their HUD show, and until when?
- ShopService sets ShieldCharges to 1 and then fires Feedback("buy", "Shield") to the same player. On the client, a toast handler reads ShieldCharges when the Feedback message arrives. What can it see?
- Why not send changes as one dictionary keyed by path, such as { coins = 105, ["items.Speed"] = nil }?
- The store just answered gap for diff 10 (it is at 8). What should the client do?
- Which of these should move into the client store as state? Pick every one.