Am I handling DataStores efficiently?

DataStoreSystem.rbxl (18.0 KB)
I’ve never handled my DataStores very efficiently in the past, so I’ve attempted a new DataStore system after browsing the DevForum for some solutions. After about an hour, I’ve come up with this system that uses pcall to check for errors in loading the DataStore, and to retry every 60 seconds if it fails.

I’m intentionally saving all data on one key so I can loop through the Data with ease.
I’m unsure if this is an efficient way to handle DataStores, or if there is even a better solution.

(for those of you that don’t want to download the place file, the code is below)

Script
local Players = game:GetService('Players')
local DataStoreService = game:GetService('DataStoreService')

local AlphaDataStore = DataStoreService:GetDataStore('AlphaPlayers')
local KeyVersion = 'Version1'

function Save(Player)
	local Data
	local Success, Error = pcall(function()
		Data = AlphaDataStore:GetAsync(KeyVersion)
	end)
	if Success then
		print('Successfully loaded DataStore')
		if Data == nil then -- DataStore is empty, insert a blank table
			print('DataStore is empty')
			Data = {}
		end
		for i,v in pairs(Data) do
			print(v)
		end
		for i,v in pairs(Data) do
			if Player.UserId == v then
				print(Player.Name..' is already saved!')
				return true -- Player is already saved here
			end
		end
		-- If we're still running the code at this point, it means the player isn't saved in this DataStore- so get saving!
		table.insert(Data, Player.UserId)
		AlphaDataStore:SetAsync(KeyVersion, Data)
		print('Saved '..Player.Name..' to AlphaPlayers '..KeyVersion..'!')
		return true
	else
		warn('DataStore Error! Error: '..Error) -- DO NOT SAVE! Retry..
		return false
	end
end

Players.PlayerAdded:Connect(function(Player)
	local Saved = Save(Player)
	if not Saved then
		repeat wait(60) warn('Something while trying to save '..Player.Name..' to AlphaPlayers! Retrying...') Saved = Save(Player) until Saved
	end
end)
2 Likes

Is there a reason why you don’t do a pcall on the SetAsync?

1 Like

Its probably a good idea to use tables for the ‘queue’ and to cancel the previous request if a more recent save request comes in from the same player, as you may find an older save accidentally overwriting a newer save, and you don’t really want multiple of these loops going on for one particular player.

3 Likes