A 50-player server: budgets, Parallel Luau and native code

Run Beacon Yard with 50 simulated players and 40 crawlers. Set a per-system millisecond budget, profile the server, move crawler sensing onto Actors with results that match serial, and add --!native only where the Script Profiler shows a gain.

Lab lesson, about 75 minutes, 8 steps

By the end you can

  • Give every server system a millisecond budget and judge it by its 95th percentile
  • Load a test server with simulated players and crawlers, and say what that load cannot show
  • Profile the server with the Script Profiler, server MicroProfiler dumps and custom labels
  • Move crawler sensing to Actors with serial writes, prove it matches the serial result, and use --!native only where it measurably helps

Before this: Big worlds: streaming, LOD and interest management, Parallel Luau: Actors and multithreading

1Fifty players, forty crawlers

Each crawler at m14-ship runs its own loop, ten times a second:

	task.spawn(function()
		while crawler.alive and model.Parent ~= nil do
			tick(crawler)
			task.wait(Config.CRAWLER_TICK_SECONDS)
Figure 1.1

Every tick calls findTarget, which walks every player and measures a distance. With one player that is nothing. With fifty players and forty crawlers, it is a real amount of work, and sensing is only the start: a chasing crawler also computes paths and moves.

The server's frame has a hard edge. Server heartbeat is capped at 60 frames per second, so one frame has 16.67 ms. You can watch it in the Developer Console: in Server Jobs, expand Heartbeat and read Steps Per Sec. When the server cannot finish its work in time, heartbeat drops and ping rises, because network data waits for the frame to end1.

40 crawlers each tick every Config.CRAWLER_TICK_SECONDS = 0.1 s, and each tick measures the distance to every one of 50 players. How many distance checks does the server do per second?

Answer

20000 checks per second. 40 x 10 x 50 = 20,000 a second. Distances are cheap; a line-of-sight raycast per check is not, which is when sensing becomes worth moving.

During a full drill, Server Jobs shows Heartbeat at about 45 Steps Per Sec. What does that tell you?

  1. Frames take longer than 16.67 ms on average, so the server simulates and answers players late
  2. The server is idle and saving CPU
  3. Players' devices are running at 45 FPS
  4. Nothing; 45 is the normal cap for servers
Answer

Frames take longer than 16.67 ms on average, so the server simulates and answers players late. 1,000 / 45 is about 22 ms per step. Find which system takes the extra 5 ms before changing anything.

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

2A millisecond budget per system

A frame budget is a table like the network budget: one row per system, a number of milliseconds per frame, and the measurement next to it. Leave headroom: the engine's own work (physics, replication, Humanoids) shares the same 16.67 ms. And judge each system by a high percentilePercentile (p50, p95)The value below which a given share of samples fall: p95 is the time 95 of every 100 frames beat.Think of it as judging a bus line by how late it is on its worst days, not on an average day., not its average. A system that takes 1 ms on most frames and 9 ms on a few has a fine average and still makes players feel a hitch.

Both sidesRemember: Parallel Luau Actors is separate workbenches where jobs can run at the same time.

The workshop has a closing time every 16.67 ms. A budget is how much of that time each job may take, measured on the busiest days.

Twenty CrawlerService frame times in ms. What does this print?

local ms = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 9 }
local total = 0
for _, v in ms do total += v end
local sorted = table.clone(ms)
table.sort(sorted)
print(total / #ms, sorted[math.ceil(0.95 * #ms)])
  1. 1.65 6
  2. 1.65 9
  3. 1 6
  4. 6 1.65
Answer

1.65 6. The average says 1.65 ms and looks fine against a 3 ms budget. The p95 says 6 ms and is twice over. Budgets use the percentile.

Write the percentile. The game repo's check uses the same nearest-rank rule.

Luau
local function percentile(samples: { number }, p: number): number
	-- Nearest rank: sort a copy, take rank ceil(p / 100 * n), clamped to 1..n.
	-- 0 for no samples. Do not reorder the caller's table.
	local total = 0
	for _, s in samples do
		total += s
	end
	return if #samples > 0 then total / #samples else 0
end
 
local ms = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 9 }
print(percentile(ms, 50), percentile(ms, 95))
Figure 2.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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

3Make the load

