Dataloss Issue - Unknown Cause? In need of help

I’ve been super stressed out, because I’ve been trying to rework my datastores to fix dataloss for hours. And I still can’t find a solution that prevents the occasional dataloss. Dataloss also doesn’t happen frequently enough for me to determine the cause or debug with prints. So I came here, hoping someone can check my code and point out anything that may seem amiss.


local function SavingStats(Player)
    local SavedPlayerStats = SaveStats(Player)
    local success, errormessage = pcall(function()
        local PlayerUserId = 'Player_'..Player.UserId
        if SavedPlayerStats ~= nil then
            myDataStore:SetAsync(PlayerUserId, SavedPlayerStats)
        end
    end)
    if success then
        print("Player Data successfully saved!")
    else
        print("There was an error when saving data")
        warn(errormessage)
    end
end

game.Players.PlayerRemoving:Connect(function(Player)
    local DoNotSave = game.ServerStorage.BoolChecks[Player.Name].DoNotSave
    if not DoNotSave.Value then
        local Save = game.ServerStorage.BoolChecks[Player.Name].Save
        SavingStats(Player)
        DoNotSave.Value = true
        repeat wait() until not game:GetService("Players"):FindFirstChild(Player)
        game.ServerStorage.StatsOfPlayers[Player.UserId]:Destroy()
        game.ServerStorage.BoolChecks[Player.Name]:Destroy()
        game.ServerStorage.PvP[Player.UserId]:Destroy()
        game.ServerStorage.PlayerAnimations[Player.Name]:Destroy()
    end
end)

game:BindToClose(function()
    for i, Player in pairs(game:GetService("Players"):GetPlayers()) do
        local DoNotSave = game.ServerStorage.BoolChecks[Player.Name].DoNotSave
        if not DoNotSave.Value then
            local Save = game.ServerStorage.BoolChecks[Player.Name].Save
            DoNotSave.Value = true
            SavingStats(Player)
        end
    end
end)

I should also note I do have a 5 minute autosave, with an autosave timer that starts as soon as the player joins, and this autosave timer does not resume, but restarts from 0 even if the player rejoins that same server. I was also able to determine data loss happens even when the player leaves the game before the 5 minute time period. So I’m pretty sure it isn’t due to the autosave. Though please let me know if it’s a possibility and if I should also show the autosave code.

Ok so I’ve had this problem aswell in the past and ended up fixing it entirely with instead of looping through all of the players in the game you should not update/ setasync or update async till the game either closes or the player leaves, store all their data in a dictionary with the key as their Id and you can update change or do anything with that value and when the player leaves or the game shuts down you loop through the table instead of the players and that works 100% of the time for me

msg me if you need help