Why are people losing data?

So I have a pretty popular game but apparently some people are losing data? I think it happens when I shut down servers, this is the code:

--save player data
local function saveData(player)
	if data[player.UserId] and player.UserId ~= 0 then
		local success = nil
		local playerData = nil
		local attempt = 1

		repeat
			success, playerData = pcall(function()
				return dataBase:UpdateAsync(player.UserId, function()
					return data[player.UserId]
				end)
			end)

			attempt += 1
			if not success then
				warn(playerData)
				task.wait()
			end
		until success or attempt == 3

		if success then
			print("Data saved successfully")
		else
			warn("Unable to save data for player", player.UserId)
		end
	else
		warn("No session data for", player.UserId)
	end
end
Players.PlayerRemoving:Connect(function(player)
	saveData(player)
	data[player.UserId] = nil
end)

game:BindToClose(function()--if game shuts down
	if not RunService:IsStudio() then
		print("Shutting down")
		for index, player in pairs(Players:GetPlayers()) do
			task.spawn(function()
				saveData(player)
			end)
		end
	else
		print("Shutting down inside studio")
	end
end)

It looks like you are possibly attempting to save peoples data multiple attempts if the first fails. I’m not completely sure about the inner workings of roblox’s save system, but there may be a set amount of time you have to execute commands in Players.PlayerRemoving. If you overshoot that time, and your save isnt complete, you get data loss. I see why you want to do multiple attempts at saving, so I don’t know how you would continue in this situation. Best of luck, and congrats on your game.

Edit: You could possibly cache the users data to the server and then have your multiple attempts at saving it, and then discard from the server.

It’s more likely roblox servers crashing than you shutting down servers.
I don’t believe game:BindToClose() works if the server crashes.
Try autosaving and if that doesn’t work go to my next point.
(autosaving may still have data loss but it will mean less data loss)

Another common issue I see with data loss is that if their data doesn’t load properly and you attempt to save it they lose data. This usually happens when either

  1. They leave before their data loads.
    and/or
  2. Their data never loaded in the first place.

I would check if their data is equal to the starting data and if it is don’t save it.
(of course this can be a problem if the player plays a little bit while their data isnt loaded but it should work)