Studio's Server & Clients test runs up to eight clients, and StudioTestService can start a server with up to eight simulated clients from a script2. Neither gives you fifty. So the load has two parts.

On the server, a load harness stands in for the rest: forty crawlers from CrawlerService.spawnForTest (it already exists for tests, and chases a fixed point set in a TestTarget attribute), plus about fifty bot characters that walk set routes and count as targets. For network and client numbers, you still need real clients: eight in Studio, then a private playtest with real people before launch.

Fifty server-side bot characters walk around the yard during a load test. What can this NOT tell you?

  1. How much each real player's device receives per second and how it renders
  2. How long CrawlerService takes per frame with fifty targets
  3. Whether server heartbeat stays near 60 during a drill
  4. Which server system is the biggest line in the Script Profiler
Answer

How much each real player's device receives per second and how it renders. Server-side load answers server questions. Network and client questions need real clients, so a load plan uses both.

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

4Measure the server

Three tools look at the server, all from the Developer Console (Ctrl+F9) on a server you can edit:

  • The Script Profiler records CPU time per function. Choose Server before you start, and 1 kHz or the more precise and more costly 10 kHz3.
  • The MicroProfiler page has a Server tab: capture up to 60 frames, after a delay of up to 4 seconds, into a dump file4.
  • Your own labels: wrap a block in debug.profilebegin("CrawlerSense") and debug.profileend(), and it appears by name in the MicroProfiler timeline.
Roblox Studio
The Developer Console's Script Profiler in Server mode after a 10-second recording during a load test, with CrawlerService functions at the top of the callgraph.
Figure 4.1.

The Script Profiler in Server mode during the load test: the top lines are where the milliseconds go.

Match each question to the tool that answers it.

  1. Which server function used the most CPU over 10 seconds?
  2. What exactly ran during the slow server frame at 12:01?
  3. How long does crawler sensing take inside each frame?
  4. Is the server keeping up right now?
Answer

Which server function used the most CPU over 10 seconds?: Script Profiler, Server; What exactly ran during the slow server frame at 12:01?: MicroProfiler Server tab dump; How long does crawler sensing take inside each frame?: debug.profilebegin and profileend labels; Is the server keeping up right now?: Server Jobs, Heartbeat, Steps Per Sec. The Script Profiler sums CPU per function, a MicroProfiler dump shows individual frames, labels name your own blocks in that timeline, and Heartbeat steps tell you live whether the server keeps up.

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

5Crawler sensing on Actors

Suppose the profiler shows crawler sensing at the top: each crawler finds the nearest living player. That work only reads the world, so it can run in parallel.

Be honest about how much work that is in Beacon Yard. At m15-scale a crawler senses by distance alone, with no line-of-sight ray, and that is deliberate: crawlers path around walls and scrap stacks anyway, so a ray would add cost without changing where they go. Distance checks are cheap, so this is exactly the case where parallel can lose (the parallel-slower question below). docs/perf-budget.md still says "Not measured yet". The tag ships the Actors so you can measure both paths; keep them in your game only if your measurement wins. A game whose enemies must see their target, through a raycast that is Safe to call in parallel, has far more reason to parallelise. Changing the world (moving a crawler, computing a path, setting an attribute) stays serial. The Parallel Luau: Actors and multithreading lesson has the rules: scripts under different Actors can run at the same time, task.desynchronize enters the parallel phase, task.synchronize leaves it, and an API with no thread-safety tag is Unsafe5.

local actor = script:GetActor()
if actor == nil then
	return
end
 
actor:BindToMessageParallel(
	"Sense",
	function(crawlers: { FrameBudget.Crawler }, players: { FrameBudget.Player }, targets: SharedTable)
		debug.profilebegin("CrawlerSense")
		for _, crawler in crawlers do
			local target = FrameBudget.sense(crawler.position, players)
			targets[crawler.id] = target or 0 -- 0 means nobody
		end
		debug.profileend()
	end
)
 
-- The scheduler sends only to Actors that are bound, so it sets this last.
actor:SetAttribute("Ready", true)
Figure 5.1

