Lesson 1 of 11
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.
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)
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()
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.
- The order is tribal knowledge. A new
QuestServicethat pays coins must start afterDataService. Nothing says so until a player loses a reward. - 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.
- Some dependencies are hidden.
CombatServicedoes not appear to needCrawlerServiceat 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,
}
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?
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.
| In the picture | In Roblox |
|---|---|
| A crew | A service module such as CoinService |
| Unloading its own tools before work begins | init: build its own state, call nobody, never yield |
| The note saying which crews must finish first | The service's deps list |
| The foreman building the schedule | The loader sorting services so each starts after its deps |
| Two crews each waiting for the other | A dependency cycle, which the loader refuses with the loop's names |
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.
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?
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:
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.
-- 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), " "))
DataMigration Remotes DataService Analytics FlagService CoinServiceIn the output, why does DataMigration come before Remotes, even though Remotes is in more lists?
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,
})
RoundService gets a setDroneActive function at start instead of requiring DroneService and CrawlerService. What does that buy?
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:
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, " "))
tester+5 tester+10Be 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
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?
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")
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.
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?
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:
-- 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)
bind Crawler1 bind Crawler2 unbind Crawler1 brains 1An 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?
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
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Plain modules plus a small loader | Services 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. |
| Nevermore | A 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. |
| Flamework | A 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?
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.

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?
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.
src/server/Loader.luausrc/server/init.server.luausrc/server/CombatService.luausrc/server/DroneService.luausrc/server/TestHooks.luautests/scale.luauscripts/lune/check-boot.luau.github/workflows/ci.yml
Declare
depson the services. Follow the needed startup order.CombatServicelistsDroneService, andDroneServicelistsMapBuilder. A helper such asDataMigrationcan be required without a place in the boot graph.You should see Every boot dependency points to a service that must start first.
Call
createWrench()inCombatService.init. Keep thestartedguard instart, which connectsSwingthroughRemoteGuard. 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.
Discover the services. Read
PlaceRole.current()and pick the roots fromROLES. Then loop over the script's ModuleScript children, require each one, and keep those with adepslist: add{ name, deps }tospecsand the module tomodules.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.
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 oneLoader:line per service in order, set theBootOrderattribute, and callTestHooks.install(script).You should see Solo, Lobby and Match each log one Loader line per service with init and start times.
Run
lune run scripts/lune/check-boot, the check in thespecsCI job. In the test place,boot_orderintests/scale.luauchecks thatBootOrderhas more than ten entries and includesCombatServiceandMapBuilder, and thatStarterPackcontainsWrench.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?
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.
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" }))
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
- Keep a stack of names still to visit and push each new dep onto it.
- Skip a name already in keep, or a shared dep is visited twice.
Solution
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.
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
- Print the order the loader returns before booting, and compare it with the old start list.
- 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
- Kahn's algorithm: each round, collect the names whose deps have all been placed, sort them, place the first.
- 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.
- 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
- Beacon Yard boots 24 modules with 20 hand-ordered calls; the order's reasons live in comments and memory.
- 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.
- Each service declares deps; a loader sorts them with Kahn's algorithm, breaks ties by name, refuses unknown deps and names a cycle.
- Break a cycle by passing a function or signal, as RoundService receives setDroneActive.
- 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.
- 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.
Queued for review
- 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?
- Why must an init never yield, for example with WaitForChild or a DataStore call?
- RoundService gets a setDroneActive function at start instead of requiring DroneService and CrawlerService. What does that buy?
- What can a spec with a fake DataService check that one using the real DataService cannot do quickly?
- 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?
Open this step in lesson mode · Link to this step · This confused me