Architecture for a big codebase: lifecycles, dependencies, frameworks

Replace Beacon Yard's 24 hand-ordered requires with a loader: init and start phases, declared dependencies, cycle errors, roles from one table, injected fakes for tests, tags as components, and an honest look at Knit, Nevermore, Flamework and jecs.

Lab lesson, about 80 minutes, 11 steps

By the end you can

  • Split every service into an init phase that builds its own state and a start phase that may use others
  • Let each service declare its dependencies and have a loader order them, refuse cycles and boot a role from one table
  • Hand a service its dependencies so a test can pass a fake one
  • Judge plain modules, Knit, Nevermore, Flamework and an ECS for a codebase like Beacon Yard

Before this: Boot order: what runs first, ModuleScripts and require, Unit tests with Jest-Lua

1Twenty-four requires and an order nobody wrote down

This is the top of the only script that boots a Beacon Yard server, at m14-ship:

local Remotes = require(script.Remotes)
local MapBuilder = require(script.MapBuilder)
local DataService = require(script.DataService)
local CoinService = require(script.CoinService)
local ShopService = require(script.ShopService)
local CombatService = require(script.CombatService)
local DroneService = require(script.DroneService)
local CrawlerService = require(script.CrawlerService)
local RoundService = require(script.RoundService)
local ExhibitService = require(script.ExhibitService)
local WorldLook = require(script.WorldLook)
local TeamService = require(script.TeamService)
local AnnounceService = require(script.AnnounceService)
local PolicyProbe = require(script.PolicyProbe)
local MonetizationService = require(script.MonetizationService)
local SettingsService = require(script.SettingsService)
local PassService = require(script.PassService)
local BadgeAwards = require(script.BadgeAwards)
local Analytics = require(script.Analytics)
local FlagService = require(script.FlagService)
local LobbyBuilder = require(script.LobbyBuilder)
local QueueService = require(script.QueueService)
local LeaderboardService = require(script.LeaderboardService)
local MatchService = require(script.MatchService)
Figure 1.1

Then the yard branch starts the services one by one:

	-- The wrench has to exist before the first character spawns. MapBuilder
	-- and DataService can yield, and StarterPack only copies tools at spawn.
	CombatService.start()
	local map = MapBuilder.build()
	DataService.start()
	MonetizationService.start()
	PassService.start()
	BadgeAwards.start()
	Analytics.start()
	FlagService.start()
	CoinService.start(map.pads)
	ShopService.start(map.shopPrompt)
	local drone = DroneService.start(map.droneSpawn)
	local crawler = CrawlerService.start({ spawn = map.crawlerSpawn, container = map.yard })
	RoundService.start({
		prompt = map.beaconPrompt,
		gateLeft = map.gateLeft,
		gateRight = map.gateRight,
		-- Both enemies switch on and off with the drill.
		setDroneActive = function(on: boolean)
			drone.setActive(on)
			crawler.setActive(on)
		end,
	})
	ExhibitService.start(map.yard)
	TeamService.start()
	AnnounceService.start()
	PolicyProbe.start()
Figure 1.2

Boot order: what runs first taught why this order matters: MapBuilder.build and DataService.start can yield, and the wrench must sit in StarterPack before then. That knowledge lives in a comment. The rest of the order lives nowhere: Analytics after DataService, FlagService before CoinService, because CoinService reads the Scrap Rush multiplier.

On a Solo server (no lobby, no match), how many init, start and build calls does init.server.luau make? Count the three before the role check plus the yard branch.

Answer

20 calls. 3 shared calls plus 17 in the yard branch. Each one sits where it does for a reason, and only a few of those reasons are written down.

What goes wrong when the team grows

Three things get worse with every service you add.

  1. The order is tribal knowledge. A new QuestService that pays coins must start after DataService. Nothing says so until a player loses a reward.
  2. Every change touches one shared file in two places, the require list and a role branch, so two people adding services on the same day get a merge conflict.
  3. Some dependencies are hidden. CombatService does not appear to need CrawlerService at boot, yet it requires it at the top of its file to deal wrench damage:
