Customer System Issue

Can you guys help me to optimize this code it’s a simple customer npc system but when many customer in queue it’s very lag npc stuck in queue when triggered

local ServerStorage = game:GetService("ServerStorage")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local PhysicsService = game:GetService("PhysicsService")
local Players = game:GetService("Players")

local PlotsFolder = workspace:WaitForChild("Plots")
local clearEvent = ReplicatedStorage:WaitForChild("ClearCustomers")

local USERNAME = "MrMostKung"

local function iterPageItems(pages)
	return coroutine.wrap(function()
		local pagenum = 1
		while true do
			for _, item in ipairs(pages:GetCurrentPage()) do
				coroutine.yield(item, pagenum)
			end
			if pages.IsFinished then
				break
			end
			pages:AdvanceToNextPageAsync()
			pagenum += 1
		end
	end)
end

local usernames = {}
do
	local userId = Players:GetUserIdFromNameAsync(USERNAME)
	local friendPages = Players:GetFriendsAsync(userId)
	for item in iterPageItems(friendPages) do
		if item.Username ~= "Account Deleted" then
			table.insert(usernames, item.Username)
		end
	end
	print("Connections of " .. USERNAME .. ": " .. table.concat(usernames, ", "))
end

local function getHumanoid(model)
	return model:FindFirstChildOfClass("Humanoid")
end

local function moveTo(model, position)
	local hum = getHumanoid(model)
	if not hum then
		return false
	end
	hum:MoveTo(position)
	return hum.MoveToFinished:Wait()
end

local function setCollisionGroup(model, groupName)
	for _, d in ipairs(model:GetDescendants()) do
		if d:IsA("BasePart") then
			d.CollisionGroup = groupName
		end
	end
end

local function sortSlotsByNumber(parts)
	table.sort(parts, function(a, b)
		local na = tonumber(a.Name:match("%d+")) or 0
		local nb = tonumber(b.Name:match("%d+")) or 0
		return na < nb
	end)
end

local plotStates = {}

