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.

Lab lesson, about 75 minutes, 10 steps

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

1Join 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)
Figure 1.1

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)
Figure 1.2

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?

  1. Idle with the start-the-drill hint, until Cooldown begins about 30 seconds later
  2. Active with the right countdown, because RemoteEvents queue messages for new players
  3. Nothing at all until they respawn
  4. Active, because the HUD reads the RoundPhase attribute on join
Answer

Idle with the start-the-drill hint, until Cooldown begins about 30 seconds later. Messages are moments; late joiners need state. Every piece of state needs a way to reach someone who was not there when it changed.

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

2Five 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:

StateTravels asRead by
Coinsleaderstats.Coins IntValueHud, ShopApp (each waits for it and subscribes)
ShieldShieldCharges attribute on the Playerthe shop and damage code
Speed PassSpeedPass attribute on the PlayerShopApp
SettingsReducedMotion, LargeText attributes on the PlayerAccessibility, SettingsGui
RoundRoundState remote, plus workspace attributesHud (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?

  1. Either 1 or the old value: an attribute change and a RemoteEvent have no guaranteed order between them
  2. Always 1, because the attribute was set first
  3. Always the old value, because remotes are faster
  4. An error, because attributes cannot be read in a remote handler
Answer

Either 1 or the old value: an attribute change and a RemoteEvent have no guaranteed order between them. Mixing channels for related state invites races. One channel for all of a player's state removes the question.

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

3One state, owned by the server

The design studios use has three parts:

  1. The server owns one state table per player: { coins, round, settings, items }. Only server code changes it, through one module, PlayerState.
  2. Changes travel as numbered diffs on one RemoteEvent: only the fields that changed, each message with a sequence number one higher than the last.
  3. A player who joins gets a snapshot first: the whole table and its current number. Diffs after that continue from it.
Server sideServer-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.
In the pictureIn Roblox
The official scorer, the only one who writes in the bookPlayerState 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 radioThe snapshot a player gets on join, with its seq
Hearing play 43 right after 41 and checking the board againThe store answering gap and asking for a fresh snapshot

See the whole analogy cast

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

One state, one channel, one storeA copper box labelled PlayerState on the server sends an arrow labelled seq diffs down to a cyan box labelled Store on the client. The store has arrows down to three cyan boxes: Hud, ShopApp and SettingsGui.seq diffsPlayerStateserver owns itStoreclient copyHudShopAppSettingsGui
Figure 3.1. The server writes; the client store copies; every screen reads the store.

Should the client be allowed to change its store and send the change back, for example when the player toggles Large text?

  1. No: the client sends a request (SetSetting, as today), the server checks it and changes PlayerState, and the diff comes back like any other
  2. Yes, for settings only, since they are harmless
  3. Yes, as long as the client also sends the sequence number
  4. No, because RemoteEvents only go from server to client
Answer

No: the client sends a request (SetSetting, as today), the server checks it and changes PlayerState, and the diff comes back like any other. The client store is a read-only copy. Every change starts as a request the server can refuse.

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

4Send 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:

Luau
local function diff(old, new, prefix, ops)
	prefix = prefix or ""
	ops = ops or {}
	for key, value in new do
		local path = prefix .. key
		if type(old[key]) == "table" and type(value) == "table" then
			diff(old[key], value, path .. ".", ops)
		elseif old[key] ~= value then
			table.insert(ops, path .. "=" .. tostring(value))
		end
	end
	for key in old do
		if new[key] == nil then
			table.insert(ops, "-" .. prefix .. key)
		end
	end
	table.sort(ops)
	return ops
end
 
local before = { coins = 100, settings = { LargeText = false, ReducedMotion = false }, items = { Speed = true } }
local after = { coins = 105, settings = { LargeText = true, ReducedMotion = false }, items = {} }
print(table.concat(diff(before, after), " "))
Figure 4.1. Expected output: -items.Speed coins=105 settings.LargeText=true

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 }?

  1. Setting a key to nil removes it from the table, so the removal of items.Speed would never be sent
  2. Dictionaries cannot be sent through RemoteEvents
  3. Keys with dots are not allowed in Luau tables
  4. It would be too many bytes
