Roblox Server Shutdown Handling: BindToClose, Soft Shutdowns, and Saving Every Player Before the Server Dies

What happens to the last ninety seconds of a player's progress when the Roblox server holding it goes away? If you have shipped a game with persistent data, you have probably already lost some of it — a rare drop that never saved, a purchase that rolled back, or a leaderboard score that reset after an update restart.
Many of those losses trace back to the shutdown path, which is code that rarely gets tested at full capacity. This guide walks through the BindToClose budget, parallel final saves, closing the doors on trades and purchases, and soft-shutdown teleports — the mechanics that decide whether every player makes it out with their data intact.
Scope note. This guide assumes your data layer already uses session locking, so two servers never write the same player at once — if it does not, start with our Roblox session locking guide, because everything below sits on top of that lock.
What Happens When A Roblox Server Shuts Down?
A Roblox server closes for a handful of reasons: the last player leaves, you restart servers to push an update, Roblox rebalances or maintains its fleet, or the process crashes outright. Each of those paths treats your scripts differently, and the differences are where data goes missing.
On a graceful close, the engine stops accepting new players, removes the ones still connected, and invokes every function you registered with game:BindToClose. Keep in mind that you should not rely on the order in which PlayerRemoving handlers and BindToClose callbacks fire — design as if they overlap, because in practice they do.
On a crash, none of that happens. The process ends, the connections drop, and anything held only in server memory is gone.
This is why a sound shutdown strategy has two layers. The first is a final save for graceful closes, and the second is periodic autosaves plus lock expiry for everything else.
How Long Does BindToClose Give You?
Roblox waits up to 30 seconds for all bound functions to finish before it terminates the server. That window is shared — every BindToClose callback you register runs concurrently, and the clock covers all of them together rather than each one individually.
Roblox gives every server up to 30 seconds after shutdown begins to finish all BindToClose callbacks. Budget about 25 seconds for saves and keep the last five as margin, because the server is killed at 30 either way.
That said, 30 seconds is a ceiling, not a promise of useful time. Data store calls made during shutdown still go through the same request queues and throttles as calls made mid-session, so a server that was already near its write budget enters shutdown with a backlog.
For this reason, compute a hard deadline the moment BindToClose fires — os.clock() + 25 is a sensible default — and pass it to every save routine. Anything still running at the deadline gets abandoned deliberately, with a log line, instead of being cut off mid-request by the engine.
Which Shutdowns Actually Run BindToClose?
Before writing the save path, it helps to be precise about which events it covers. The table below maps each shutdown cause to whether BindToClose fires and what actually protects the player's data in that case.
| Shutdown cause | BindToClose runs? | What protects the data |
|---|---|---|
| Last player leaves | Yes | PlayerRemoving save, with BindToClose waiting for it to commit |
| Restart for an update | Yes | Parallel final saves plus an optional soft shutdown |
| Platform maintenance or rebalancing | Generally yes | Parallel final saves within the 30-second window |
| Crash, out-of-memory kill, or host failure | No | Autosave interval and session-lock expiry |
| Stopping a Studio play session | Yes | Same path, with a shortened deadline |
All of the above points to the same conclusion: BindToClose is a best-effort final flush. The autosave interval sets your worst-case loss on a crash, and the session lock's expiry decides how quickly a player can load into a new server afterward.
No. A hard crash, an out-of-memory kill, or a host failure skips BindToClose entirely. Periodic autosaves bound the lost progress, and session-lock expiry lets the next server load the data safely.
How Do You Run Final Saves In Parallel?
A common shutdown bug in Roblox codebases is a sequential save loop inside BindToClose. It works in testing with two players and quietly fails at full capacity, because each save waits for the previous one to finish.
The arithmetic is unforgiving. A healthy UpdateAsync typically returns in a few hundred milliseconds, but at 50 players and roughly 600 milliseconds per save — before a single retry — a sequential loop consumes the entire 30-second window.
Run final saves in parallel. Spawn one save task per loaded session with task.spawn, then have BindToClose wait until the in-flight table drains or the deadline passes.
Moreover, the loop should be keyed on your own session cache rather than on Players:GetPlayers(). By the time BindToClose runs, some players may already be gone from the Players service, and their final saves may already be in flight from a PlayerRemoving handler.
Key the final save on your session cache, not Players:GetPlayers(). When BindToClose runs, some players may already be removed, and their saves may already be in flight from PlayerRemoving.
Here's a minimal version of the pattern, with an in-flight table that prevents double writes and a shared deadline that every save respects:
```lua local Players = game:GetService("Players") local RunService = game:GetService("RunService") local DataStoreService = game:GetService("DataStoreService") local store = DataStoreService:GetDataStore("PlayerData") local SHUTDOWN_BUDGET = 25 -- seconds; the engine stops the server at 30 local sessions = {} -- [userId] = { data = table, dirty = boolean } local inFlight = {} -- [userId] = true while a final save is running local closing = false -- other systems read this before mutating state local function finalSave(userId, deadline) local session = sessions[userId] if not session or inFlight[userId] then return end if not session.dirty then sessions[userId] = nil return end inFlight[userId] = true local snapshot = session.data local attempt = 0 while os.clock() < deadline do attempt += 1 local ok, err = pcall(function() store:UpdateAsync(tostring(userId), function(current) -- verify the session lock here (see the session-locking guide) return snapshot end) end) if ok then sessions[userId] = nil break end warn(("save %d attempt %d failed: %s"):format(userId, attempt, tostring(err))) local backoff = math.min(0.25 * 2 ^ attempt, deadline - os.clock()) task.wait(math.max(backoff, 0)) end inFlight[userId] = nil end Players.PlayerRemoving:Connect(function(player) finalSave(player.UserId, os.clock() + SHUTDOWN_BUDGET) end) game:BindToClose(function() closing = true local budget = RunService:IsStudio() and 3 or SHUTDOWN_BUDGET local deadline = os.clock() + budget for userId in pairs(sessions) do task.spawn(finalSave, userId, deadline) end while next(inFlight) and os.clock() < deadline do task.wait(0.1) end end) ```Note that task.spawn resumes the save function immediately, so the in-flight flag is set before the first yield. As a result, the wait loop at the bottom of BindToClose never sees an empty table by accident, and a save that PlayerRemoving started a moment earlier is waited on rather than duplicated.
The same structure works whether your data lives in one key per player or is split across several stores. If you shard data into multiple keys, spawn one task per key rather than one per player — key layout itself is covered in our Roblox data stores guide.
Retries, Throttling, And The Write Budget
Parallel saves solve the latency problem, but they introduce a budget problem. At the time of writing, Roblox documents the per-server write budget for UpdateAsync, SetAsync, and IncrementAsync as 60 plus 10 per player each minute, and a single key accepts one write roughly every 6 seconds.
For a 30-player server, that works out to approximately 360 writes per minute. A shutdown that fires 30 player saves at once fits comfortably — unless the server also writes guild data, leaderboards, and analytics on the way out, or spent the previous minute draining the same budget with autosaves.
Keep the following rules in mind when you size the final flush:
- Check the budget at runtime.
DataStoreService:GetRequestBudgetForRequestTypewith the SetIncrementAsync request type tells you how many writes are available right now. Log it when BindToClose fires so you can see whether shutdown starts in the red. - Prioritize player saves. Player progress goes first, while ordered-store leaderboards, telemetry, and cosmetic stats go second and only if the deadline allows. A missed leaderboard update is an annoyance, whereas a missed inventory write is a support ticket.
- Cap retries with the deadline, not a count. Exponential backoff starting at about 250 milliseconds works well, but every wait should be clamped to the time left before the deadline. A retry that would land after second 30 is worth nothing.
- Skip clean sessions. If a player's data has not changed since the last successful autosave, there is nothing to flush. A dirty flag on each session can cut shutdown writes substantially in games where many players idle.
Taken together, these rules keep the final flush inside both the time window and the request budget. If you are unsure where your write volume comes from during normal play, our Roblox performance profiling guide covers how to instrument data store calls alongside frame time and memory.
Closing The Doors: Trades, Purchases, And Rewards
A final save is only as good as the state it captures. If the server keeps processing trades, purchases, and rewards while saves are running, the snapshot you write may already be stale — or worse, half of a two-player trade may land while the other half does not.
Therefore, the first line of every shutdown handler should flip a server-wide closing flag. Every system that mutates persistent state checks that flag and refuses new work once it is set.
Here's how that flag applies to the systems most likely to cause trouble:
- Trades. Reject new trade requests and cancel any trade that has not reached its commit step. If you run escrow-style trades, as described in our Roblox inventory trading guide, the commit itself should be one atomic write that either completes before the deadline or never starts.
- Developer product purchases. Have ProcessReceipt return
Enum.ProductPurchaseDecision.NotProcessedYetwhile the server is closing. Roblox keeps the receipt and retries it on the player's next server, which is far safer than granting currency into a save that may never land. - Rewards and drops. Stop awarding timed rewards, quest completions, and loot once the flag is set. The player will not notice a reward that arrives two minutes later in a new server, but they will notice one that vanished.
Stop accepting trades and purchases the moment shutdown begins. Returning NotProcessedYet from ProcessReceipt makes Roblox retry the receipt on the player's next server instead of risking a lost grant.
In addition, if your experience coordinates state across servers — parties, guild banks, global events — consider broadcasting a short closing notice. A lightweight publish, as covered in our cross-server messaging guide, lets peer servers stop waiting on a server that is about to disappear.
How Do Soft Shutdowns Work?
When you publish an update and restart servers, every connected player is disconnected at once. A soft shutdown replaces that disconnect with a pair of teleports, so players land in a fresh server running the new version with little more than a loading screen in between.
A soft shutdown teleports everyone into a temporary reserved server when an update closes the old one, then sends them back to fresh public servers. Players see a loading screen instead of a disconnect.
The mechanics are straightforward. The closing server teleports every player into a single newly reserved server, and that holding server, which starts on the new version, waits briefly before sending each player back to the public matchmaking pool for the place.
Roblox's own Migrate To Latest Update option in the Creator Dashboard covers part of this flow, and it is worth testing before you maintain your own. That said, a custom soft shutdown gives you control over timing, teleport data, and the holding-server experience, which matters for games with long sessions or in-progress matches.
Here's a compact implementation using TeleportOptions with ShouldReserveServer:
```lua local Players = game:GetService("Players") local RunService = game:GetService("RunService") local TeleportService = game:GetService("TeleportService") local isHoldingServer = game.PrivateServerId ~= "" and game.PrivateServerOwnerId == 0 if isHoldingServer then -- new version: give final saves a moment to commit, then rejoin the public pool Players.PlayerAdded:Connect(function(player) task.wait(5) pcall(function() TeleportService:TeleportAsync(game.PlaceId, { player }) end) end) end game:BindToClose(function() if RunService:IsStudio() or isHoldingServer or game.PrivateServerOwnerId ~= 0 then return end local players = Players:GetPlayers() if #players == 0 then return end local options = Instance.new("TeleportOptions") options.ShouldReserveServer = true options:SetTeleportData({ softShutdown = true }) pcall(function() TeleportService:TeleportAsync(game.PlaceId, players, options) end) end) ```Notice that the soft-shutdown callback and the save callback are registered separately. Because BindToClose callbacks run concurrently, the teleport and the saves proceed in parallel, and the 30-second window covers both.
This is also where session locking earns its keep. A player can arrive in the holding server before their final save from the old server has committed, so the destination must wait for the lock to release rather than loading stale data — the teleport side of that handoff is covered in depth in our Roblox TeleportService guide.
Before shipping a soft shutdown, account for a few edge cases:
- Private servers. Players in a VIP server would be teleported out of it, so the example skips the soft shutdown when
game.PrivateServerOwnerIdis non-zero. Those players simply rejoin the owner's server after the restart. - Reserved match servers. The holding-server check above treats every reserved server as a holding server. If your game already uses reserved servers for matches, identify the holding server through the softShutdown teleport data instead.
- Teleport failures. TeleportAsync can fail for individual players, so wrap the call in pcall and listen to TeleportService.TeleportInitFailed. Rely on the final save regardless — a player who fails to teleport simply disconnects with their data already flushed.
How Do You Test A Shutdown Path?
Shutdown code runs rarely in production and almost never during development, which is exactly why it rots. Fortunately, every piece of it can be exercised on purpose.
Here's a testing routine that covers the paths that matter:
- Studio stop. BindToClose fires when you stop a play session in Studio, and Studio waits on it. Shorten the deadline with
RunService:IsStudio()during normal iteration, but keep a toggle that runs the full path so you can step through it. - Multi-client local servers. Start a local server with four or more clients from the Test tab, then close the server window. Confirm in the output that each session saves exactly once and that the in-flight table drains before the deadline.
- Live restart on a test place. Publish to a separate test place, join with several accounts, and restart servers from the Creator Dashboard. Verify that soft-shutdown teleports land, that data loads cleanly in the new server, and that no lock conflict outlives its expiry.
- Simulated throttling. Temporarily add an artificial delay of two or three seconds inside each save attempt. Then confirm that the deadline logic abandons late saves cleanly rather than hanging until the engine kills the process.
After all, a shutdown path that has only ever run in a two-player Studio session has not really been tested. The conditions that break it — 40 or 50 players, a throttled budget, a slow teleport — only show up when you create them deliberately.
How Do You Know Your Shutdown Path Is Working?
Observability closes the loop. At minimum, log four values every time BindToClose fires: the number of sessions in the cache, the write budget at entry, the number of saves that committed before the deadline, and the elapsed time when the in-flight table drained.
Ship those values somewhere you can query across servers rather than leaving them in the server output, which disappears with the process. Many teams forward them through HttpService to an external log pipeline, or write a compact summary to a dedicated data store that they later read through the Roblox Open Cloud APIs.
Once the data is flowing, two signals tell you most of what you need to know. A rising count of abandoned saves means the budget or the deadline is too tight, while a drain time that creeps toward 25 seconds means your player count or save size has outgrown the current design.
Overall, a well-instrumented shutdown path turns data loss from an anecdote in a support channel into a number you can watch. For a broader view of how servers start, scale, and stop, see our Roblox server architecture guide.
Frequently Asked Questions
The questions below cover the shutdown edge cases that the main walkthrough touches only briefly. Each answer stands on its own, so you can jump to the one that matches the bug in front of you.
Does BindToClose run when a Roblox server crashes?
No. BindToClose only runs on a graceful close. A crash, out-of-memory kill, or host failure ends the process immediately, so periodic autosaves and session-lock expiry are the only protection against loss.
Why does Roblox Studio hang when I stop a play test?
BindToClose runs when you stop a Studio play session, and Studio waits on it. Check RunService:IsStudio() and shorten the deadline to a few seconds so Stop returns promptly during normal iteration.
How do I stop PlayerRemoving and BindToClose from saving the same player twice?
Give each session an in-flight flag. PlayerRemoving starts the save and sets the flag, and BindToClose skips any session already flagged and waits for it, so each player gets exactly one final write.
What happens to a developer product purchase made while the server is closing?
Set a closing flag in BindToClose and have ProcessReceipt return Enum.ProductPurchaseDecision.NotProcessedYet while it is set. Roblox keeps the receipt and retries it the next time that player joins a server.
How often should a Roblox game autosave player data?
Many games autosave every 60 to 180 seconds, and only when data is dirty. The documented write budget is 60 plus 10 per player each minute, and one key accepts a write about every 6 seconds, so tighter loops throttle.
Ship The Shutdown Path Before You Need It
Every Roblox server eventually closes, and the only question is whether it takes player progress with it. A 25-second deadline, parallel saves keyed on the session cache, a closing flag on trades and purchases, and a soft shutdown for updates cover the graceful cases, while autosaves and session locking cover the rest.
If you are auditing an existing data layer, start with the shutdown path, because it often has never run at full capacity. Pair this guide with our session locking guide and data stores guide, and you will have the full lifecycle of a player save covered from first load to final flush.


