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

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.

Choose one

A player joins 10 seconds into a 40-second drill. What does their HUD show, and until when?

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.

Link to this step · This confused me

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:

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.

Choose one

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?

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.

Link to this step · This confused me

Step 3 of 10

One 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
The server writes; the client store copies; every screen reads the store.
Choose one

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

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.

Link to this step · This confused me

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:

Luau
Ctrl Enter runs the cell. Checked against the expected output

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.

Choose one

Why not send changes as one dictionary keyed by path, such as { coins = 105, ["items.Speed"] = nil }?

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.

Link to this step · This confused me

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:

Luau
Ctrl Enter runs the cell. Checked against the expected output

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.

Choose one

The store just answered gap for diff 10 (it is at 8). What should the client do?

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.

Link to this step · This confused me

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.

Choose all that apply

Which of these should move into the client store as state? Pick every one.

Which of these should move into the client store as state? Pick every one.

Press 1 to 5 to choose, Enter to check.

Link to this step · This confused me

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.

Work it out

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?

ops

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

A teammate proposes putting the whole player state in one attribute as a JSON string. What is the main problem?

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.

Link to this step · This confused me

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.

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.

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.

Link to this step · This confused me

Step 9 of 10

Where the scorebook picture breaks

Choose one

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?

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.

Link to this step · This confused me

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.

Luau
Ctrl Enter runs the cell. Checked by 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; 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 in order

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

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

The Course Runner prints this code when the test passes.

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

Link to this step · This confused me