local CrawlerService = require(childModule(serverFolder, "CrawlerService")) :: {
	damageFromWrench: (player: Player, hit: Instance, amount: number) -> boolean,
}
Figure 1.3

A teammate adds QuestService.start() right after CombatService.start(), before DataService.start(). QuestService pays 20 coins for the first drill through DataService.addCoins. What is the likely result?

  1. It boots without an error, and early rewards go to profiles that have not loaded yet, so some vanish
  2. Luau refuses to run the script because the order is wrong
  3. DataService starts itself the first time addCoins is called
  4. Roblox reorders start calls by their dependencies
Answer

It boots without an error, and early rewards go to profiles that have not loaded yet, so some vanish. Nobody does, which is the problem. A loader that reads declared dependencies turns this silent bug into an error at boot.

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

2Two phases: init builds, start connects

Every serious Roblox codebase splits a service's life into phases. The names vary; the rule does not:

  • init: build your own state. Create your folder, your tables, your tool. Call no other service and never yield.
  • start: now everyone has finished init. Connect events, read other services, load data. Yielding is allowed.

Run every init, then every start. Beacon Yard's boot problem disappears: CombatService.init puts the wrench in StarterPack, and because no init yields, it is there before anything else can spawn a character. The comment about order becomes a rule the loader enforces.

Server sideService lifecycles and dependencies is crews on a building site: each sets up its own corner, then the foreman schedules the work from every crew's note of who must finish first.
In the pictureIn Roblox
A crewA service module such as CoinService
Unloading its own tools before work beginsinit: build its own state, call nobody, never yield
The note saying which crews must finish firstThe service's deps list
The foreman building the scheduleThe loader sorting services so each starts after its deps
Two crews each waiting for the otherA dependency cycle, which the loader refuses with the loop's names

See the whole analogy cast

Think of a building site. Before work begins, every crew unloads its own tools and sets up its own corner, and nobody needs anyone else for that. Then the foreman reads each crew's note, "we need the walls up first", and builds the day's schedule from those notes. Crews are services, setting up is init, the notes are dependencies, and the foreman is the loader.

Think of it as Crews on a building site: each sets up its own corner, then the foreman schedules the work from every crew's note of who must finish first

The client boots too. At m15-scale, init.client.luau still starts its modules by hand: the Store first, because every screen reads the player's state from it, then Accessibility, then the HUD and the rest. A client loader would follow the same rules. Mount UI only after the store has its first snapshot, and keep per-character controllers apart from per-player ones, since a character is replaced on every respawn.

Why must an init never yield, for example with WaitForChild or a DataStore call?

  1. A yield lets the engine run other work, such as spawning a character, before every init has finished, so the wrench might not be in StarterPack yet
  2. init runs on the client, where yielding is not allowed
  3. Luau throws an error when a function named init yields
  4. Yielding in init makes the service start twice
Answer

A yield lets the engine run other work, such as spawning a character, before every init has finished, so the wrench might not be in StarterPack yet. Inits are the part of boot that runs without a break. Anything that can wait, such as profiles, the map or HTTP, belongs in start.

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

3Each service says what it needs

Instead of one person ordering twenty calls, each service declares its dependencies next to its code:

luau
local CoinService = {}
CoinService.deps = { "Analytics", "DataService", "FlagService", "MapBuilder", "Remotes" }
 
function CoinService.start(deps)
	local pads = deps.MapBuilder.handles().pads
	-- ...
end

The loader collects every service's list and sorts them so each comes after everything it needs. This is a topological sort, and the simplest version is Kahn's algorithm: repeatedly start a service whose dependencies have all started. When several are ready at once, take the one whose name sorts first. That last rule matters: the order then depends only on the names and their lists, never on the order of the files. Before you run it on six of the yard's real services, predict one position.

CoinService needs Analytics, DataService, FlagService and Remotes. Analytics needs DataService. FlagService needs Remotes. DataService needs DataMigration and Remotes. Remotes and DataMigration need nothing. The loader places one ready service at a time, the one whose name sorts first. In which position, 1 to 6, does FlagService land?

Answer

