Server sometime stopping before the script has time to finish saving Datastorage

Im having an issue with the Datastore service
So as soon as the player leaves, it saves 2 stores.
But sometime only the money one gets saved, and the other doesnt show any errors, it just doesnt execute

function setStore(plr,store,amount)
    print("SavedData: "..tostring(store))
    local Success, errorMessage = pcall(function()
        store:SetAsync(plr.UserId,amount)
    end)
    if not Success then
        error(errorMessage)
    end
end

function onPlayerLeave(plr)
    -- Delete printers & other stuff
    local money = plr.Storage.Money.Value
    local balance = plr.Storage.Balance.Value
    setStore(plr,moneyStore,money)
    setStore(plr,balanceStore,balance)
end

game.Players.PlayerRemoving:Connect(function(plr)
    onPlayerLeave(plr)
end)

In the onPlayerLeave() function, it should call the setStore() function twice for both stores… But half of the time, it only has time to save money and doesnt even fire the setStore() for balance.

18:07:33.750  SavedData: moneyStore  -  Server - ServerMain:33 18:07:33.934  SavedData: balanceStore  -  Server - ServerMain:33
``` Worked 

18:11:57.688  SavedData: moneyStore  -  Server - ServerMain:33 

Didnt work
And this is the output of line 2^

Is it possible that the server closes before is has time to finish setting up the datastores?
All I want is for both stores to save…

It is possible that the server closes in this case, if the player who left was the last remaining player. You could test using multiple to see if that’s the case. You could also try:

game:BindToClose(function()
	task.wait(5)
end)

to buy some seconds before that happens.

1 Like

Thanks! This is exactly what I was looking for! <3

First of all I’d recommend storing/loading stats from a table value so that you need only make single load/save requests to the DataStore for each player instance (this will benefit the efficiency of the script, alleviate stress/strain from Roblox’s DataStore API and mitigate the risk of overstepping DataStore allowance limits).

Secondly, if this is an issue exclusive to studio, then as suggested make use of the “BindToClose()” function to bind a function to the closing/shutting down of the server. This is necessary because the PlayerRemoving event often doesn’t fire while in studio (this is because in studio, the server is locally hosted and as such can be closed much faster than a regular Roblox server in a live-session of the experience).

If it is necessary for DataStore saving to take place in studio then switch the function bound to the server closing/shutting down to the following.

game:BindToClose(function()
	for _, plr in pairs(game.Players:GetPlayers()) do
		onPlayerLeave(plr) --calls the onPlayerLeave function for each player instance when the server closes/shuts down
	end
end)
1 Like