Best way to clear a datastore key upon game shutdown?

Hey y’all, I’m using datastores to store server metadata for my game, so players can join servers and see their information in a server browser. The thing is, as the title suggests, I can’t find an effective way to clear that server’s metadata from the datastore. I’m currently using game:BindToClose() to clear the key, but it doesn’t clear the metadata from the datastore, and all I see in the server browser is the entry of a server that’s dead.

Script is seen below:

local metadatastore = game.DataStoreService:GetDataStore("ServerMetadata")
local updating = false
local serveridx 

game:BindToClose(function()
	if serveridx then
		repeat task.wait()
			metadatastore:SetAsync(serveridx,nil)
			metadatastore:RemoveAsync(serveridx)
		until metadatastore:GetAsync(serveridx) == nil
	end	
end)

function update()
	if not updating then
		updating = true
		local Metadata = {}
		Metadata.IP = tonumber(game.PrivateServerId)
		Metadata.map = workspace.Map.Metadata:GetAttribute("MapName")
		Metadata.diff = workspace.Map.Metadata:GetAttribute("Difficulty")
		Metadata.plr = #game.Players:GetPlayers()
		for i = 1,100 do
			local s,e = pcall(function()
				if metadatastore:GetAsync(i) == nil then
					if serveridx then
						metadatastore:SetAsync(serveridx,Metadata)
						return "excellent"
					else
						serveridx = i
						metadatastore:SetAsync(i,Metadata)
						return "excellent"
					end	
				end
			end)
			if e == "excellent" then break end
		end
		updating = false
	end	
end

repeat wait() until workspace.Map:GetAttribute("Loaded") == true

game.ReplicatedStorage.UpdateMetadata.Event:Connect(update)

while task.wait(10) do
	update()
end

I’m aware, this is probably the least effective to make a server browsing system, but it does the trick(sort of?).
Simply put, it runs a for loop across the datastore(from 1 to 100, to find an empty key) every 10 seconds, and inserts the server’s metadata onto the found empty slot. It also saves the index of the key the data is in, so we can clear that entry when the game is about to shut down.

Another thing I want to add is, when I check the datastore entry of a dead server using a plugin, I see the “IP” element of the metadata table is gone, but everything else is there.

TL;DR: Yes, my current method works, but not every time. Sometimes, the entry gets cleared, and sometimes it doesn’t.

Apologies for this spaghetti of a topic, I’ll really appreciate it if anyone would tell me what might be causing the issue, or tell me a better way to make a server browsing system.

2 Likes