DEV Community

CyberMax
CyberMax

Posted on Originally published at cybermaxtools.com

Saving player data safely with DataStore in Roblox: three rules and a small manager

Lost saves are the most expensive bug a Roblox game can have, and they nearly always come from the same few mistakes. This is a small data manager built around three rules that rule those mistakes out, with template defaults, migrations and a shutdown save.

The short version

Keep each player's data in memory on the server and follow three rules. Never create a profile when the load failed, so a blank one can never be saved over real data. Never write without a loaded profile. Save with UpdateAsync and a version number, and refuse the write when the stored version is newer than yours. Add retries, an autosave and BindToClose around those rules.

Set it up in Studio

  1. In Game Settings > Security, turn on Enable Studio Access to API Services so DataStores work in Studio.
  2. In ServerScriptService, add a ModuleScript named DataManager and paste the first block.
  3. Add a Script next to it and paste the second block. It starts the manager and shows how to change data.
  4. Edit TEMPLATE to hold your own fields. Read with DataManager.get and change with DataManager.update from other server scripts.
  5. Test: join, wait for coins, leave, rejoin. Then stop the server with a player in it to test the shutdown save.

The code

ServerScriptService/DataManager (ModuleScript)

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")

local store = DataStoreService:GetDataStore("PlayerData_v1")

-- Every field a player can have, with its default. Raise `schema` when you rename or reshape a field.
local TEMPLATE = { schema = 2, coins = 0, gems = 0, inventory = {}, settings = { music = true } }
local AUTOSAVE_SECONDS = 120
local SESSION = if game.JobId ~= "" then game.JobId else "studio" -- which server wrote a save

local DataManager = {}
local profiles = {} -- [player] = { data = table, version = number, dirty = boolean, saving = boolean }
local inFlight = 0 -- saves currently talking to the DataStore

local function deepCopy(value)
    if type(value) ~= "table" then
        return value
    end
    local copy = {}
    for k, v in value do
        copy[k] = deepCopy(v)
    end
    return copy
end

-- Add fields that exist in the template but not in an older save. Never removes or overwrites anything.
local function reconcile(data, template)
    for key, default in template do
        if data[key] == nil then
            data[key] = deepCopy(default)
        elseif type(default) == "table" and type(data[key]) == "table" and next(default) ~= nil then
            reconcile(data[key], default)
        end
    end
    return data
end

-- One function per old schema number: it turns that schema into the next one.
local MIGRATIONS = {
    [1] = function(data) -- schema 1 called gems "diamonds"
        data.gems = data.gems or data.diamonds or 0
        data.diamonds = nil
    end,
}

local function migrate(data)
    for step = data.schema or 1, TEMPLATE.schema - 1 do
        if MIGRATIONS[step] then
            MIGRATIONS[step](data)
        end
    end
    data.schema = TEMPLATE.schema
    return data
end

-- DataStore calls fail now and then. Try 4 times, waiting 2, 4 and 8 seconds in between.
local function retry(fn)
    local lastError
    for attempt = 1, 4 do
        local ok, result = pcall(fn)
        if ok then
            return true, result
        end
        lastError = result
        if attempt < 4 then
            task.wait(2 ^ attempt)
        end
    end
    return false, lastError
end

function DataManager.load(player)
    local ok, stored = retry(function()
        return store:GetAsync("u_" .. player.UserId)
    end)
    if not ok then
        -- RULE 1: a failed load is not a new player. No profile is created, so nothing can be saved over the real data.
        warn("Load failed for", player.Name, stored)
        player:Kick("Your data could not be loaded, so nothing was changed. Please rejoin.")
        return nil
    end
    if player.Parent ~= Players then
        return nil -- left while the load was in progress
    end
    stored = stored or { version = 0, data = deepCopy(TEMPLATE) }
    profiles[player] = {
        data = reconcile(migrate(stored.data), TEMPLATE),
        version = stored.version or 0,
        dirty = false,
        saving = false,
    }
    return profiles[player].data
end

function DataManager.get(player)
    local profile = profiles[player]
    return profile and profile.data
end

-- Change data through this, so the manager knows there is something to save.
function DataManager.update(player, change)
    local profile = profiles[player]
    if not profile then
        return false
    end
    change(profile.data)
    profile.dirty = true
    return true
end

function DataManager.save(player)
    local profile = profiles[player]
    if not profile or not profile.dirty or profile.saving then
        return false -- RULE 2: no loaded profile, no write
    end
    profile.saving = true
    profile.dirty = false -- changes made while the save is in flight mark it dirty again
    inFlight += 1

    local stale = false
    local ok, err = retry(function()
        return store:UpdateAsync("u_" .. player.UserId, function(current)
            stale = false
            if current and (current.version or 0) > profile.version and current.session ~= SESSION then
                stale = true -- RULE 3: another server saved newer data; do not overwrite it
                return nil
            end
            return { version = profile.version + 1, session = SESSION, data = profile.data }
        end)
    end)

    if ok and not stale then
        profile.version += 1
    else
        profile.dirty = true
        warn("Save not written for", player.Name, if stale then "newer data exists on another server" else err)
    end
    profile.saving = false
    inFlight -= 1
    return ok and not stale
