Parallel Luau: Actors and multithreading

Learn Parallel Luau for Roblox. Put scripts under Actors, desynchronize for independent work, synchronize to touch the world, share data with messages and SharedTable, and judge when Beacon Yard would benefit.

Concept lesson, about 65 minutes, 10 steps

By the end you can

  • Explain why task.spawn does not use more than one CPU core, and what Actors change
  • Split work into a parallel phase (task.desynchronize) and a serial phase (task.synchronize)
  • Check an API's thread safety before calling it in parallel, and pass data with Actor messages or SharedTable
  • Decide when parallelism helps (independent math and raycasts) and when it does not (one drone, ComputeAsync)

Before this: Events, signals and the task library, Performance: MicroProfiler, memory, network

1Eight cores, one busy

Your phone probably has six or eight CPU cores. By default, every Luau script in your game runs on one of them, one script at a time. task.spawn does not change that: it hands a job to a helper, and the helpers take turns on the same core.

Both sidesRemember: task.spawn is hand a job to a helper.

Before pressing Run, predict which string prints first: caller continues or helper starts?

Luau with roblox-lite (not Roblox)
local order = {}
 
task.spawn(function()
	table.insert(order, "helper starts")
	table.insert(order, "helper finishes")
end)
table.insert(order, "caller continues")
 
print(table.concat(order, ", "))
Figure 1.1. Expected output: helper starts, helper finishes, caller continues

The helper ran all the way through before the caller continued. Nothing happened at the same time. If the helper had done 30 ms of maths, the caller and every other script would have waited 30 ms.

You move DroneService's per-frame step into task.spawn, and say it costs 30 ms. What happens to the server frame?

  1. It still costs 30 ms on the same thread; task.spawn does not run code on another core
  2. It now runs on another core and the frame is free
  3. It runs on the client instead of the server
  4. It is split evenly across all cores
Answer

It still costs 30 ms on the same thread; task.spawn does not run code on another core. task.spawn schedules a coroutine on the same Luau thread. It changes when code runs, not where. Parallel execution needs Actors.

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

2Where the helper picture breaks

Where does it break?“Hand a job to a helper” is a good picture of task.spawn. Where does it stop being true?

It breaks here. Helpers take turns rather than working at the same time: a spawned function that never yields blocks the caller and every other script.

The true model. task.spawn creates a coroutine and resumes it right away on the same scheduler. Concurrency is cooperative: work interleaves only at yields such as task.wait.

Parallel Luau is the case where helpers really do work at the same time. To get it, you put scripts under ActorActorAn instance whose descendant scripts can run in parallel with scripts under other Actors.Think of it as a separate workbench: one worker per bench, many benches working at once. instances. An Actor is a unit of isolation: scripts inside one Actor run one after another, and scripts in different Actors can run on different cores at the same moment1.

You put all eight crawler NPC scripts under one Actor and call task.desynchronize in each. How many run at the same time?

  1. One at a time; scripts in the same Actor run serially
  2. Eight, one per core
  3. Two, because the server has two threads
  4. None; desynchronize errors under an Actor
Answer

One at a time; scripts in the same Actor run serially. Scripts in the same Actor always run sequentially with respect to each other. Give each NPC its own Actor to let the engine spread them across cores.

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

3Parallel phase, serial phase

Being under an Actor is not enough. Code still runs serially until it asks to go parallel with task.desynchronize(), and it must come back with task.synchronize() before it changes the world2. A signal can start in parallel directly with ConnectParallel1.

luau
-- A script under an Actor
local RunService = game:GetService("RunService")
 
RunService.Heartbeat:ConnectParallel(function(dt)
	-- PARALLEL: read the world, do maths, cast rays
	local target = chooseTarget() -- pure maths and raycasts
 
	task.synchronize()
	-- SERIAL: write to instances
	model:PivotTo(target)
end)

The engine runs every Actor's parallel part together, then every serial part one at a time. Most real systems need both: compute in parallel, apply in serial.

Go deeper Why writes must wait

If two Actors moved the same part at the same moment, which position should win, and what would a third Actor reading it in between see? The engine avoids the question by letting parallel code read freely and making every write happen in the serial phase, one Actor at a time. You pay for that safety with a switch back to serial, so batch your writes.

Imagine CombatService.trySwing's hit check moved into its own Actor per player. Put one Actor's work in order.

  1. Call task.synchronize to return to the serial phase
  2. require the modules the script needs, in serial
  3. Write the results to instances
  4. Call task.desynchronize to enter the parallel phase
  5. Do the independent maths and raycasts
Answer

1. require the modules the script needs, in serial 2. Call task.desynchronize to enter the parallel phase 3. Do the independent maths and raycasts 4. Call task.synchronize to return to the serial phase 5. Write the results to instances. Require first (it cannot run in parallel), go parallel for the read-and-compute work, synchronize, then write.

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

