Feedback on datastore

i need some feedback on my datastore, is it safe? what should I change/add to it?
thanks.

local DataStoreService = game:GetService("DataStoreService")
local Datastore = DataStoreService:GetDataStore("AnOrdinaryDataStore")

local Gamemodule = require(script.Gamemodule)

local HttpsService = game:GetService("HttpService")

local function waitForRequestBudget(requestType)
	local currentBudget = DataStoreService:GetRequestBudgetForRequestType(requestType)
	while currentBudget > 1 do
		currentBudget = DataStoreService:GetRequestBudgetForRequestType(requestType)
		wait(6)
	end
end

local function save(player)
		
	local StatsToSave = {}

	for i,v in ipairs(player:WaitForChild("Stats"):GetChildren()) do
		StatsToSave[v.Name] = v.Value 
	end
		
	repeat
		waitForRequestBudget(Enum.DataStoreRequestType.UpdateAsync)
		local s, err = pcall(Datastore.UpdateAsync, Datastore, player.UserId.."_Stats", function()
			return StatsToSave
		end)
	until s
		
end

game.Players.PlayerAdded:Connect(function(player)
	local Stats = Gamemodule.CreateStats(player) -- a function in a module to creat stats so there wont be so much lines of code
	
	local leaderstats = Stats[1]
	local Overall = Stats[2]
	local Values = Stats[3]
	local stats = Stats[4]
	
	local StatsData 
	local s, e = pcall(function()
		StatsData = Datastore:GetAsync(player.UserId.."_Stats")
	end)

	if s then 
		if StatsData then
			for i,v in pairs(StatsData) do
				stats:FindFirstChild(i).Value = v
				print(i, v)
			end
		end
	else 
		warn(e)
	end
	
	coroutine.wrap(function()
		while wait(60) do
			save(player)
		end
	end)()
end)

game.Players.PlayerRemoving:Connect(function(player)
	local s, e  = pcall(function()
		save(player)
	end)

	if not s then
		warn(e)
	end
end)

game:BindToClose(function() 
	if game:GetService("RunService"):IsStudio() then
		wait(1)
	else
		for _, player in ipairs(game.Players:GetPlayers()) do 
			coroutine.wrap(function()
				local s, e  = pcall(function()
					save(player)
				end)

				if not s then
					warn(e)
				end
			end)()
		end
	end
end)

I’m not entirely sure the usefulness of implementing this yourself. From what I understand the datastore itself will yield and automatically do this if you try using UpdateAsync back to back too much.


Other than that, have you thought about using update async in order to check if the new value is greater than the old

Datastore.UpdateAsync:Connect(function(oldValue)
    if newValue > oldValue then
        return new
    else
        return nil -- returning nil means the save is canceled
    end
end)

Potentially implementing a check like that could be beneficial (for certain values like level which can only go up)