Weird issue with specifically PlayerRemoving and BindToClose

hi, ive been trying to solve this one issue for around a week: PlayerRemoving and BindToClose saving doesn’t seem to work for me. my (test) script is below, and for some reason the increase in x.Value += 1 only seems to happen around 40% of the time, completely at random. however, if i include a print line after it it will still print.

things ive tried to rule out:

  • nothing wrong with the GetAsync, manually tested by setting it with a different script and Get worked
  • references seem okay, at least each has been tested
  • if I run SetAsync elsewhere it also works. just the specific combination of it being in PlayerRemoving and BindToClose
  • i have tested both removing and bind separately, both appear the same, where the += 1 works sometimes but not others
  • i have turned off vpn, and my connection is pretty fast
  • have followed the advice from these posts: [SOLVED!] PlayerRemoving function doesn't always work and How to properly save player data in data stores upon server close, neither worked
  • for the script below it is the only script in a blank world, so its not interference from others

if you test this and it works (i.e. print line upon joining increases each time) please say, then itd probably be a problem only on my laptop lol

local players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("PlayerDataStore")

game.Players.PlayerAdded:Connect(function(player)
	local x = Instance.new("IntValue", player)
	x.Name = "x"
	x.Value = DataStore:GetAsync(player.UserId) or 1
	print (x.Value)
end)

game.Players.PlayerRemoving:Connect(function(player)
	local x = player:FindFirstChild("x")
	if x then 
		x.Value += 1
		print("fired")
		local success, err = pcall(function()
			DataStore:SetAsync(player.UserId, x.Value)
		end)
		if success then
			print("saved")
		else
			print("failed: " .. tostring(err))
		end
	end
end)

game:BindToClose(function()
	for _, player in pairs(players:GetPlayers()) do
		local x = player:FindFirstChild("x")
		if x then
			local success, err = pcall(function()
				DataStore:SetAsync(player.UserId, x.Value)
			end)
			if not success then
				warn("failed for " .. player.Name .. ": " .. tostring(err))
			end
		end
	end
end)

sorry if im submitting this wrong, always open to feedback ^^

edit - will be testing out OtherWRLDly’s solution and then updating when i can. the weirdest thing about this all is that this exact format of saving script genuinely worked no flaws a few months ago, but i havent seen any relevant updates to the async after searching so far,

Could it be that the player object is being destroyed while this is happening, and if it’s not fast enough, the object is gone before it can be stored?

I tested .PlayerRemoving myself and im pretty sure it confirmed what I said above, a few times when i left, my Player’s parent was the Players, different times my Player’s parent was nil. I don’t recommend parenting important data do something thats about to be destroyed

i recommend just using this: ProfileStore - Save your player data easy (DataStore Module)

creating your own takes a lot longer and there are a TON of edge cases you have to check for

might want to try updateasync instead of setasync

I can see a couple of potential issues here.

PlayerRemoving and BindToClose will both fire when the last player leaves, since the server begins shutting down at that point. This means you’re effectively saving twice per player at the worst possible time, which can cause DataStore throttling or requests not finishing before shutdown.

I tested your script in an empty baseplate and it worked, so the logic itself is fine. However, if you have other scripts also using PlayerRemoving or BindToClose, they could be adding more DataStore requests and creating a queue, which increases the chance of failures.

This looks like a timing issue rather than a logic bug. During shutdown, DataStore requests don’t always have enough time to complete unless you explicitly yield.

Why don’t you try this and tell me how it goes? I basically make a table of active players to know which ones to remove or add and I save with BindToClose, I don’t save with PlayerRemoved. This is an example if you only want BindToClose, but keep in mind it won’t save when players leave, but when server shuts down. However from what I’ve tested it works, BindToClose fires.

local players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("PlayerDataStore")

local activePlayers = {}

local function save(player)
	local x = player:FindFirstChild("x")
	if not x then return end

	local success, err = pcall(function()
		DataStore:SetAsync(player.UserId, x.Value)
	end)

	if success then
		print("saved for", player.Name)
	else
		warn("failed for", player.Name, err)
	end
end

players.PlayerAdded:Connect(function(player)
	activePlayers[player] = true

	local x = Instance.new("IntValue")
	x.Name = "x"
	x.Parent = player

	local success, data = pcall(function()
		return DataStore:GetAsync(player.UserId)
	end)

	x.Value = (success and data) or 1
	print("loaded:", x.Value)
end)

-- DO NOT REMOVE THEM FROM activePlayers
-- players.PlayerRemoving:Connect(function(player)
--     activePlayers[player] = nil
-- end)

game:BindToClose(function()
	for player, _ in pairs(activePlayers) do
		local x = player:FindFirstChild("x")
		if x then
			x.Value += 1
		end

		save(player)
		task.wait(0.2)
	end

	task.wait(5)
end)

So right now how can we fix PlayerAdded? We need to add a delay so it doesn’t make uneccessary double saves for the last player in-game before a server is shut down, but we also need to save for players who leave mid-game.

local players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("PlayerDataStore")