end

function DataManager.start()
    Players.PlayerAdded:Connect(DataManager.load)
    for _, player in Players:GetPlayers() do
        task.spawn(DataManager.load, player)
    end

    Players.PlayerRemoving:Connect(function(player)
        local profile = profiles[player]
        while profile and profile.saving do
            task.wait(0.1) -- let an autosave that is in flight finish first
        end
        DataManager.save(player)
        profiles[player] = nil
    end)

    task.spawn(function()
        while true do
            task.wait(AUTOSAVE_SECONDS)
            for player in profiles do
                task.spawn(DataManager.save, player)
            end
        end
    end)

    -- The server is closing: keep it open (Roblox allows up to 30 seconds) until every profile is written.
    game:BindToClose(function()
        local deadline = os.clock() + 25
        while os.clock() < deadline do
            local busy = false
            for player, profile in profiles do
                if profile.dirty and not profile.saving then
                    task.spawn(DataManager.save, player)
                end
                busy = busy or profile.dirty or profile.saving
            end
            if not busy and inFlight == 0 then
                break
            end
            task.wait(0.2)
        end
    end)
end

return DataManager
Enter fullscreen mode Exit fullscreen mode

ServerScriptService/Main (Script)

local Players = game:GetService("Players")
local DataManager = require(script.Parent:WaitForChild("DataManager"))

DataManager.start()

-- Example: 10 coins a minute. Every change goes through DataManager.update.
while true do
    task.wait(60)
    for _, player in Players:GetPlayers() do
        DataManager.update(player, function(data)
            data.coins += 10
        end)
    end
end
Enter fullscreen mode Exit fullscreen mode

The three rules that prevent data loss

Most "my data reset" reports come from one sequence: GetAsync fails or is slow, the script treats the player as new, and the blank profile is saved over the real one. Rule 1 and rule 2 make that impossible: a failed load kicks the player with no profile, and save() does nothing without one.

Rule 3 covers two servers. A player who rejoins quickly can be loaded by server B before server A has finished saving. Each save stores a version number; a server that finds a higher version written by another server knows its copy is out of date and does not overwrite it.

Adding a field later

When you add a field to TEMPLATE, every existing save is missing it. reconcile() fills in missing fields with their defaults when a player loads, and never touches fields that are already there.

When you rename or reshape a field, raise TEMPLATE.schema and add a function to MIGRATIONS under the old schema number. Old saves are upgraded one step at a time as their players join, so you never have to rewrite every key in the DataStore.

Why UpdateAsync and not SetAsync

SetAsync writes whatever you give it. UpdateAsync hands you the value that is stored right now and lets you decide, which is the only way to check a version before writing. Returning nil from the function cancels the write.

Roblox may call that function more than once, so it must not do anything except compute the new value: no granting items, no yielding.

Saving on shutdown

When a server closes, PlayerRemoving alone is not reliable. game:BindToClose keeps the server open for up to 30 seconds; this manager uses that time to write every profile that still has changes and waits until those writes have finished.

Good to know

  • The dirty flag saves requests: a player who changed nothing since the last save is not written again. Roblox limits writes per minute per server, and a shutdown with many players is exactly when you need the budget.
  • What this does not do is hold a lock, so two servers could both load the same player in a short window; the version check then stops the older copy from winning, but changes made on that server are not saved. Session locking closes that window by letting only one server own a profile at a time.
  • Never store Instances, functions or mixed tables (number and string keys together) in a DataStore. Stick to numbers, strings, booleans and plain tables.

Questions

Why kick the player when the load fails?

Because the alternative is letting them play on a blank profile, which they will take for lost progress, and which is one bug away from being saved. A kick with a clear message loses nothing.

How often should I autosave?

Every two to five minutes is plenty. Saving on every change wastes the request budget and can hit the limit of one write per key every six seconds.

Does this work with leaderstats?

Yes. Treat leaderstats as a display: after DataManager.update changes a value, copy it to the IntValue. Do not read leaderstats back into your data.

Should I use ProfileStore or another library instead?

For a serious game, a maintained library with session locking is a good choice. Writing this once is still worth it: you will know what the library is doing for you.

If you would rather not write it

Start free: the free Studwright demo: the kit's free modules running in your browser, nothing to install. The full kit is on the same page. Studwright's SaveData module adds the session lock this tutorial leaves out, so one server owns a save at a time, and the kit includes 15 more tested modules: Receipts, Codes, DailyRewards, Leaderboard, Inventory, Currency and others. Free demo first, then the kit: https://cybermaxtools.com/store/studwright/?utm_source=devto&utm_medium=article&utm_campaign=rbxtut-how-to-save-player-data-safely-with-data

Roblox is a trademark of Roblox Corporation. CyberMax is not affiliated with or endorsed by Roblox.


Published automatically by CyberMax. Every number above comes from the linked public data; nothing is estimated.

Top comments (0)