local function buildPlotState(plotModel)
	local system = plotModel:FindFirstChild("CustomerSystem")
	if not system then
		return nil
	end

	local state = {}
	state.plot = plotModel
	state.system = system
	state.spawnPoint = system:WaitForChild("SpawnPoint")
	state.frontPoint = system:WaitForChild("FrontPoint")
	state.leavePoint = system:WaitForChild("LeavePoint")
	state.exitPoint = system:WaitForChild("ExitPoint")

	local counterPart = system:WaitForChild("CounterPart")
	state.servePrompt = counterPart:WaitForChild("ServePrompt")
	state.servePrompt.Enabled = false
	state.serveToken = 0
	state.isServing = false

	local queueSlotsFolder = system:WaitForChild("QueueSlots")
	state.slots = queueSlotsFolder:GetChildren()
	sortSlotsByNumber(state.slots)

	state.queue = table.create(#state.slots)
	state.frontOccupant = nil

	return state
end

for _, plot in ipairs(PlotsFolder:GetChildren()) do
	local s = buildPlotState(plot)
	if s then
		table.insert(plotStates, s)
	end
end

assert(#plotStates > 0, "No plot states found")

local function findNextQueueSlot(state)
	local lastOccupied = 0
	for i = 1, #state.slots do
		if state.queue[i] ~= nil then
			lastOccupied = i
		end
	end
	local nextIndex = lastOccupied + 1
	if nextIndex <= #state.slots and state.queue[nextIndex] == nil then
		return nextIndex
	end
	return nil
end

local function assignCustomerToSlot(state, customer, slotIndex)
	customer:SetAttribute("QueueIndex", slotIndex)
	customer:SetAttribute("ArrivedAtSlot", false)
	state.queue[slotIndex] = customer
	moveTo(customer, state.slots[slotIndex].Position)
	customer:SetAttribute("ArrivedAtSlot", true)
end

local function shiftQueueForward(state)
	for i = 1, #state.slots - 1 do
		if state.queue[i] == nil and state.queue[i + 1] ~= nil then
			local cust = state.queue[i + 1]
			state.queue[i + 1] = nil
			assignCustomerToSlot(state, cust, i)
		end
	end
end

local function checkoutAndLeave(state, customer)
	if state.isServing then
		return
	end
	state.isServing = true
	state.serveToken += 1
	local token = state.serveToken

	state.currentCustomer = customer
	customer:SetAttribute("IsCheckingOut", true)
	state.servePrompt.Enabled = true

	local conn
	conn = state.servePrompt.Triggered:Connect(function(player)
		if state.serveToken ~= token then return end
		local ownerName = state.plot:FindFirstChild("IsOwner") and state.plot.IsOwner.Value
		if ownerName and ownerName ~= "" and player.Name ~= ownerName then return end
		if state.currentCustomer ~= customer then return end
		if not customer.Parent then return end

		state.servePrompt.Enabled = false
		if conn then conn:Disconnect() end

		task.spawn(function()
			moveTo(customer, state.leavePoint.Position)
			local idx = customer:GetAttribute("QueueIndex")
			if idx then state.queue[idx] = nil end
			shiftQueueForward(state)
			moveTo(customer, state.exitPoint.Position)
			customer:Destroy()
			if state.currentCustomer == customer then
				state.currentCustomer = nil
			end
			state.isServing = false
		end)
	end)

	task.spawn(function()
		while customer.Parent and state.serveToken == token do
			task.wait(0.2)
		end
		if state.serveToken == token then
			state.servePrompt.Enabled = false
			if conn then conn:Disconnect() end
			state.isServing = false
		end
	end)
end

local function goFrontAndWaitTurn(state, customer)
	while state.frontOccupant ~= nil and state.frontOccupant.Parent do
		task.wait(0.1)
	end
	state.frontOccupant = customer
	moveTo(customer, state.frontPoint.Position)
	while true do
		local slotIndex = findNextQueueSlot(state)
		if slotIndex then
			state.frontOccupant = nil
			return slotIndex
		end
		task.wait(0.2)
	end
end

local function applyRandomFriendAppearance(npc)
	local hum = npc:FindFirstChildOfClass("Humanoid")
	if not hum or #usernames == 0 then return end

	local pick = usernames[math.random(1, #usernames)]
	npc.Name = pick

	if pick ~= "Account Deleted" then
		local okId, friendUserId = pcall(function()
			return Players:GetUserIdFromNameAsync(pick)
		end)
		if okId and friendUserId then
			local okDesc, desc = pcall(function()
				return Players:GetHumanoidDescriptionFromUserIdAsync(friendUserId)
			end)
			if okDesc and desc then
				pcall(function()
					hum:ApplyDescription(desc)
				end)
			end
		end
	end
end

local function isPlotEligible(state)
	local isOpen = state.plot:FindFirstChild("IsOpen")
	local isOwner = state.plot:FindFirstChild("IsOwner")
	if not isOpen or not isOwner then return false end
	return (isOpen.Value == true) and (isOwner.Value ~= "")
end

local function getEligiblePlots()
	local eligible = {}
	for _, s in ipairs(plotStates) do
		if isPlotEligible(s) and findNextQueueSlot(s) then
			table.insert(eligible, s)
		end
	end
	return eligible
end

local function spawnCustomerAtRandomPlot()
	local eligible = getEligiblePlots()
	if #eligible == 0 then return false end

	local state = eligible[math.random(1, #eligible)]
	if not findNextQueueSlot(state) then return false end

	local npc = ServerStorage.CustomerNPC:Clone()
	npc:PivotTo(workspace.SpawnPoint.CFrame)
	npc.Parent = state.plot.CustomerKeep
	applyRandomFriendAppearance(npc)
	setCollisionGroup(npc, "Customers")

	local slotIndex = goFrontAndWaitTurn(state, npc)
	if not slotIndex then
		npc:Destroy()
		return false
	end

	assignCustomerToSlot(state, npc, slotIndex)
	return true
end

local function clearCustomers(state)
	if state.servePrompt then
		state.servePrompt.Enabled = false
	end
	state.currentCustomer = nil
	state.frontOccupant = nil
	state.isServing = false
	for i = 1, #state.queue do
		state.queue[i] = nil
	end
	local keep = state.plot:FindFirstChild("CustomerKeep")
	if keep then
		for _, npc in ipairs(keep:GetChildren()) do
			if npc:IsA("Model") then
				npc:Destroy()
			end
		end
	end
end

local SPAWN_INTERVAL = 1

task.spawn(function()
	while true do
		spawnCustomerAtRandomPlot()
		task.wait(SPAWN_INTERVAL)
	end
end)

for _, state in ipairs(plotStates) do
	task.spawn(function()
		while true do
			local front = state.queue[1]
			if front and front.Parent and front:GetAttribute("ArrivedAtSlot") and not front:GetAttribute("IsCheckingOut") then
				task.spawn(function()
					checkoutAndLeave(state, front)
				end)
			end
			task.wait(0.2)
		end
	end)
end

clearEvent.OnServerEvent:Connect(function(player)
	for _, state in ipairs(plotStates) do
		local plot = state.plot
		local ownerVal = plot:FindFirstChild("IsOwner")
		local openVal = plot:FindFirstChild("IsOpen")
		if not ownerVal or not openVal then continue end
		if ownerVal.Value ~= player.Name then continue end
		if openVal.Value == true then return end
		clearCustomers(state)
		return
	end
end)

Thank you

First, you should identify what is causing lag. I cannot do this just by looking at the code, at least not with certainty. The best way to do so is to use the microprofiler, which roblox made a really nice video on how to use it here

Alternatively, you could share a microprofiler dump, and I can analyze it

Did you find what the issue was? What was it?
I’m curious :P (and it can be useful if someone with a similar issue finds this threads)