Help with server leader system

I’m trying to apply a server to be the leader if no leader is found or if that server is a leader but no players are in it. My problem is that it sometimes doesn’t remove the leader after that server has no players.

When all players in a server that is a leader teleports to another game, it sometimes doesn’t apply a new leader.

local module = {}

local MemoryStoreService = game:GetService("MemoryStoreService")
local LeaderLock = MemoryStoreService:GetSortedMap("LeaderLock")

local MessagingService = game:GetService("MessagingService")

local serverId = game.JobId
local isServerHost = false

local expirationTime = 1000
local leaderLockTime = 60

local function ApplyLeader()
	local success, currentLeader = pcall(function()
		return LeaderLock:GetAsync("CurrentLeader")
	end)

	if not currentLeader or (currentLeader and currentLeader == serverId) then
		print("applying for leader")

		local success, err = pcall(function()
			LeaderLock:SetAsync("CurrentLeader", serverId, leaderLockTime)
		end)

		if success then
			isServerHost = true

			local dataToSend = {
				Value = serverId,
				MessageFrom = "Apply Leader"
			}

			print("Sending message: ", currentLeader, serverId)

			MessagingService:PublishAsync("UpdateLeader", dataToSend)

			print("Server host: "..tostring(isServerHost))

			return true
		end
	end

	if currentLeader ~= serverId then
		isServerHost = false

		print("No host | ", currentLeader, " ~ ", serverId)
	end
end

ApplyLeader()

local function RemoveLeader()
	local success, err = pcall(function()
		LeaderLock:RemoveAsync("CurrentLeader")
	end)

	if success then
		print("Removed leader")
	else
		warn("Failed to remove leader: ", err)
	end
end

MessagingService:SubscribeAsync("UpdateLeader", function(message)
	local data = message.Data
	print("Message: ", data.Value, "|", serverId, "|", data.MessageFrom)

	if data.Value and data.Value ~= serverId then
		isServerHost = false
		print("Set no host")

	elseif data.Value == serverId then
		isServerHost = true
		print("Set host")

	elseif not data.Value then
		print("Apply leader")
		ApplyLeader()
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	if #game.Players:GetPlayers() <= 1 then
		if isServerHost then
			isServerHost = false
			RemoveLeader()
		end

		local dataToSend = {
			Value = false,
			MessageFrom = "Removing"
		}

		MessagingService:PublishAsync("UpdateLeader", dataToSend)
	end
end)

return module

Could you possibly use game:BindToClose() for when the server is closing to replace the leader?

Isn’t that only for servers closing on shutdown?

Not sure, but I thought it got called when the server shut down (So, when it is shutdown by a developer or shuts down due to no players)