I am attempting to create a ModuleScript where it will put DataStore requests into a Queue. This is to prevent reaching the request limit of DataStore and receiving an error.

The method I have tried below is probably very inefficient. (And probably does not work) I also ran into problems when I tried to adapt this code to GetAsync as I need to return a value.

So: Anyway I can make this more efficient? And how can I adapt it to work with GetAsync.

local Remote = {}

local DataService = game:GetService("DataStoreService")


local function MaximumRequests()
	return 60 + game.Players.NumPlayers * 2 --Double check
end


 
-----SetQue-----
local SetQue = {}			
local SetRequests = 0

spawn(function()
	while wait(0) do
		if #SetQue >= 1 then
			SetRequests = SetRequests + 1
			if SetRequests < MaximumRequests() then
				DataService:GetDataStore(SetQue[1][1]):SetAsync(SetQue[1][2],SetQue[1][3])
				table.remove(1)
			end
		end
	end
end)

spawn(function()
	while wait(65) do
		SetRequests = 0
	end
end)

local function InTable(Tab,...)
	for _,n in pairs(Tab) do
		if n == {...} then
			return true
		end
	end
end

------Functions----------

function Remote:SetPlayerData(Key,Value,Player,Callback)
	table.insert(SetQue,{Key,Value,Player})
	spawn(function()
		repeat wait(0) until not  InTable(SetQue,Key,Player)
	end)
end

function Remote:GetPlayerData(Key,Player)
	return FakeData[Key] --Return data 
end

return Remote