Datastore set taking forever to save

Hello,

In my game to change gamemodes, I save the players data before teleporting the player to the new server. Currently, this can take up to 30 seconds to save the players data then teleport which is annoying. Ive had a few people come to be about this aswell. I save the data beforehand to prevent any data issues with switching servers and getting data before its set.

Is there any way this can be sped up? Ive been told 5 seconds is how long you should wait before re attempting to set data, so im not sure how to speed this up.

function module.setPlayerData(player)
	local playerData = module.setDataToTemplate(player) -- returns user data in a table which can be stored
	local userId
	local playerName
	
	
	if typeof(player) == "number" then
		userId = player
		
        -- i probably should change this but its not a huge issue really
		for i, folder in pairs(ServerStorage.PlayerData:GetChildren()) do
			if folder.userId.Value == userId then
				playerName = folder.Name
				continue
			end
		end
	else
		playerName = player.Name
		userId = player.UserId
	end 
	
	if playerData and ServerStorage:WaitForChild("PlayerData")[playerName].level.Value ~= 0 then -- check to make sure there's actually data to save
		for i = 1,NUMBER_OF_ATTEMPTS do
			local success = pcall(function()
				PlayerDataStore:SetAsync(userId,playerData)
			end)
			if success == true then 
				continue 
			end
			wait(5.5)
		end
		for i = 1,NUMBER_OF_ATTEMPTS do
			local success = pcall(function()
				PlayerBackupDataStore:SetAsync(userId,playerData)
			end)
			if success == true then 
				return true 
			end
			wait(5.5)
		end
	elseif playerData and playerData.level.Value == 0 then
		return true
	end
	return nil
end

Also, if anyone knows how i can implement UpdateAsync, please tell me how i can do so. Im very confused on how UpdateAsync works.

Thanks to anyone who can help with this!

This might be your culprit. The continue should be a break, otherwise it just restarts the loop over until NUMBER_OF_ATTEMPTS.

Also for debug purposes, you should always at least print errors returned by pcall. It might make it more confusing if you just consume errors and assume there’s no user error.

2 Likes

I didnt ever think to break loops like that, let me try that out. Ive always thought it was continue.

Edit: breaking the loop did fix it, ill remember this for future datastores

Do you know how I could move this over to use UpdateAsync() instead of SetAsync()? I hear a lot of debate saying its much better to use but i have no clue how to use it.

1 Like

I’m not personally sure on the differences or benefits of one or the other. Maybe someone else can elaborate on that.

2 Likes

This thread goes into some details as why UpdateAsync() is preferred to SetAsync()

There is a tutorial at the very end of the thread if you still are not sure how to accomplish this.