5. DataMigration, Remotes, DataService, Analytics, FlagService, CoinService. FlagService is ready from the third pick, but DataService and then Analytics win the tie on name. Run the cell to check.

Luau
-- Six Beacon Yard services and the modules each one requires at m14-ship.
local services = {
	{ name = "CoinService", deps = { "Analytics", "DataService", "FlagService", "Remotes" } },
	{ name = "Analytics", deps = { "DataService" } },
	{ name = "FlagService", deps = { "Remotes" } },
	{ name = "DataService", deps = { "DataMigration", "Remotes" } },
	{ name = "Remotes", deps = {} },
	{ name = "DataMigration", deps = {} },
}
 
local function order(list)
	local byName, left, result = {}, {}, {}
	for _, service in list do
		byName[service.name] = service
		left[service.name] = true
	end
	while next(left) ~= nil do
		local ready = {}
		for name in left do
			local blocked = false
			for _, dep in byName[name].deps do
				if left[dep] then
					blocked = true
				end
			end
			if not blocked then
				table.insert(ready, name)
			end
		end
		if #ready == 0 then
			return nil, "cycle"
		end
		table.sort(ready)
		left[ready[1]] = nil
		table.insert(result, ready[1])
	end
	return result
end
 
print(table.concat(order(services), " "))
Figure 3.1. Expected output: DataMigration Remotes DataService Analytics FlagService CoinService
Who needs whom among six yard servicesTwo rows of three boxes. Top row: CoinService, Analytics, DataService, with arrows from CoinService to Analytics and from Analytics to DataService. Bottom row: FlagService, Remotes, DataMigration. CoinService points down to FlagService, FlagService points to Remotes, and DataService points down to DataMigration and diagonally to Remotes.CoinServiceAnalyticsDataServiceFlagServiceRemotesDataMigration
Figure 3.2. An arrow means needs. CoinService also needs DataService and Remotes directly; those arrows are left out to keep it readable.

In the output, why does DataMigration come before Remotes, even though Remotes is in more lists?

  1. Both were ready at the start and DataMigration sorts first by name
  2. DataMigration has more dependencies
  3. Remotes depends on DataMigration
  4. The loader starts the service listed last first
Answer

Both were ready at the start and DataMigration sorts first by name. Ties are broken by name, so the result depends only on what each service needs. That is what lets five people add services without fighting over a file.

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

4Cycles: two crews waiting on each other

What if RoundService needed DroneService to switch the drone on, and DroneService needed RoundService to know whether a drill is running? Neither can go first. The loader in the cell above returns "cycle"; a good loader names the loop, such as cycle: DroneService -> RoundService -> DroneService, and boots nothing.

Luau has its own guard one level down: if two ModuleScripts require each other while loading, require stops with Requested module was required recursively1. The loader catches the start-order version of the same mistake, which no require ever sees.

Server sideRemember: Service lifecycles and dependencies is crews on a building site: each sets up its own corner, then the foreman schedules the work from every crew's note of who must finish first.

Beacon Yard already avoided this cycle. Look at how the boot script hands RoundService a way to switch both enemies:

	RoundService.start({
		prompt = map.beaconPrompt,
		gateLeft = map.gateLeft,
		gateRight = map.gateRight,
		-- Both enemies switch on and off with the drill.
		setDroneActive = function(on: boolean)
			drone.setActive(on)
			crawler.setActive(on)
		end,
	})
Figure 4.1

RoundService gets a setDroneActive function at start instead of requiring DroneService and CrawlerService. What does that buy?

  1. RoundService needs neither enemy module, so the enemies can depend on the round without a cycle, and a test can pass a function that only records calls
  2. The drone moves faster because a callback skips a require
  3. Callbacks replicate to clients, so the HUD can switch the drone
  4. It is required because ModuleScripts cannot call each other
Answer

RoundService needs neither enemy module, so the enemies can depend on the round without a cycle, and a test can pass a function that only records calls. When two services want each other, pass one of them a function or a signal. The cycle disappears and both get easier to test.

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

5Hand in the dependencies, and tests get easy