The scheduler takes a snapshot ten times a second, sends each ready Actor its batch, and reads targets on the next tick. If a crawler has no usable result, it can sense in serial. The busy flag keeps a second step from starting while path computation yields. A SharedTable is not copied when sent to another Actor, and its updates are visible to all of them5. The cost is one tick of delay: a crawler acts on what it sensed 0.1 s ago.

Serial, parallel, serialA copper serial box snapshots players and sends batches to a shared parallel box of eight Actors, which returns targets to a copper serial box that moves the crawlers.batchestargetsSnapshotserial, 10 Hz8 Actorssense in parallelActserial: path, move
Figure 5.2. Read in parallel, write in serial, with one tick between sensing and acting.

Which crawler operations may run in the parallel phase?

  1. Measuring the ground-plan distance to each player in a snapshot table
  2. workspace:Raycast for line of sight to the chosen target
  3. PathfindingService path:ComputeAsync to the target
  4. humanoid:MoveTo toward the next waypoint
  5. Setting the crawler's Health attribute after a bite
Answer

Measuring the ground-plan distance to each player in a snapshot table; workspace:Raycast for line of sight to the chosen target. Plain maths on your own tables and WorldRoot:Raycast (Thread Safety: Safe) can run in parallel. ComputeAsync is Unsafe, and MoveTo and attribute writes change the world, so they wait for the serial phase.

There is one trap. Different Actors may see the players in a different order. If two players are exactly as near, "keep the first one found" picks a different player in parallel than in serial, and the crawlers chase someone else for no reason anyone can reproduce.

Players 1 and 2 are both 10 studs from the crawler. What does this print?

local function nearest(list)
	local best, bestD = nil, math.huge
	for _, p in list do
		if p.d < bestD then best, bestD = p.id, p.d end
	end
	return best
end
local a = { { id = 1, d = 10 }, { id = 2, d = 10 } }
local b = { { id = 2, d = 10 }, { id = 1, d = 10 } }
print(nearest(a), nearest(b))
  1. 1 2
  2. 1 1
  3. 2 2
  4. 2 1
Answer

1 2. Order-dependent answers break the promise that parallel equals serial. Add a tie-break: on equal distance, the lower id wins.

With the tie-break, the answer no longer depends on the order:

Luau
local function nearest(list)
	local best, bestD = nil, math.huge
	for _, p in list do
		if p.d < bestD or (p.d == bestD and p.id < best) then
			best, bestD = p.id, p.d
		end
	end
	return best
end
 
local a = { { id = 1, d = 10 }, { id = 2, d = 10 } }
local b = { { id = 2, d = 10 }, { id = 1, d = 10 } }
print(nearest(a), nearest(b))
Figure 5.3. Run it in the lesson view or in the Studio command bar.

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

6Native code, where it helps

--!native at the top of a script compiles its functions to machine code instead of bytecode. It works for server scripts (and for client scripts only on Android), behaves exactly the same, and helps most in scripts that do a lot of maths on tables and buffers, called many times. It also costs something: compile time at server start, extra memory, and a limit on the total amount of native code in a game. The docs say to measure each function with and without it in the Script Profiler, which marks natively running functions, and to annotate Vector3 parameters so the compiler can specialise6.

Which Beacon Yard module is the best first candidate for --!native?

  1. DronePacket: bit packing with buffer.writebits for every drone, ten times a second, on the server
  2. RoundService: a phase change every few seconds
  3. ShopService: a purchase a few times per session
  4. The client's SettingsGui, so menus open faster on iPhone
Answer

DronePacket: bit packing with buffer.writebits for every drone, ten times a second, on the server. Start with the hottest pure-maths module, measure before and after in the Script Profiler, and keep it only if the number moves.

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

7Build it: load, measure, parallelise

Build along