4Thread safety: read the label

In the parallel phase the engine checks every API call against its thread safety level and blocks unsafe ones1:

LevelPropertiesFunctions
UnsafeCannot be read or written in parallelCannot be called
Read ParallelCan be read, not writtenn/a
Local SafeRead and write inside the same Actor; read-only from other ActorsCallable inside the same Actor
SafeRead and writeCallable

Every API reference page prints the level. Two examples that matter for games: WorldRoot:Raycast is Safe3. Path:ComputeAsync, which computes a pathfinding route, is Unsafe4. An API with no label is Unsafe.

Which of these may run after task.desynchronize?

  1. workspace:Raycast(origin, direction, params), as trySwing casts it
  2. math.noise(x, y, z)
  3. path:ComputeAsync(start, finish)
  4. part.Position = newPosition
  5. require(script.Parent.Rules)
Answer

workspace:Raycast(origin, direction, params), as trySwing casts it; math.noise(x, y, z). Raycasts and pure maths parallelise well. Pathfinding's ComputeAsync, property writes and require must wait for the serial phase.

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

5Talking between Actors

Real parallel helpers sit at separate workbenches. They cannot reach into each other's drawers. They pass notes, or they share one locked board on the wall that only one of them can write on at a time.

Think of it as Hand a job to a helper

Actors cannot just share Luau tables, because two cores could change the same table at once. The engine gives you three channels1:

  • Actor messages. actor:SendMessage(topic, ...) sends data to one Actor; a script inside binds a handler with BindToMessage or BindToMessageParallel5. Sending does not wait for the receiver.
  • SharedTable. A table-like value many Actors can read and update atomically. Keys are strings or small non-negative integers; values are booleans, numbers, vectors, strings, nested SharedTables or serialisable data types6. You find one by name in SharedTableRegistry or pass it in a message.
  • The data model. Actors can read properties and attributes others wrote, but writes need the serial phase, so this forces frequent synchronising.
luau
-- Coordinator (serial): hand chunk jobs to workers
for i, worker in workers do
	worker:SendMessage("GenerateChunk", i, seed)
end
 
-- Worker script under each Actor
local actor = script:GetActor()
actor:BindToMessageParallel("GenerateChunk", function(index, seed)
	local voxels = generate(index, seed) -- parallel maths
	task.synchronize()
	writeChunk(index, voxels) -- serial write
end)

Match each need to the channel that fits.

  1. Tell the Actor that checks Player3's wrench swings to start
  2. Let 16 workers read and update one big grid of cell costs
  3. Show the result to players
  4. Run the handler in parallel as soon as the message arrives
Answer

Tell the Actor that checks Player3's wrench swings to start: Actor:SendMessage; Let 16 workers read and update one big grid of cell costs: SharedTable; Show the result to players: Write instances in the serial phase; Run the handler in parallel as soon as the message arrives: BindToMessageParallel. Messages go to one Actor. A SharedTable is shared state with atomic updates. Anything players see is an instance write, which is serial.

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

6When parallelism helps, and when it does not

Parallel Luau helps when you have many independent jobs of real maths: validating dozens of hits with raycasts, scoring targets for many NPCs, generating terrain chunks from noise1. It does not help with one small job, with work that mostly writes instances, or with APIs that are Unsafe.

Look at Beacon Yard honestly. The server runs one drone, and its step is a few vector operations and a PivotTo write. The MicroProfiler capture shows where the frame goes:

Roblox Studio
The MicroProfiler paused over the Beacon Yard viewport: frame bars along the top and a timeline of tasks below.

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

Figure 6.1.

A capture of the yard during a drill. There is no batch of independent jobs here for workers to share.

The m08-crawler milestone adds a ground enemy with pathfinding, which changes the picture a little. ComputeAsync itself must stay serial. What can go parallel is everything around it: line-of-sight raycasts, choosing which crate to go around, steering between waypoints, for several crawlers at once.

Which change is most likely to gain from Parallel Luau?

  1. Validating 30 players' wrench hits per second with raycasts, one Actor per player
  2. Moving the one drone with PivotTo
  3. Computing one crawler's path with ComputeAsync
  4. Updating the HUD clock ten times a second
Answer

Validating 30 players' wrench hits per second with raycasts, one Actor per player. Thirty independent raycast validations spread well across cores. One drone is too small, ComputeAsync is Unsafe, and the HUD is cheap client work.

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

7Split the work fairly

When you do have a batch, split it evenly. The docs recommend more Actors than cores: smaller pieces balance better across the cores the device actually has1. Each Actor should still do enough work to be worth the switch. Predict how split(10, 4) divides 10 jobs across 4 Actors before pressing Run.

Luau
local function split(count, actors)
	local batches = {}
	local each = math.floor(count / actors)
	local extra = count - each * actors
	for i = 1, actors do
		table.insert(batches, if i <= extra then each + 1 else each)
	end
	return batches
