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
- Is this approach safe with respect to race conditions and DataStore failures?
- Are there any important edge cases I’m missing?
- 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.