DataStore Saving Issue

Hey everyone!
I’ve been having some small issues with saving recently. I’m noticing that often times, even a print statement in my saving function won’t print anything. I’m pretty sure it has to do with me testing in studio, as the game closes before the code can run. It did seem to work when using game:BindToClose() instead of game.Players.PlayerAdded. Is there anyway to circumvent this or is that just the way it is?
My code:

Server Script:

local module = require(script.SavingModule)
local DS = game:GetService("DataStoreService"):GetDataStore("Another Test")

module:New(DS)

game.Players.PlayerAdded:Connect(function(plr)
	local Coins = Instance.new("IntValue", plr)
	Coins.Name = "Coins"
	Coins.Value = 10
	
	local data = module:RetrieveSave(plr)
	
	if not data then return end
	
	Coins.Value = data.Coins
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local data = {
		Coins = plr.Coins.Value
	}
	
	module:Update(data, plr)
end)

ModuleScript:

local DataStore


local module = {}

function module:New(DS: DataStore, Data_Names)
	DataStore = DS
end

function module:Update(DTS, plr)
	local data ={}
	
	for i,v in DTS do
		if type(v) ~= "number" and type(v) ~= "string" then
			warn("Data type of "..tostring(v), type(v).." is not a supported data type and couldn't be saved")
			continue
		end
		data[i] = v
	end
	
	
	local success, err = pcall(function()
		DataStore:SetAsync(plr.UserId, data)
	end)
	
	if err then print("Failed to retrieve save of "..plr..": "..err) return end
	
	print(data) -- not printing
	return data
end

function module:RetrieveSave(plr)
	local data
	
	local success, err = pcall(function()
		data = DataStore:GetAsync(plr.UserId)
	end)
	
	if err then print("Failed to retrieve save of "..plr..": "..err) return end
	
	if not data then print(plr.Name.." has no data") return end
	
	return data
end

return module

Can anybody see anything wrong with my code?

Yea - you’ll want to keep that. In addition to what you have, you should go through the players and save their data when the server shuts down with BindToClose()

game:BindToClose(function()
	for _, player in ipairs(Players:GetChildren()) do
	local data = {
		Coins = plr.Coins.Value
	}	
	module:Update(data, plr)
	end 
end)

Here’s the problem with that: doing that in studio results in the game warning me I’m sending too many requests

You should have throttling in your datastore requests, certainly.

For that particular warning in studio, it’s up to you. (I personally ignore it)
It’s happening because of making the request at the same time.
i.e. the last player is leaving, and the server is shutting down.
You could make it so that if only 1 player is on the server and is leaving, ignore the PlayerRemoving call - or some other work around.