end
 
print(table.concat(split(10, 4), ", "))
print(table.concat(split(32, 8), ", "))
Figure 7.1. Expected output: 3, 3, 2, 2 4, 4, 4, 4, 4, 4, 4, 4

Using split from the cell above, what does split(7, 3) return?

print(table.concat(split(7, 3), ", "))
  1. 3, 2, 2
  2. 2, 2, 2
  3. 3, 3, 1
  4. 7, 0, 0
Answer

3, 2, 2. Each actor gets 2, and the first actor takes the 1 leftover job: 3, 2, 2. Every job is kept and no batch differs by more than one.

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

8What professionals do

Other ways pros do this

OptionWhat it isWhen pros pick itTrade-offs
Parallel Luau with ActorsScripts under Actors that desynchronize for independent work.Many independent, maths-heavy jobs: hit validation, NPC sensing, procedural chunks.Serial writes, thread-safety rules, harder debugging. No gain for small work.
Spread work over framesProcess N items per frame with task.wait or a queue.Work that is not urgent: rebuilding a leaderboard, regenerating distant chunks.Still one core; results arrive later.
Do less workCache results, lower the rate, cull what players cannot see.Always first. Most slow code does work nobody needs.Needs a profile to know what is unneeded.
Move work to the clientLet each client compute cosmetic work for itself.Visual-only effects such as particles, idle animations, camera.Never for anything that decides gameplay; clients can lie.

A server frame runs long when 20 crawlers chase players. Order the professional's steps.

  1. Capture again on the same scene and compare
  2. Move independent sensing raycasts for each crawler into its own Actor
  3. Remove work nobody needs, such as re-pathing crawlers that are far from every player
  4. Capture a MicroProfiler dump during the chase
Answer

1. Capture a MicroProfiler dump during the chase 2. Remove work nobody needs, such as re-pathing crawlers that are far from every player 3. Move independent sensing raycasts for each crawler into its own Actor 4. Capture again on the same scene and compare. Measure first, cut unneeded work, parallelise what is left and independent, then confirm with a second capture.

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

9Challenges

Level 1, Apprentice

Challenge

Classify three APIs from the game by their thread safety.

Start from
The game at milestone m06 (download)

Done means

  • You look up the thread safety line for three APIs Beacon Yard uses
  • You say for each whether it could run after task.desynchronize

Hints

  1. Try WorldRoot:Raycast, Model:PivotTo and Players:GetPlayers.
  2. The level is printed on each method's reference entry.

An API reference entry gives no thread safety level. What should you assume?

  1. Unsafe
  2. Safe
  3. Read Parallel
  4. Local Safe
Answer

Unsafe. Members without a level are Unsafe by default. Call them only in the serial phase.

Level 2, Builder

Challenge

In a separate test place, measure whether parallel raycasts help on your machine.

Start from
The game at milestone m06 (download)

Done means

  • A test place has 8 Actors, each casting 200 rays per Heartbeat in parallel
  • The rays are cast after ConnectParallel or task.desynchronize, and nothing is written in parallel
  • You compare a MicroProfiler capture with the same rays cast serially by one script

Hints

  1. Build the RaycastParams in serial before the loop starts.
  2. Count hits into a local variable and print the total after task.synchronize.
  3. Look for worker threads in the parallel capture.

Level 3, Professional

Challenge

Fix the planning helpers in challenges/parallel_luau_work.luau on m14-ship. Press Play and run this in the server command bar:

luau
game.ServerScriptService.RunGameTests:Invoke("parallel-luau")
Start from
The game at milestone m14 (download)
Grade it
In Studio, press Play, then run game.ServerScriptService.RunGameTests:Invoke("parallel-luau") in the server command bar. Copy the pass code from Output.

Done means

  • phaseFor returns parallel only for Raycast and math.noise, and serial for everything else
  • splitIntoBatches keeps every job and no two batches differ by more than one
  • challenges/parallel-luau.luau prints TEST PASS for all nine cases

Hints

  1. Use a table of operations known to be safe, and default to serial.
  2. Hand the leftover jobs to the first actors, one each.

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

10Recap

Retiring the analogy

You no longer need “hand a job to a helper”. task.spawn creates a coroutine and resumes it right away on the same scheduler. Concurrency is cooperative: work interleaves only at yields such as task.wait.

Recap

  1. task.spawn takes turns on one thread. Real parallelism needs scripts under different Actors.
  2. Desynchronize for reads, maths and Safe calls; synchronize before any write. Check every API's thread safety.
  3. Use it for many independent jobs, after profiling. ComputeAsync stays serial; one drone gains nothing.

task.spawn is hand a job to a helper, until helpers take turns rather than working at the same time: a spawned function that never yields blocks the caller and every other script.

Next Mobile: streaming, memory and draw budgets

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