m14-ship to m15-scale

  • src/server/LoadHarness.luau
  • src/server/TestHooks.luau
  • src/server/CrawlerService.luau
  • src/shared/FrameBudget.luau
  • src/server/SenseWorker.server.luau
  • src/shared/Config.luau
  • docs/perf-budget.md
  1. From the server command bar, run game.ServerScriptService.RunLoadTest:Invoke(50, 40, 20). TestHooks installs this bindable in the test build. The harness sets LoadTest, builds R15 bots with CreateHumanoidModelFromDescriptionAsync (requires network access), and unpins the targets of the test crawlers so they sense the bots.

    You should see The test place runs 50 bots and 40 crawlers for 20 seconds, then prints a report and cleans up.

  2. Have CrawlerService create the Actors and clone SenseWorker under each. Send batches only to ready workers. Read the shared results the next tick, use serial sensing when needed, and guard each crawler with busy while a step can yield.

    You should see ServerScriptService.SenseActors contains eight Actors. Each worker sets Ready after binding Sense.

  3. Use Config.FRAME_BUDGETS_MS and FrameBudget.report. On every Heartbeat, record Frame from FrameBudget.frameSample(Stats.HeartbeatTime, dt): the server's own task scheduler time for that frame7, in milliseconds. Record the Heartbeat dt too, as FrameInterval, and pass { FrameInterval = true } as the third argument of report so that line has no budget and is never over. If the stat cannot be read, frameSample falls back to dt and the Frame line says "(interval, not server work)". Follow docs/perf-budget.md to record the server Script Profiler and MicroProfiler. The tagged table leaves the measurement columns blank. Fill them with your Studio results.

    You should see The report shows p50 and p95 against the configured budgets, with Frame judged against 16.70 ms and a FrameInterval line marked info with no budget.

To compare serial and parallel sensing, add a temporary comparison to a local copy and give both paths the same snapshot. The milestone has a serial fallback and no comparison flag. If you try --!native on DronePacket, record both versions with the same load. The tagged module uses ordinary Luau.

The Frame line needs care. The time between two Heartbeats is about 16.7 ms on an idle server too, because the server is capped at 60 steps a second, so the interval measures pacing, not your code. Frame is the work the server did inside the frame, and that is what the 16.70 ms budget judges. The interval is printed beside it as FrameInterval, for information only.

An idle test server prints FrameInterval p95 16.7 ms and Frame p95 2.1 ms. Which line tells you whether the server's code fits its budget?

  1. Frame: it is Stats.HeartbeatTime, the server's own work per frame, judged against 16.70 ms
  2. FrameInterval: it is the real length of a frame, so it is the one to keep under 16.70 ms
  3. Neither: frame budgets can only be read in the MicroProfiler
  4. Both must be under 16.70 ms, so this server is already over on FrameInterval
Answer

Frame: it is Stats.HeartbeatTime, the server's own work per frame, judged against 16.70 ms. Judge the work, not the wait. The interval only grows past 16.7 ms once the work no longer fits, so by then Frame has already told you.

A teammate adds --!native to every server script 'in case it helps'. What is the strongest reason not to?

  1. Native code costs compile time at server start, extra memory and part of a game-wide limit, and most scripts gain nothing
  2. Native scripts behave differently, so tests stop being valid
  3. Native code does not run on servers
  4. It disables the Script Profiler
Answer

Native code costs compile time at server start, extra memory and part of a game-wide limit, and most scripts gain nothing. Treat --!native like any optimisation: find the hot function, measure with and without, and keep it where the number moves.

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

8Challenges and recap

Other ways pros do this

OptionWhat it isWhen pros pick itTrade-offs
Do less workLower the tick rate, put crawlers far from every player to sleep, sense only every few ticks.First, always: the cheapest frame is the one with less to do.Can make crawlers react a little later; tune and playtest.
Parallel LuauRead-only work on Actors, writes in the serial phase.Large batches of independent, read-heavy work such as sensing with raycasts.Message and scheduling overhead; small batches can be slower than serial.
--!native or @nativeMachine code for hot Luau functions.Maths-heavy functions on tables and buffers, called often, on the server.Compile time, memory and a game-wide limit.
Extended Services for ComputeReserve more server CPU from Roblox.Heartbeat stays low after you have optimised.Costs money and hides problems if used first.
Where does it break?“Separate workbenches where jobs can run at the same time” is a good picture of parallel luau actors. Where does it stop being true?

It breaks here. Having another bench does not guarantee a dedicated worker or a speedup.

The true model. Roblox schedules Actor work. Code enters the parallel phase explicitly, and each API's thread safety determines what that code can do.