Notice that start(deps) can receive its dependencies instead of requiring them. That is dependency injectionDependency injectionHanding a module the other modules it uses, instead of letting it fetch them itself, so a test can hand it fakes.Think of it as a crew that works with whatever tools the foreman gives it, so a trainee can practise with toy ones., and it pays for itself the first time you test. The real DataService needs ProfileStore, a player and a live session. A test only needs something with an addCoins function:

Luau
local CoinService = {}
 
function CoinService.start(deps)
	local DataService = deps.DataService
	function CoinService.pay(player, amount)
		return DataService.addCoins(player, amount)
	end
end
 
-- A fake DataService: no ProfileStore, no Player, just a log of calls.
local paid = {}
local fakeData = {
	addCoins = function(player, amount)
		table.insert(paid, player .. "+" .. amount)
		return amount
	end,
}
 
CoinService.start({ DataService = fakeData })
CoinService.pay("tester", 5)
CoinService.pay("tester", 10)
print(table.concat(paid, " "))
Figure 5.1. Expected output: tester+5 tester+10

Be clear about how far Beacon Yard goes. At m15-scale most services still require their dependencies at the top of the file, because that gives the type checker their types. Only handles that exist after another service's start arrive through deps, such as the pads CoinService reads from MapBuilder:

function CoinService.start(deps: { MapBuilder: { handles: () -> { pads: { BasePart } } } })
	for _, pad in deps.MapBuilder.handles().pads do
Figure 5.2

So a spec could fake DataService this way only once CoinService takes it through deps. Today the Jest-Lua specs from Unit tests with Jest-Lua fake whole modules instead: Loader.spec.luau hands Loader.boot fake services that only record their init and start calls.

What can a spec with a fake DataService check that one using the real DataService cannot do quickly?

  1. That a pickup asks for exactly 5 coins, in milliseconds, with no player, no ProfileStore session and no Studio
  2. That ProfileStore saves the coins to Roblox's servers
  3. That the HUD shows the new balance
  4. That an exploiter cannot fake a pickup
Answer

That a pickup asks for exactly 5 coins, in milliseconds, with no player, no ProfileStore session and no Studio. Fakes test one service's rules in isolation. Keep a few slower tests that use the real pieces together, too.

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

6Roles from one table

Beacon Yard boots three kinds of server from one script: Lobby, Match and Solo. At m14-ship that is an if with two long branches. With declared dependencies, a role is a short list of the services it wants, and the loader adds what they need:

local ROLES: { [string]: { string } } = {
	Lobby = {
		"SettingsService",
		"WorldLook",
		"PassService",
		"Analytics",
		"StrikeService",
		"QueueService",
		"LeaderboardService",
	},
	Solo = {
		"SettingsService",
		"WorldLook",
		"CombatService",
		"CoinService",
		"ShopService",
		"RoundService",
		"ExhibitService",
		"TeamService",
		"AnnounceService",
		"PolicyProbe",
	},
}
ROLES.Match = table.clone(ROLES.Solo)
table.insert(ROLES.Match, "MatchService")
Figure 6.1

In the Lobby, PassService brings in DataService. Its module requires DataMigration, a helper with no startup phase. A service lists only the services it needs the loader to start.

Two roots and what the loader addsA gold box labelled Roots, holding PassService and SettingsService, has an arrow to a copper box labelled Loader, which has an arrow to an ink box labelled Booted, listing eight services including DataService, PlayerState and Remotes.Roots2 servicesLoaderadds depsBooted8 services
Figure 6.2. The roots name what the server is for. The loader adds what those services need. The real Lobby has 7 roots and boots 14 services.

This is a pure graph walk. PlayerState, NetMeter, PlayerScopes and RemoteGuard are services you add later in this module; for now they are just names. At m15-scale, PassService needs DataService and Remotes. DataService needs PlayerState and Remotes. PlayerState needs NetMeter, PlayerScopes, RemoteGuard and Remotes. SettingsService needs PlayerScopes, RemoteGuard and Remotes. Which services boot for the roots PassService and SettingsService?

  1. PassService
  2. SettingsService
  3. DataService
  4. Remotes
  5. PlayerState
  6. NetMeter
  7. PlayerScopes
  8. RemoteGuard
  9. DataMigration
  10. MapBuilder
