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
Step 1 of 11
Twenty-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.
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?
Press 1 to 4 to choose, Enter to check.
Step 2 of 11
Two 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?
Press 1 to 4 to choose, Enter to check.
Step 3 of 11
Each 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?
In the output, why does DataMigration come before Remotes, even though Remotes is in more lists?
Press 1 to 4 to choose, Enter to check.
Step 4 of 11
Cycles: 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?
Press 1 to 4 to choose, Enter to check.
Step 5 of 11
Hand 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:
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
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?
Press 1 to 4 to choose, Enter to check.
Step 6 of 11
Roles 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?
Press 1 to 9 to choose, Enter to check.
Step 7 of 11
Tags 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:
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?
Press 1 to 4 to choose, Enter to check.
Step 8 of 11
Frameworks: 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?
Press 1 to 4 to choose, Enter to check.
Step 9 of 11
Build 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?
Press 1 to 4 to choose, Enter to check.
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.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.
Step 10 of 11
Where 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?
Press 1 to 4 to choose, Enter to check.
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.
Step 11 of 11
Challenges and recap
Fix closure in this cell. It is meant to return the roots plus everything they need, but it stops one level down.
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; 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
Put one boot of a Solo yard server with the loader in order.
- Call init on each service in that order, so the wrench is in StarterPack
- Add every dependency of the listed services and sort them, refusing a cycle
- Call start on each service with a table of its declared dependencies
- Players join and spawn holding the wrench
- Read PlaceRole and pick the Solo list from ROLES
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
Meet the criteria above, then record your own result. No test grades this check.
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
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?