Answer

Setting a key to nil removes it from the table, so the removal of items.Speed would never be sent. Design the message so every change is something that exists in it. A remove op is data; a nil is an absence.

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

5Numbered 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:

Luau
local state, seq = nil, 0
 
local function receive(message)
	if message.kind == "snapshot" then
		if state ~= nil and message.seq <= seq then
			return "stale"
		end
		state, seq = table.clone(message.state), message.seq
		return "applied"
	end
	if state == nil or message.seq > seq + 1 then
		return "gap"
	end
	if message.seq <= seq then
		return "stale"
	end
	for key, value in message.set do
		state[key] = value
	end
	seq = message.seq
	return "applied"
end
 
local results = {
	receive({ kind = "diff", seq = 6, set = { coins = 95 } }),
	receive({ kind = "snapshot", seq = 7, state = { coins = 100, phase = "Active" } }),
	receive({ kind = "diff", seq = 7, set = { coins = 1 } }),
	receive({ kind = "diff", seq = 8, set = { coins = 105 } }),
	receive({ kind = "diff", seq = 10, set = { phase = "Cooldown" } }),
}
print(table.concat(results, " "), state.coins, state.phase)
Figure 5.1. Expected output: gap applied stale applied gap 105 Active

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?

  1. Ask the server for a fresh snapshot (a StateSync request) and apply it; diffs keep being checked against the new number
  2. Apply diff 10 anyway; it is probably fine
  3. Wait for diff 9 forever
  4. Kick the player
Answer

Ask the server for a fresh snapshot (a StateSync request) and apply it; diffs keep being checked against the new number. Detect, then resync. Never guess at state you did not receive.

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

6One 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, {})
Figure 6.1

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.

  1. Coins
  2. The round phase and its end time
  3. Owning the Speed Pass
  4. The ShopOpen message
  5. The Feedback toast for a coin pickup
Answer

Coins; The round phase and its end time; Owning the Speed Pass. Coins, round and pass ownership have a value right now, so they are state. ShopOpen and Feedback are events: a late joiner should not see an old toast or have the shop pop open.

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

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

Answer

3 ops. coins, round.phase and round.endsAt: three ops in one message, instead of three channels firing at different moments.

Ways to replicate state

OptionWhat it isWhen pros pick itTrade-offs
Attributes and valuesSetAttribute 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 PlayerStateA 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-syncReactive 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.
ReplicaServer-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.
ReflexProducers 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?

  1. Every change re-sends the whole string, and every listener has to decode and compare it, so you lose the point of diffs
  2. Attributes cannot hold strings
  3. JSON cannot represent numbers
  4. Late joiners would not receive it
Answer

Every change re-sends the whole string, and every listener has to decode and compare it, so you lose the point of diffs. Snapshots on join, diffs after: you only pay for what changed.

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

8Build 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.

Roblox Studio
Two Roblox Studio client windows side by side during a Server and Clients test. Both HUDs show the drill as Active with the same countdown, including the client that joined after the drill started.

Select a numbered pin, or a row below, to read what it marks.

Figure 8.1.

A client that joined mid-drill (right) shows the same Active countdown as one that was there from the start (left).

Build along

m14-ship to m15-scale

  • src/shared/StateDiff.luau
  • src/shared/Types.luau
  • src/server/PlayerState.luau
  • src/server/DataService.luau
  • src/server/Remotes.luau
  • src/server/RemoteGuard.luau
  • src/client/Store.luau
  • src/client/Hud.luau
  • src/client/ShopApp.luau
  • src/client/SettingsGui.luau
  • src/client/init.client.luau
  1. Register State and StateSync. Use StateDiff.diff in the PlayerState flush, with the last-sent copy and the current table. Leave a player out of that flush until sendSnapshot has established a baseline. Clean the per-player tables through PlayerScopes.

    You should see Each dirty player with a snapshot can receive at most one diff per Heartbeat.

  2. Send the snapshot after the profile loads and on a permitted, argument-free StateSync request. DataService writes coins and speed ownership directly. PlayerState mirrors settings, shield, pass and round attributes, and keeps the existing leaderstats for the player list.

    You should see The snapshot includes coins, speedOwned, speedPass, shieldCharges, settings, round and zone.

  3. Start Store on the client. Have it request StateSync at startup and on a sequence gap. Expose get and subscribe plus read, watch, view and subscribeMany. Change the HUD, shop and settings to read the store. RoundState still fires. The HUD reads State, and ShopOpen and Feedback stay on their own remotes.

    You should see The HUD watches round and coins. The shop watches coins and speedPass.

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

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