Answer

PassService; SettingsService; DataService; Remotes; PlayerState; NetMeter; PlayerScopes; RemoteGuard. The two roots and their transitive dependencies make eight services. DataMigration is loaded by require and has no boot phase.

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

7Tags as components

Services handle systems. Many things in a game are instances that share behaviour: every crawler, every coin, every scrap pile. Beacon Yard already marks them with CollectionService tagsTag (CollectionService)A string label on an instance that scripts can search for.Think of it as a coloured sticker.. At m14-ship, CombatService asks for everything tagged Drone or Crawler and casts its ray only at those parts, so the tag is the component and the raycast is the system. (From The network budget: measure, batch, pack on, the drone is data in a table with no server part, and only crawlers keep the tag.)

The next step is a binder: when a tag is added, build a small object for that instance; when it is removed or destroyed, clean the object up. CollectionService:GetTagged, GetInstanceAddedSignal and GetInstanceRemovedSignal are all you need2. A tagged crawler that the server spawns gets its brain the moment the tag lands, and a crawler a designer drops into the map in Studio gets one too. Beacon Yard has no binder at m15-scale, so here is one in miniature. The fake CollectionService below stands in for the real one so the cell runs anywhere:

Luau
-- A stand-in for CollectionService with the three calls a binder uses.
local tagged, added, removed = {}, {}, {}
local Tags = {
	GetTagged = function(_, tag) return table.clone(tagged[tag] or {}) end,
	GetInstanceAddedSignal = function(_, tag)
		return { Connect = function(_, fn) added[tag] = fn end }
	end,
	GetInstanceRemovedSignal = function(_, tag)
		return { Connect = function(_, fn) removed[tag] = fn end }
	end,
}
local log = {}
 
-- The binder: one object per tagged instance, cleaned up when the tag goes.
local function bind(tag, make)
	local objects = {}
	local function add(instance)
		objects[instance] = make(instance)
	end
	for _, instance in Tags:GetTagged(tag) do
		add(instance)
	end
	Tags:GetInstanceAddedSignal(tag):Connect(add)
	Tags:GetInstanceRemovedSignal(tag):Connect(function(instance)
		local object = objects[instance]
		objects[instance] = nil
		if object then
			object.destroy()
		end
	end)
	return objects
end
 
tagged.Crawler = { "Crawler1" } -- placed in Studio before the server starts
local brains = bind("Crawler", function(name)
	table.insert(log, "bind " .. name)
	return { destroy = function() table.insert(log, "unbind " .. name) end }
end)
added.Crawler("Crawler2") -- the server spawns another one
removed.Crawler("Crawler1") -- the first one is destroyed
 
local count = 0
for _ in brains do
	count += 1
end
print(table.concat(log, " ") .. " brains " .. count)
Figure 7.1. Expected output: bind Crawler1 bind Crawler2 unbind Crawler1 brains 1

An entity component systemEntity component system (ECS)A way to structure a simulation where entities are plain ids, components are data attached to them, and systems update every entity that has a given set of components.Think of it as a spreadsheet with one row per thing and one column per kind of data, where each system works down the columns it cares about. (ECS) takes the idea further: entities are plain ids, components are tables of data, and systems loop over every entity with a given set of components each frame. It shines with thousands of entities and many combinations of state (burning, stunned, shielded, slowed). Beacon Yard has one drone and one crawler type; tags and a binder are plenty.

Which change would make an ECS such as jecs worth adopting in Beacon Yard?

  1. Hundreds of crawlers, drones and pets on screen, each with any mix of status effects that systems update every frame
  2. Adding a third button to the shop
  3. Moving the HUD to React
  4. Saving one more field in the player profile
Answer

Hundreds of crawlers, drones and pets on screen, each with any mix of status effects that systems update every frame. Adopt an ECS when entity count and state combinations hurt, not because a framework is popular. Measure first.

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

8Frameworks: what they give you, and what Beacon Yard needs

Everything in this lesson is what frameworks package. Here is what the common ones are, with their status today:

How studios structure a Roblox codebase

