Why do players not always end up in the same server?

The title explains the issue, I have no idea

local memoryStore = game:GetService("MemoryStoreService")
local queue = memoryStore:GetSortedMap("Queue")

local tpService = game:GetService("TeleportService")

local minimum = 2
local maximum = 2

local placeId = 16359028002

local re = game.ReplicatedStorage.Events:WaitForChild("QueueRE")



function addToQueue(player)
	queue:SetAsync(player.UserId, player.UserId, 2592000)
end

function removeFromQueue(player)
	queue:RemoveAsync(player.UserId)
end


local cooldown = {}

local function teleportPlayers(queuedPlayers)

	local server = tpService:ReserveServer(placeId)

	local playersToTeleport = {}

	for _, data in pairs(queuedPlayers) do
		local userId = data.value
		local player = game.Players:GetPlayerByUserId(userId)
		if player then
			table.insert(playersToTeleport, player)
		end
	end

	tpService:TeleportToPrivateServer(placeId, server, playersToTeleport)
end

re.OnServerEvent:Connect(function(player, inQueue)
	
	if cooldown[player] then return end
	cooldown[player] = true
	
	if inQueue == "IN QUEUE" then
		pcall(addToQueue, player)
	elseif inQueue == "QUEUE" then
		pcall(removeFromQueue, player)
	end
	
	wait(1)
	cooldown[player] = false
end)



game.Players.PlayerRemoving:Connect(removeFromQueue)



local lastOverMin = tick()

while wait(1) do
	
	local success, queuedPlayers = pcall(function()
		return queue:GetRangeAsync(Enum.SortDirection.Descending, maximum)
	end)
	
	if success then
		
		local amountQueued = 0
		
		for i, data in pairs(queuedPlayers) do
				
			amountQueued += 1
		end
		
		if amountQueued < minimum then
			lastOverMin = tick()
		end

		local timeOverMin = tick() - lastOverMin
		
		if timeOverMin >= 20 or amountQueued == maximum then
			
			for i, data in pairs(queuedPlayers) do	
				teleportPlayers(queuedPlayers)
			end
		end
	end
end

1 Like