Lesson 2 of 11
Lifetimes: signals, Trove and leak hunting
Hunt memory leaks in Beacon Yard: the lastSwing table that never forgets a player, Player objects the engine keeps by default, a hand-written Signal, a cleanup scope per player and per object with Trove as the library choice, memory categories, and a 200-player leak test.
By the end you can
- Find the per-player tables and connections in Beacon Yard that outlive the player
- Write a Signal and a cleanup scope, and give every player and object one scope that owns what it creates
- Tag memory by system and read a Luau heap snapshot for growth
- Prove a fix with a test that joins and removes 200 players and expects nothing left behind
Before this: Architecture for a big codebase: lifecycles, dependencies, frameworks, Events, signals and the task library, Performance: MicroProfiler, memory, network
Step 1 of 11
The table that remembers every player
CombatService refuses a swing that comes less than 0.4 seconds after the last one. To know when the last one was, it keeps a table keyed by player:
local lastSwing: { [Player]: number } = {}
local previousSwing = lastSwing[player]
if previousSwing ~= nil and now - previousSwing < SWING_GAP then
return "rejected"
end
lastSwing[player] = now
Search the file for anything that removes an entry. There is nothing. Every player who ever swings stays in lastSwing until the server shuts down, and a key in a table keeps the whole Player object it points to in memory, with everything that object references.
A Solo server stays up from Friday evening to Sunday night. 3,000 different players visit and each swings the wrench at least once. On Sunday night 12 players are online. How many entries does lastSwing hold?
Step 2 of 11
Audit the yard: who cleans up and who forgets
Most of Beacon Yard's services already clean up. SettingsService keeps a per-player cooldown too, and drops it the moment the player leaves:
Players.PlayerRemoving:Connect(function(player: Player)
lastChange[player] = nil
end)
Every module-level table keyed by Player at m14-ship, checked against its PlayerRemoving handler:
| Table | Service | Cleared when the player leaves? |
|---|---|---|
lastSwing | CombatService | No |
tried | BadgeAwards | Yes |
sessions, memoryOnly, coinStats | DataService | Yes, in onPlayerRemoving |
loading | DataService | Yes, when the profile load ends |
hits on each drone and crawler | DroneService, CrawlerService | Yes |
waiting | QueueService | Yes |
lastChange | SettingsService | Yes |
CoinService has a seen table too, but it is created inside each coin's function and dies with the coin, so it lives exactly as long as it should.
Tables are half the story. The performance guide warns that after a player leaves, the engine does not destroy their Player object or character by default, so connections to them, such as CharacterAdded, keep their functions and everything those functions reference in memory1. CombatService and DataService both connect to CharacterAdded for every player who joins:
game:GetService("Players").PlayerAdded:Connect(function(player: Player)
player.CharacterAdded:Connect(function()
task.defer(give, player)
end)
The guide's fix is one setting: turn on Workspace.PlayerCharacterDestroyBehavior, and the engine destroys old characters and the Player object when the player leaves, which disconnects every event on them2. Beacon Yard's project file does not set it.
You enable PlayerCharacterDestroyBehavior and change nothing else. Is the lastSwing leak fixed?
Press 1 to 4 to choose, Enter to check.
Step 3 of 11
Your own events: a Signal in twenty lines
Roblox events (RBXScriptSignal) cover engine things. Between your own modules you want the same shape: Connect, Fire, Disconnect. A Signal is a list of functions. Here is a working one:
Every Connect adds a function to a list that lives as long as the signal. A handler you forget to disconnect is a leak of exactly the kind lastSwing is. One difference from engine events: this Signal calls handlers immediately, while a place with Workspace.SignalBehavior set to Deferred runs engine handlers at the next resumption point3, as Events, signals and the task library showed. GoodSignal and RbxUtil's Signal behave like this cell.
Why does Fire loop over table.clone(handlers) and check entry.connected?
Press 1 to 4 to choose, Enter to check.
Step 4 of 11
One bag per lifetime
The fix for every leak above is the same habit: whatever you create because something exists, register its cleanup in a bag owned by that thing, and empty the bag when it goes. Libraries call the bag a Trove, Janitor or Maid; this lesson calls it a scopeCleanup scope (Trove, Janitor, Maid)An object that collects everything created for one lifetime (connections, instances, table entries, threads) and cleans it all up in one call when that lifetime ends.Think of it as a hotel room's checkout list: everything the guest started is written down, and checkout works through the list..
| In the picture | In Roblox |
|---|---|
| A guest checking in | PlayerAdded, or a crawler spawning |
| Writing the key card and minibar tab on the room's list | scope:Add a connection, scope:Track a table entry |
| Housekeeping working through the list at checkout | PlayerRemoving calls scope:Clean |
| A key card nobody deactivated | CombatService.lastSwing keeping an entry for every player who ever swung |
Think of a hotel room's checkout list. When a guest checks in and takes a key card, opens a minibar tab or books a wake-up call, the front desk writes it on the room's list. At checkout, housekeeping works through the list: deactivate the card, close the tab, cancel the call. Nobody has to remember what this particular guest did, because it is all on the list.
Think of it as A hotel room's checkout list: every key card, tab and booking the guest starts is written down, and checkout works through the list
A scope needs three moves: Add an item (a function to call, a connection to disconnect, an instance to destroy), Track a table entry so it is set now and cleared later, and Clean. This one cleans newest first, because later items often depend on earlier ones:
A teammate writes scope:Track(lastSwing, player, now) inside trySwing, on every swing, instead of once at join. What happens?
Press 1 to 4 to choose, Enter to check.
Step 5 of 11
Objects have lifetimes too
Players are one lifetime. Every crawler, drone, coin and round is another. Instance:Destroy() disconnects the events of that instance and its descendants, so a crawler's own Humanoid and Path connections go with it1. What does not go with it is a connection the crawler made to something that outlives it, such as RunService.Heartbeat or Players.PlayerRemoving. That connection keeps its function, and the function keeps the crawler's table, alive.
At m14-ship, each crawler loop stops when its alive flag goes false. A crawler scope would make that rule visible: whatever a crawler connects or spawns goes into its scope, and the scope is cleaned when the model is destroyed. Trove's AttachToInstance does that last step for you4. Beacon Yard has no crawler scope yet, even at m15-scale, so try it as an extension once the player scopes below work.
A new crawler type connects these when it spawns. Which one still runs, and keeps the crawler's data in memory, after the crawler's model is destroyed?
Press 1 to 4 to choose, Enter to check.
Step 6 of 11
See it: memory categories and heap snapshots
You cannot fix what you cannot see. In a live or test server, the Developer Console's Memory tool shows three numbers worth watching: LuaHeap growing over time suggests a leak, InstanceCount growing suggests instances your code still references, and PlaceScriptMemory breaks memory down by script1.
The Luau heap tool goes deeper. Create Snapshot records what Luau has allocated; take one, let twenty players join and leave, take another, and compare. Its Memory Categories view groups memory by category, which defaults to the script's name. debug.setmemorycategory("CombatService") tags what the current thread allocates from then on with a name you choose, and debug.resetmemorycategory() puts it back56. Every Beacon Yard service is a ModuleScript under one boot script, so tagging each service's work by name is what turns one big row into one row per service.
The catch is the word thread. A category belongs to the thread that set it, not to the module. The m15-scale boot script tags each service's init and start, but an event handler runs in a new thread the engine starts, so it falls back to the script's name. lastSwing is written by the Swing handler, so a wrapper around start alone would put its growth under the boot script's row, not under CombatService. That is why m15-scale tags inside the handler too:
-- Memory a swing allocates shows under CombatService in the
-- Developer Console, not under the remote's default category.
-- The event thread ends here, so an error cannot leak the label.
debug.setmemorycategory("CombatService")
CombatService.trySwing(player, origin, direction, seenSeq, alpha)
debug.resetmemorycategory()
DroneService does the same inside its own loop.
The rule: set the category at the top of every long-lived loop or handler whose memory you want to see, and reset it at the end.

Select a numbered pin, or a row below, to read what it marks.
The Luau heap's Memory Categories view, with a row per tagged service.
Which readings suggest a leak on a server whose player count stays steady at about 12?
Press 1 to 5 to choose, Enter to check.
Step 7 of 11
Prove it: a leak test
A leak fix without a test comes back the next time someone adds a table. The test is simple: send many fake players through join and leave, then count what is left. Real Player objects cannot be created in a test, but the services only use them as table keys, so a plain table stands in:
The level 3 challenge does this properly: fake players join a fake CombatService with a swing map, a hit map and a CharacterAdded connection each, some leave while others are still joining, and at the end every table must be empty and every connection gone.
Why can a plain table such as { Name = "YardTester1" } stand in for a Player in this test?
Press 1 to 4 to choose, Enter to check.
Step 8 of 11
Pick your bag
Cleanup helpers studios use
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Trove (RbxUtil) | Add, Connect, Clean, Destroy, Extend for child troves, AttachToInstance. Wally sleitnick/trove 1.8.0, MIT, actively maintained (changed this week). | A small, well-known bag with good docs; the build-along installs it. | Cleans in the order items were added and runs cleanup functions with task.spawn, so do not rely on order. |
| Janitor | A cleanup bag with keyed items, so you can replace or remove one entry by name. MIT, maintained (last change July 2026). | You often swap one item, such as the current round's connection, without cleaning the rest. | A larger API than Trove. |
| Maid (Nevermore) | The original pattern, part of the Nevermore packages. MIT, actively maintained. | Codebases already on Nevermore. | Comes with Nevermore's install route and conventions. |
| Your own scope | About 40 lines: Add, Track, Clean, like the cells in this lesson. | You want exact control of order and no dependency. | You maintain it and its tests. |
| PlayerCharacterDestroyBehavior | An engine setting that destroys old characters and the Player object when a player leaves. | Every game: it removes a whole class of connection leaks. | Does nothing for entries in your own tables. |
Your round code swaps the current round's connections every drill but keeps the rest of the player's scope. Which helper fits that best?
Press 1 to 4 to choose, Enter to check.
Step 9 of 11
Build along: a scope for every player
You build this in your own copy of the finished game. First pass the level 3 challenge below.
wally.tomlwally.lockdefault.project.jsonsrc/server/PlayerScopes.luausrc/server/CombatService.luausrc/server/init.server.luautests/scale.luau
Add
Trove = "sleitnick/trove@1.8.0"under[dependencies]and runwally installto update the lockfile.PlayerScopesrequires Trove the first time it needs to create one.You should see wally install finishes and Packages contains Trove.
Index Troves by player in
PlayerScopes.For. Implementreleaseto remove and destroy the Trove, andcountto count live Troves. Instart, connectPlayerRemovingand calltask.defer(PlayerScopes.release, player)so profile and strike saves can see the entries before cleanup. Services that use scopes listPlayerScopesindeps.You should see For returns one Trove per player. The leave handler defers its cleanup one step.
Use
PlayerScopes.For(player)inonPlayerAdded. Register a cleanup withscope:Addand connectCharacterAddedwithscope:Connect. Keep cleanup registration outsidetrySwing. The boot wrapper sets the memory category for each service'sinitandstartonly, so wrap thetrySwingcall in theSwinghandler withdebug.setmemorycategory("CombatService")anddebug.resetmemorycategory().You should see CombatService registers one lastSwing cleanup and one scoped CharacterAdded connection per join.
Add
"PlayerCharacterDestroyBehavior": "Enabled"to Workspace's$propertiesindefault.project.json. Verify the value in Studio.You should see Workspace shows PlayerCharacterDestroyBehavior set to Enabled after Rojo sync.
In
tests/scale.luau, use a different fake player for each of 200 iterations. Add a cleanup throughFor, callrelease, and comparecountbefore and after the loop. Then take a Studio server heap snapshot before and after real clients leave, and check that the CombatService category no longer grows.You should see The leak_scope test runs 200 cleanups and finishes with its original Trove count.
Step 10 of 11
Where the checkout picture breaks
A hotel's night audit spots a room still marked occupied with no guest. What tells you that a Beacon Yard server is holding on to players who left?
Press 1 to 4 to choose, Enter to check.
Where does it break?“A hotel room's checkout list: every key card, tab and booking the guest starts is written down, and checkout works through the list” is a good picture of cleaning up per-player and per-object state. Where does it stop being true?
It breaks here. A hotel's night audit notices a room with no guest; Luau never reports what it could not free, so you need heap snapshots and leak tests. A checkout list has one line per thing the guest did, but a scope gets a line per Add call, so adding on every swing makes the list itself grow. And one stray reference anywhere keeps the whole guest checked in.
The true model. Every lifetime (player, object, round) owns a scope; code registers each cleanup once, where the thing is created, and the scope is cleaned where the lifetime ends. The engine setting PlayerCharacterDestroyBehavior handles connections on the Player itself; your tables are yours to clear.
The picture breaks in a second place. A hotel list has one line per thing the guest did. A scope has one line per Add call, so code that adds on every swing makes the list itself grow, as the track-every-swing question showed. And one stray reference anywhere, a single key in a table or a closure in a live connection, keeps the whole guest checked in.
Step 11 of 11
Challenges and recap
This Signal skips a handler. Fire the drill twice: the tutorial hint should show once and the HUD should update both times. Fix Fire so all three tests pass.
Level 1, Apprentice
Challenge
Fix Fire in the once-fix cell.
- 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
- Fire calls every handler connected when it started, even if one removes itself
- The Once handler runs on the first Fire only
- All three assertions in once-fix pass
Put one player's lifetime in order once the build-along is done.
- Swings write lastSwing[player] without adding anything to the scope
- CombatService adds one cleanup for lastSwing and connects CharacterAdded through the scope
- PlayerAdded: PlayerScopes.For(player) creates the player's Trove
- PlayerRemoving defers release one step so save handlers can still see the entries. Release clears lastSwing and disconnects CharacterAdded
Level 2, Builder
Challenge
Find the leak with the heap tool before you fix it, then show it gone. There is no Luau test for this one: the proof is the pair of snapshot comparisons.
- Start from
- The game at milestone m14 (download)
Done means
- Two Luau heap snapshots from a Studio Server & Clients test, before and after the same join-and-leave cycles, on the m14-ship game
- A note naming the category or object type that grew, and lastSwing as the cause
- The same two snapshots after the build-along, with no growth in the CombatService category
Meet the criteria above, then record your own result. No test grades this check.
Level 3, Professional
Challenge
Write the three tools in challenges/work/player_scope.luau. The written solution is challenges/solutions/lifetimes-and-leaks.md. In Play, run game.ServerScriptService.RunGameTests:Invoke("lifetimes-and-leaks", "leaks-scopes") 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("lifetimes-and-leaks", "leaks-scopes")in the server command bar. Copy the pass code from Output.
Done means
- newSignal connects in order, disconnects once, supports Once, and survives changes made while it fires
- newScope adds functions, connections and destroyables, tracks table keys, cleans newest first and only once
- newPlayerScopes gives one scope per player and releases it safely
- After 200 fake players join and leave, every per-player table is empty and every connection is gone
- challenges/lifetimes-and-leaks.luau prints TEST PASS for every check
Retiring the analogy
You no longer need “a hotel room's checkout list: every key card, tab and booking the guest starts is written down, and checkout works through the list”. Every lifetime (player, object, round) owns a scope; code registers each cleanup once, where the thing is created, and the scope is cleaned where the lifetime ends. The engine setting PlayerCharacterDestroyBehavior handles connections on the Player itself; your tables are yours to clear.
Recap
- CombatService.lastSwing never removes a player, so a long-running server keeps every player who ever swung; the other per-player tables at m14-ship are cleared on PlayerRemoving.
- By default the engine does not destroy a Player who leaves, so connections to it stay alive; Workspace.PlayerCharacterDestroyBehavior fixes connections but not your table entries.
- A Signal is a list of functions: loop over a copy in Fire, and every Connect needs a matching Disconnect.
- Give every lifetime (player, crawler, round) a scope: register cleanup once where the lifetime starts, clean it where it ends. Trove, Janitor and Maid are ready-made scopes.
- Watch LuaHeap and InstanceCount and compare Luau heap snapshots by memory category. debug.setmemorycategory tags a thread, so set it inside every long-lived loop or handler, not only around init and start.
- Prove the fix with a test that joins and removes many fake players and expects every table empty.
Cleaning up per-player and per-object state is a hotel room's checkout list: every key card, tab and booking the guest starts is written down, and checkout works through the list, until a hotel's night audit notices a room with no guest; Luau never reports what it could not free, so you need heap snapshots and leak tests. A checkout list has one line per thing the guest did, but a scope gets a line per Add call, so adding on every swing makes the list itself grow. And one stray reference anywhere keeps the whole guest checked in.
Queued for review
- You enable PlayerCharacterDestroyBehavior and change nothing else. Is the lastSwing leak fixed?
- Why does Fire loop over table.clone(handlers) and check entry.connected?
- A teammate writes scope:Track(lastSwing, player, now) inside trySwing, on every swing, instead of once at join. What happens?
- A new crawler type connects these when it spawns. Which one still runs, and keeps the crawler's data in memory, after the crawler's model is destroyed?
- Which readings suggest a leak on a server whose player count stays steady at about 12?