OptionWhat it isWhen pros pick itTrade-offs
Plain modules plus a small loaderServices are ModuleScripts with deps, init and start; a loader of about 100 lines orders and boots them.Beacon Yard and most teams writing Luau. You can read every line.You own the loader and its conventions; there is no client-server bridge built in.
Knit (archived)Services and controllers with KnitInit and KnitStart, plus automatic remotes between them. MIT licence.Reading older codebases. The repository is archived and its last change was in July 2024.No fixes or updates. Teach its Init/Start pattern, never install it in new code.
NevermoreA large MIT-licensed collection of packages; ServiceBag finds, initialises and starts services and their dependencies.Teams that want many ready-made packages from one actively maintained source (updated this month).Big surface and its own conventions; installed through npm packages.
FlameworkA framework for roblox-ts (TypeScript) with decorators, dependency injection and lifecycle events. MIT licence.Teams already writing roblox-ts.Requires TypeScript; maintained but slow, with the last change in September 2025.
jecs (ECS)A fast entity component system for Luau, MIT licence, actively maintained.Many entities with many component combinations, measured to be a bottleneck.A different way of thinking; overkill for a handful of enemy types.

A new teammate wants to install Knit in Beacon Yard because a tutorial used it. What do you answer?

  1. Knit is archived and gets no fixes; we keep its init and start idea in our own small loader
  2. Install it: archived means finished and stable
  3. Install it, but only on the client
  4. Knit is required for remotes to work
Answer

Knit is archived and gets no fixes; we keep its init and start idea in our own small loader. Learn frameworks for their ideas. Depend only on what is maintained, or on code small enough to own.

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

9Build along: the yard loader

You build this in your own copy of the finished game. First pass the level 3 challenge below. Use its order and boot functions as the starting point for src/server/Loader.luau. The challenge uses the older dependency graph.

Roblox Studio
Roblox Studio's Output window after pressing Play, listing Loader lines for each service in dependency order with an init and start time, then a final line saying the Solo role booted.
Figure 9.1.

The loader's boot log: one line per service, in dependency order, with timings.

After a merge, about one playtest in five spawns a player with no wrench. Nothing errors. The diff shows a teammate added ReplicatedStorage:WaitForChild("Assets") to the top of TeamService.init. What is the most likely cause?

  1. The WaitForChild yields when Assets has not replicated yet, so the engine can spawn a character before CombatService.init has put the wrench in StarterPack
  2. WaitForChild is deprecated, so the call fails silently
  3. TeamService and CombatService now form a cycle
  4. StarterPack is cleared whenever any init yields
Answer

The WaitForChild yields when Assets has not replicated yet, so the engine can spawn a character before CombatService.init has put the wrench in StarterPack. Intermittent missing-at-spawn bugs usually mean something yields in a phase that promised not to. A loader can catch this in Studio by timing each init and warning when one takes more than a frame.

Build along

m14-ship to m15-scale

  • src/server/Loader.luau
  • src/server/init.server.luau
  • src/server/CombatService.luau
  • src/server/DroneService.luau
  • src/server/TestHooks.luau
  • tests/scale.luau
  • scripts/lune/check-boot.luau
  • .github/workflows/ci.yml
  1. Declare deps on the services. Follow the needed startup order. CombatService lists DroneService, and DroneService lists MapBuilder. A helper such as DataMigration can be required without a place in the boot graph.

    You should see Every boot dependency points to a service that must start first.

  2. Call createWrench() in CombatService.init. Keep the started guard in start, which connects Swing through RemoteGuard. All init calls finish before any start, so the wrench needs no separate ordering rule.

    You should see CombatService.init builds the wrench before any start runs. CombatService.start registers Swing.

  3. Discover the services. Read PlaceRole.current() and pick the roots from ROLES. Then loop over the script's ModuleScript children, require each one, and keep those with a deps list: add { name, deps } to specs and the module to modules.

    You should see Booting the yard prints an error naming the role if ROLES has no entry for it, and specs lists every sibling module that has deps.

  4. Wrap each phase so it is timed and runs under the service's own memory category. This is the helper from the tag:

    local function timed(name: string, phase: "init" | "start", fn: unknown): (...unknown) -> ()
    	local run = fn :: (...unknown) -> ()
    	return function(...: unknown)
    		debug.setmemorycategory(name)
    		local began = os.clock()
    		run(...)
    		times[name][phase] = (os.clock() - began) * 1000
    		debug.resetmemorycategory()
    	end
    end
    -- require through a variable: the type checker only follows literal paths.
    
    Figure 9.2

    Then call Loader.boot(specs, modules, roots), print one Loader: line per service in order, set the BootOrder attribute, and call TestHooks.install(script).

    You should see Solo, Lobby and Match each log one Loader line per service with init and start times.

  5. Run lune run scripts/lune/check-boot, the check in the specs CI job. In the test place, boot_order in tests/scale.luau checks that BootOrder has more than ten entries and includes CombatService and MapBuilder, and that StarterPack contains Wrench.

    You should see The boot check runs in CI, and the Studio test checks the wrench and both services.

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