local saving = {} -- debounce table

local function save(player)
	if saving[player] then return end -- prevent double save
	saving[player] = true

	local x = player:FindFirstChild("x")
	if not x then 
		saving[player] = nil
		return 
	end

	local success, err = pcall(function()
		DataStore:SetAsync(player.UserId, x.Value)
	end)

	if success then
		print("saved for", player.Name)
	else
		warn("failed for", player.Name, err)
	end

	saving[player] = nil
end

players.PlayerAdded:Connect(function(player)
	local x = Instance.new("IntValue")
	x.Name = "x"
	x.Parent = player

	local success, data = pcall(function()
		return DataStore:GetAsync(player.UserId)
	end)

	x.Value = (success and data) or 1
	print("loaded:", x.Value)
end)

players.PlayerRemoving:Connect(function(player)
	local x = player:FindFirstChild("x")
	if x then
		x.Value += 1
	end

	save(player)
end)

game:BindToClose(function()
	for _, player in ipairs(players:GetPlayers()) do
		save(player)
		task.wait(0.2) -- avoid throttling
	end

	task.wait(3) -- allow requests to finish
end)

I haven’t tested it much, but these are some ideas you can use.

ah i think ive tried checking for player existence right before the save? in any case wouldnt a player not existing throw a visible error in output?

oh i appreciate it! i just tried it with playerremoving disabled and bindtoclose on though, and it sometimes would show the warn. i think maybe it was the rate limit, but it was being weird with how it showed up which threw me off haha
thank you for the help!

i checked resources on it and i dont think update is the right case here, since what i need this for is simple and will almost always have a change to it, thank you though

you don’t really want to make your own data saving system unless its for ordereddatastores for leaderboards. otherwise you really should use profilestore.

Okay, here’s something I coded for my game today, and honestly I think it’s a really nice way to do things. It also fixed my DataStore throttling.

You can have one BindToClose module script which gathers data saving functions from multiple scripts, then sends over all that data to that module script.

If you have multiple scripts that save data, this is useful. How to migrate?

  1. PlayerRemoving persists in each script, that’s not a problem.
  2. BindToClose gets completely removed and replaced with a custom function.
  3. It collects the neccessary functions and triggers them in module.

Shutdown Manager (Module > ServerScriptService)

local ShutdownManager = {}

local Players = game:GetService("Players")

local callbacks = {}
local shuttingDown = false

function ShutdownManager.Register(func)
	table.insert(callbacks, func)
end

function ShutdownManager.IsShuttingDown()
	return shuttingDown
end

game:BindToClose(function()
	shuttingDown = true

	for _, player in ipairs(Players:GetPlayers()) do
		for _, func in ipairs(callbacks) do
			local success, err = pcall(function()
				func(player)
			end)

			if not success then
				warn("Shutdown error:", err)
			end
		end

		task.wait(0.2)
	end

	task.wait(3)
end)

return ShutdownManager

That’s the main module which collects all BindToClose functions you had in your previous scripts and sends them over - if you had just one, then no problem, this also works, but is much better.

Example usage in a ServerScript where you save data:

local ShutdownManager = require(game.ServerScriptService.ShutdownManager)

local alreadySaved = {}

local function savePlayer(player)
	-- your saving logic here
end

game.Players.PlayerRemoving:Connect(function(player)
	if alreadySaved[player] then return end
	alreadySaved[player] = true

	savePlayer(player)
end)

ShutdownManager.Register(function(player)
	if alreadySaved[player] then return end
	alreadySaved[player] = true

	savePlayer(player)
end)

Saving data with retry example

local function saveWithRetry(userId, data, retries)
	retries = retries or 3

	for i = 1, retries do
		local success, err = pcall(function()
			DataStore:SetAsync(userId, data)
		end)

		if success then return true end

		warn("Save failed:", err)
		task.wait(2)
	end

	return false
end

Example of updating data

local function savePlayer(player)
	pcall(function()
		DataStore:UpdateAsync(player.UserId, function(old)
			old = old or {}

			old.Coins = player:GetAttribute("Coins") or 0
			old.Level = player:GetAttribute("Level") or 1

			return old
		end)
	end)
end

How to check if we already saved data for a player, so we don’t trigger BindToClose.

local alreadySaved = {}

local function trySave(player, saveFunc)
	if alreadySaved[player] then return end
	alreadySaved[player] = true

	saveFunc(player)
end

Hope this helps you!

You can use UpdateAsync instead of SetAsync because it is safer.

With SetAsync, you are directly overwriting the value. If multiple servers save at the same time or a request fails, you can end up losing data because it doesn’t consider what was previously stored.

UpdateAsync works differently. It gives you the previous value, lets you modify it, and then saves it. Roblox will also retry the operation automatically if there are conflicts, which makes it much more reliable.

Another important thing is that UpdateAsync still works even if the data doesn’t exist yet — you can just do old = old or {} (or 0) and create it safely.

So in general:

  • SetAsync = overwrite (simple, but less safe)
  • UpdateAsync = modify existing data (safer, recommended for most systems)