9Where 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?

  1. Play numbers only work within one ordered channel; attribute changes and other remotes have no order relative to it, so state split across channels can still disagree
  2. Numbers cannot be sent through attributes
  3. RoundState is an UnreliableRemoteEvent
  4. Roblox limits a game to one RemoteEvent
Answer

Play numbers only work within one ordered channel; attribute changes and other remotes have no order relative to it, so state split across channels can still disagree. One ordered channel per piece of related state. And unlike a fan's notebook, the client's copy can be edited by an exploiter, so the server never reads it back.

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.

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

10Challenges 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.

Luau
local function apply(state, ops)
	for _, op in ops do
		-- Bug: "settings.LargeText" becomes one flat key, and a remove op
		-- (which has no value) writes nil to a key that does not exist.
		state[op.path] = op.value
	end
	return state
end
 
local state = { coins = 100, settings = { LargeText = false }, items = { Speed = true } }
apply(state, {
	{ path = "coins", value = 105 },
	{ path = "items.Speed", remove = true },
	{ path = "settings.LargeText", value = true },
})
print(state.coins, state.items.Speed, state.settings.LargeText)
Figure 10.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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 in the lesson view; 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

Hints

  1. Walk every part but the last, then set or clear the last part on the table you reached.
  2. Create a table on the way if a part is missing.
Solution
luau
local function apply(state, ops)
	for _, op in ops do
		local parts = string.split(op.path, ".")
		local node = state
		for i = 1, #parts - 1 do
			if type(node[parts[i]]) ~= "table" then
				node[parts[i]] = {}
			end
			node = node[parts[i]]
		end
		if op.remove then
			node[parts[#parts]] = nil
		else
			node[parts[#parts]] = op.value
		end
	end
	return state
end
 
local state = { coins = 100, settings = { LargeText = false }, items = { Speed = true } }
apply(state, {
	{ path = "coins", value = 105 },
	{ path = "items.Speed", remove = true },
	{ path = "settings.LargeText", value = true },
})
print(state.coins, state.items.Speed, state.settings.LargeText)

Put a mid-drill join in order once the build-along is done.

  1. The player joins and DataService loads their profile
  2. The client store applies the snapshot and the HUD shows the countdown
  3. PlayerState sends a snapshot with round.phase = Active and its seq
  4. A coin pickup sends a diff numbered one higher, which the store applies
  5. The drill ends and the next diff moves round.phase to Cooldown
Answer

1. The player joins and DataService loads their profile 2. PlayerState sends a snapshot with round.phase = Active and its seq 3. The client store applies the snapshot and the HUD shows the countdown 4. A coin pickup sends a diff numbered one higher, which the store applies 5. The drill ends and the next diff moves round.phase to Cooldown. The snapshot gives the late joiner the present; numbered diffs keep them current from there.

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

Hints

  1. To force a gap, add 2 to the seq for one diff behind a test flag, then remove the flag.
  2. Print the store's answer for each message while you test.

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

Hints

  1. Recurse only when both sides hold a table at the same key.
  2. Copy tables when you put them in an op, when you apply an op, and when you keep a snapshot.
  3. To know whether a key changed for listeners, diff the old and new value of just that key.

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

  1. At m14-ship the HUD learns the round only from FireAllClients, so a player who joins mid-drill sees Idle until Cooldown.
  2. 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.
  3. One server-owned state per player, changed only by server code; clients send requests, never writes.
  4. Send numbered diffs on one remote and a snapshot on join; the client store ignores stale diffs and resyncs on a gap.
  5. One client store feeds every screen; events such as ShopOpen and Feedback stay events. Batch diffs per frame.
  6. 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.

Next Data-driven content: designers edit data, not code

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