10Where the building-site picture breaks

On a real site, two crews stuck waiting on each other talk it out and one starts early. What does a loader do with a cycle, and how is it fixed?

  1. It boots nothing and names the loop; you fix the code, for example by passing a callback as RoundService gets setDroneActive
  2. It starts the service with the shorter name first
  3. It starts both at once in separate threads
  4. It waits until one of them finishes start
Answer

It boots nothing and names the loop; you fix the code, for example by passing a callback as RoundService gets setDroneActive. Crews negotiate; code cannot. Point one dependency the other way and the loop is gone.

Where does it break?“Crews on a building site: each sets up its own corner, then the foreman schedules the work from every crew's note of who must finish first” is a good picture of service lifecycles and dependencies. Where does it stop being true?

It breaks here. Crews stuck on each other negotiate and one starts early; a loader cannot, so a cycle is a design fault fixed in code by splitting a service or passing a callback. And a crew finishes and leaves, while a service runs for the life of the server and must clean up after every player who leaves.

The true model. Each service has an init phase that only builds its own state and a start phase that may use others; it declares its deps, and a loader orders them with a stable topological sort, refuses unknown deps and cycles, and hands each start its deps so tests can pass fakes.

The picture breaks a second way. A crew finishes and leaves the site. A service never leaves: it runs for the whole life of the server, and players come and go around it. Everything it creates for a player has to be cleaned up when that player goes, which is the next lesson.

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

11Challenges and recap

Fix closure in this cell. It is meant to return the roots plus everything they need, but it stops one level down.

Luau
local deps = {
	Remotes = {},
	DataMigration = {},
	DataService = { "DataMigration", "Remotes" },
	PassService = { "DataService", "Remotes" },
	SettingsService = { "Remotes" },
	WorldLook = {},
}
 
local function closure(roots)
	-- Bug: adds each root's direct deps, but not the deps of those deps.
	local keep = {}
	for _, root in roots do
		keep[root] = true
		for _, dep in deps[root] do
			keep[dep] = true
		end
	end
	local names = {}
	for name in keep do
		table.insert(names, name)
	end
	table.sort(names)
	return table.concat(names, " ")
end
 
print(closure({ "PassService" }))
Figure 11.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 closure in the closure-fix cell so all three tests pass.

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

  • closure follows deps of deps, however deep
  • Each name appears once, sorted
  • All three assertions in closure-fix pass

Hints

  1. Keep a stack of names still to visit and push each new dep onto it.
  2. Skip a name already in keep, or a shared dep is visited twice.
Solution
luau
local deps = {
	Remotes = {},
	DataMigration = {},
	DataService = { "DataMigration", "Remotes" },
	PassService = { "DataService", "Remotes" },
	SettingsService = { "Remotes" },
	WorldLook = {},
}
 
local function closure(roots)
	local keep = {}
	local stack = table.clone(roots)
	while #stack > 0 do
		local name = table.remove(stack)
		if not keep[name] then
			keep[name] = true
			for _, dep in deps[name] do
				table.insert(stack, dep)
			end
		end
	end
	local names = {}
	for name in keep do
		table.insert(names, name)
	end
	table.sort(names)
	return table.concat(names, " ")