Sensing with distances only (no raycasts) for 40 crawlers moves to 8 Actors, and CrawlerService's p95 goes up. Why is that plausible?

  1. Twenty thousand cheap distance checks a second are tiny next to the cost of messages, scheduling and phase changes; more benches do not guarantee a speed-up
  2. Actors always run slower than scripts outside Actors
  3. Distance maths is not allowed in the parallel phase
  4. The SharedTable copies the data eight times
Answer

Twenty thousand cheap distance checks a second are tiny next to the cost of messages, scheduling and phase changes; more benches do not guarantee a speed-up. That is where the workbench picture breaks: a bench is not a free worker. Measure, and keep the parallel version only when the profiler says it wins, typically once each batch does real work such as raycasts.

Level 1, Apprentice

Challenge

Measure Beacon Yard's server at m14-ship with eight clients and write its first frame budget.

Start from
The game at milestone m14 (download)

Done means

  • A Server and Clients test with eight clients ran a full drill
  • You recorded Heartbeat Steps Per Sec from Server Jobs and a 10-second Script Profiler recording in Server mode
  • You wrote the three most expensive server functions and a budget for each

Hints

  1. Developer Console (Ctrl+F9), then Server Jobs and Script Profiler.
  2. Choose Server in the Script Profiler before pressing Start.

Level 2, Builder

Challenge

Fix percentile in the percentile-cell 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

  • percentile sorts a copy with table.clone
  • It returns the value at rank ceil(p / 100 * n), clamped to 1..n, and 0 for no samples
  • Every test in percentile-cell passes

Hints

  1. local sorted = table.clone(samples) then table.sort(sorted).
  2. math.clamp(math.ceil(p / 100 * n), 1, n) is the rank.
Solution
luau
local function percentile(samples: { number }, p: number): number
	local n = #samples
	if n == 0 then
		return 0
	end
	local sorted = table.clone(samples)
	table.sort(sorted)
	return sorted[math.clamp(math.ceil(p / 100 * n), 1, n)]
end
 
local ms = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 9 }
print(percentile(ms, 50), percentile(ms, 95))

Your report shows CrawlerService at p95 6 ms against a 3 ms budget, and CombatService with no budget line. What should the release gate do?

  1. Fail on both: CrawlerService is over, and a system without a budget counts as over until someone sets one
  2. Pass, because the average is under budget
  3. Fail only on CombatService, because CrawlerService is close
  4. Pass, because budgets only matter after launch
Answer

Fail on both: CrawlerService is over, and a system without a budget counts as over until someone sets one. A budget nobody enforces is a wish. Every system gets a line, and the gate reads p95.

Level 3, Professional

Challenge

Write the budget and sensing rules in the game repo's challenges/work/frame_budget.luau, then run the server-at-scale 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-at-scale") in the server command bar. Copy the pass code from Output.

Done means

  • challenges/work/frame_budget.luau computes nearest-rank percentiles and a report sorted by p95, with missing budgets counted as over
  • sense uses ground-plan distance, skips dead players and breaks ties on the lower id
  • splitBatches makes contiguous, fair batches with no empty ones
  • The server-at-scale challenge prints TEST PASS for all nineteen checks, including parallel_matches

Hints

  1. Sort the report with table.sort and a comparison on p95, slowest first.
  2. On equal distance, keep the player with the lower id.
  3. Use min(count, actors) batches; the first count % batches get one extra.

Retiring the analogy

You no longer need “separate workbenches where jobs can run at the same time”. Roblox schedules Actor work. Code enters the parallel phase explicitly, and each API's thread safety determines what that code can do.

Recap

  1. Server heartbeat is capped at 60, so a frame has 16.67 ms; Server Jobs Heartbeat Steps Per Sec shows whether the server keeps up, and ping rises when it does not.
  2. Give every system a millisecond budget and judge it at p95; a system without a budget counts as over.
  3. Server-side bots and test crawlers load the server; network and device questions still need real clients, up to eight in Studio and then a private playtest.
  4. Profile with the Script Profiler in Server mode, MicroProfiler Server dumps and debug.profilebegin labels.
  5. Parallelise read-only work on Actors with serial writes and a deterministic tie-break, keep --!native where the profiler shows a gain, and do less work first.

Parallel Luau Actors is separate workbenches where jobs can run at the same time, until having another bench does not guarantee a dedicated worker or a speedup.

Next Security at scale: one validation layer, shared bans, device trust

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