Datastore retrying code review

Because I can’t seem to be able to force a datastore to fail on command, I would like to see if the community can check my code. I want it to be able to sent a Get request to the data store service to get all of the data (wrapped in pcall of course). If it fails, I want it to retry 6 times and kick the player after that if it still doesn’t get any data back.

Here is the code:

local DataStoreRetryCount = 0
local PlayerDataString = nil

while DataStoreRetryCount < 6 do
	local GetAsyncSuccess, RequestFail = pcall(function()
		PlayerDataString = DataStore:GetAsync(Key)
	if GetAsyncSuccess then
		warn("Get Async Request Failed: "..RequestFail..". Retrying...")
		DataStoreRetryCount = DataStoreRetryCount + 1

if DataStoreRetryCount == 6 then
	Player:Kick("Data could not be loaded. Please rejoin.")

Would this work in practice, and if not, what could be improved?

1 Like

You can force the request to fail by using error. Instead of using a while loop a numeric for loop would be the better option here. Lastly you can use pcall to return the player data.


local retryLimit = 6

local function getData(key)
	for i=1, retryLimit do
		local success, res = pcall(DataStore.GetAsync, DataStore, key)
		-- or
		--local success, res = pcall(function() return DataStore:GetAsync(Key) end)
		if success then return res end
		-- probably best to also include the key / data store name
		warn("Get Async Request Failed: ".. res ..". Retrying...")
	Player:Kick("Data could not be loaded. Please rejoin.")
1 Like

I’d like to also note it’s retrying only five times. Also, I do not think causing the datastore to error (unless absolutely necessary) would be good practice; your code is fine as is.


I think the causing the datastore to error is for testing only.

1 Like

The only reason that I want it to error is because I want to see what the code would do.

@kingdom5 exactly right

1 Like

Apologies, @kingdom5 and @RedDuck765, I thought you were trying to implement this in an actual game.


If you want the request to error, try running the script in an offline game; or disable Studio API access in Game Settings.