end
 
print(closure({ "PassService" }))

Put one boot of a Solo yard server with the loader in order.

  1. Call init on each service in that order, so the wrench is in StarterPack
  2. Add every dependency of the listed services and sort them, refusing a cycle
  3. Call start on each service with a table of its declared dependencies
  4. Players join and spawn holding the wrench
  5. Read PlaceRole and pick the Solo list from ROLES
Answer

1. Read PlaceRole and pick the Solo list from ROLES 2. Add every dependency of the listed services and sort them, refusing a cycle 3. Call init on each service in that order, so the wrench is in StarterPack 4. Call start on each service with a table of its declared dependencies 5. Players join and spawn holding the wrench. Pick the role, resolve and check the order, run every init without a yield, then every start. Spawns can only happen once something yields.

Level 2, Builder

Challenge

Finish the build-along in your copy and boot all three roles. There is no Luau test for this one: the proof is a lobby without a yard and a Solo drill that plays as before.

Start from
The game at milestone m14 (download)

Done means

  • Every service the boot script starts declares deps that match its requires, plus MapBuilder where it reads map parts
  • ROLES lists Lobby, Solo and Match; Match is Solo plus MatchService
  • The Lobby role boots no MapBuilder, CombatService or enemies, and the Output shows its order
  • Solo plays a full drill: wrench in hand on first spawn, coins pay, the shop sells

Hints

  1. Print the order the loader returns before booting, and compare it with the old start list.
  2. If the first spawn has no wrench, something in an init yields.

Level 3, Professional

Challenge

Write order and boot in challenges/work/service_loader.luau. The test uses the yard's real dependency lists and shuffles them. The written solution is challenges/solutions/architecture-at-scale.md. In Play, run game.ServerScriptService.RunGameTests:Invoke("architecture-at-scale", "arch-loader") 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("architecture-at-scale", "arch-loader") in the server command bar. Copy the pass code from Output.

Done means

  • order puts every dependency before its dependents and ignores the order of the input list
  • Ties go to the name that sorts first, picked one at a time
  • A cycle returns nil and 'cycle: ...' naming only the services in the loop; an unknown dependency names both services
  • With roots, order returns only the roots and what they need
  • boot runs every init, then every start with exactly its declared deps, and runs nothing on an error
  • challenges/architecture-at-scale.luau prints TEST PASS for every check

Hints

  1. Kahn's algorithm: each round, collect the names whose deps have all been placed, sort them, place the first.
  2. When no name is ready but some are left, every one left is stuck behind another: walk from the first stuck name through stuck deps until a name repeats.
  3. Check unknown dependencies before anything else.

Retiring the analogy

You no longer need “crews on a building site: each sets up its own corner, then the foreman schedules the work from every crew's note of who must finish first”. Each service has an init phase that only builds its own state and a start phase that may use others; it declares its deps, and a loader orders them with a stable topological sort, refuses unknown deps and cycles, and hands each start its deps so tests can pass fakes.

Recap

  1. Beacon Yard boots 24 modules with 20 hand-ordered calls; the order's reasons live in comments and memory.
  2. Split every service into init (own state, no calls to others, no yields) and start (connect, read others, may yield); run every init before any start.
  3. Each service declares deps; a loader sorts them with Kahn's algorithm, breaks ties by name, refuses unknown deps and names a cycle.
  4. Break a cycle by passing a function or signal, as RoundService receives setDroneActive.
  5. start(deps) can inject dependencies so tests pass fakes; at m15-scale only handles such as MapBuilder arrive that way. Roles are short lists; the loader adds what they need.
  6. Tags are components for many similar instances; an ECS pays off only with many entities and combinations. Knit is archived: keep the pattern, not the package.

Service lifecycles and dependencies is crews on a building site: each sets up its own corner, then the foreman schedules the work from every crew's note of who must finish first, until crews stuck on each other negotiate and one starts early; a loader cannot, so a cycle is a design fault fixed in code by splitting a service or passing a callback. And a crew finishes and leaves, while a service runs for the life of the server and must clean up after every player who leaves.

Next Lifetimes: signals, Trove and leak hunting

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