Global Leaderboard Review + Question

I’m working on a leaderboard service using OrderedDataStore. The full implementation is a bit larger, so I’ve reduced it to the main parts:

local stats = {}
local pending = {}
local lastGlobalValue = {}
local flushing = {}

local function getPeriodKey(periodType: string): string
	if periodType == "Monthly" then
		return os.date("!%Y_%m")
	elseif periodType == "Weekly" then
		return os.date("!%Y_W%W")
	end

	return "Global"
end

local function getStore(statName: string, periodType: string): OrderedDataStore
	local periodKey = getPeriodKey(periodType)

	local storeName = if periodType == "Global"
		then ("Leaderboard_%s_Global"):format(statName)
		else ("Leaderboard_%s_%s_%s"):format(statName, periodType, periodKey)

	return DataStoreService:GetOrderedDataStore(storeName)
end

local function flushGlobalMax(store: OrderedDataStore, key: string, value: number): boolean
	local success = pcall(function()
		store:UpdateAsync(key, function(oldValue)
			return math.max(oldValue or 0, value)
		end)
	end)

	return success
end

local function flushIncrements(statName: string, key: string, amount: number): boolean
	for _, periodType in {"Monthly", "Weekly"} do
		local success = pcall(function()
			getStore(statName, periodType):IncrementAsync(key, amount)
		end)

		if not success then
			return false
		end
	end

	return true
end

function LeaderboardService:TrackIncrement(statName: string, userId: number, amount: number)
	if amount > 0 then
		pending[userId] = pending[userId] or {}
		pending[userId][statName] =
			(pending[userId][statName] or 0) + amount
	end
end

function LeaderboardService:FlushPlayer(player: Player, profile: any): boolean
	local userId = player.UserId

	if flushing[userId] then
		return false
	end

	flushing[userId] = true

	-- Global stats
	for statName, config in pairs(stats) do
		local value = config.getValue(profile)
		local store = getStore(statName, "Global")

		local success = if config.type == "Max"
			then flushGlobalMax(store, tostring(userId), value)
			else pcall(function()
				store:SetAsync(tostring(userId), value)
			end)

		if not success then
			warn("Failed to flush", statName, userId)
		end
	end

	-- Weekly / Monthly increments
	local playerPending = pending[userId]
	pending[userId] = nil

	if playerPending then
		for statName, amount in pairs(playerPending) do
			if not flushIncrements(statName, tostring(userId), amount) then
				-- Re-add for retry
				pending[userId] = pending[userId] or {}
				pending[userId][statName] = amount
			end
		end
	end

	flushing[userId] = nil
	return true
end

Questions

  1. Is this approach safe with respect to race conditions and DataStore failures?
  2. Are there any important edge cases I’m missing?
  3. What’s the best way to prevent banned players from appearing on the leaderboard?

I was thinking about filtering them in GetTop(), but GetSortedAsync() only returns a limited page.

Any other feedback on the architecture or DataStore usage would be appreciated.

1 Like

Support me: My Group
One thing I noticed is that pending gets set to nil before all the increments finish. Id move the pending data into a seperate table first so new increments dont get mixed with the batch being flushed. For banned players, filtering GetSortedAsync results can cause you to get less players than expected since the page is limited. You could keep fetching pages until you have enough valid players. Also SetAsync can overwrite newer values from another server so UpdateAsync would be safer for global stats.