Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Data Stores and Services

Saving Player Data: leaderstats, PlayerAdded and BindToClose

Build a complete save system: create leaderstats, load on PlayerAdded, save on PlayerRemoving and BindToClose, merge defaults with saved data and retry failed requests.

You know the basics of DataStores. Now it is time to put them into a complete save system that loads when a player joins, keeps their values while they play, and saves when they leave or when the server shuts down. This is the part of an experience that players notice most when it breaks, so we will build it carefully.

The Roblox code is shown read-only. The runnable examples are JavaScript stand-ins that reproduce the logic: merging defaults, a retry helper and the whole join/leave lifecycle.

The plan

A reliable save system follows five steps.

  1. Join: when PlayerAdded fires, load the data (with retries) and store it in memory.
  2. Play: the game changes the in-memory values, never the DataStore directly.
  3. Show: put visible numbers in leaderstats so players see them.
  4. Leave: when PlayerRemoving fires, save the in-memory data once.
  5. Shutdown: when the server closes, save everyone with game:BindToClose.

Why memory first? DataStore requests have rate limits and take time. Updating the store on every coin pickup would exceed the budget quickly. Keep the working copy in a table, and write it at safe moments (plus an autosave every few minutes).

leaderstats

If a Folder named exactly leaderstats is a child of a Player, Roblox shows its values in the default player list. Create one value object for each stat:

LUA
local function createLeaderstats(player, data)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Value = data.coins
	coins.Parent = leaderstats
end

IntValue, NumberValue, StringValue and BoolValue hold simple values. Changes made on the server replicate to every player.

Defaults and reconcile

A saved table can be missing fields after you add a new feature. A reconcile step fills missing fields with defaults without touching saved ones:

LUA
local DEFAULTS = { coins = 0, level = 1, version = 1 }

local function reconcile(saved, defaults)
	for key, value in pairs(defaults) do
		if saved[key] == nil then
			saved[key] = value
		end
	end
	return saved
end

The full script

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

local store = DataStoreService:GetDataStore("PlayerData_v1")
local sessionData = {} -- [player] = data

local function withRetries(callback, attempts)
	for i = 1, attempts do
		local ok, result = pcall(callback)
		if ok then
			return true, result
		end
		warn("Attempt " .. i .. " failed:", result)
		task.wait(2 ^ (i - 1)) -- 1s, 2s, 4s ...
	end
	return false, nil
end

local function onPlayerAdded(player)
	local key = "Player_" .. player.UserId
	local ok, saved = withRetries(function()
		return store:GetAsync(key)
	end, 3)

	if not ok then
		player:Kick("Your data could not be loaded. Please rejoin.")
		return
	end

	local data = reconcile(saved or {}, DEFAULTS)
	sessionData[player] = data
	createLeaderstats(player, data)
end

local function save(player)
	local data = sessionData[player]
	if not data then return end -- never loaded: do not save!
	local key = "Player_" .. player.UserId
	withRetries(function()
		return store:SetAsync(key, data)
	end, 3)
end

Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(function(player)
	save(player)
	sessionData[player] = nil
end)

game:BindToClose(function()
	for _, player in Players:GetPlayers() do
		task.spawn(save, player)
	end
	task.wait(3)
end)

Study three details here. When the load fails after three attempts, the script kicks the player instead of continuing with defaults, so a failed load can never overwrite their save. The save function does nothing if sessionData[player] is missing, which guards against saving data that was never loaded. And BindToClose runs each save in its own thread with task.spawn so saves happen at the same time, and then waits a little so the server does not close first. (Studio also fires BindToClose when you stop a test.)

The save lifecycle

Join Load with retries into memory.
Play Change memory, not the store.
Leave Save once, then clean up.
Shutdown BindToClose saves everyone.

An autosave every few minutes protects against crashes.

1 / 2

Runnable stand-in: reconcile and retry

First the pure logic: merge defaults into saved data, including data from an older version.

JS Reconcile saved data with defaults (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The old save keeps its 340 coins and level 9, and gains the new fields. This is how you add features without wiping anyone.

JS Join, play and leave with retries

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the log: Player 2's load fails twice then succeeds on the third attempt, player 1's extra 25 coins are saved, and an unknown player is skipped instead of saving junk.

Autosave

Add a loop that saves everyone every few minutes. If the server crashes, players lose at most a few minutes.

LUA
task.spawn(function()
	while true do
		task.wait(180)
		for _, player in Players:GetPlayers() do
			task.spawn(save, player)
		end
	end
end)

Keep it well below the DataStore request budget by spacing out saves if you have many players.

Common mistakes

  • Saving inside PlayerAdded before loading completes, which can write defaults.
  • Not handling players who join before your script runs. Loop over Players:GetPlayers() once at the start and call onPlayerAdded for them.
  • Forgetting BindToClose. Players in a server that shuts down lose recent progress.
  • Changing leaderstats values from the client. Clients can change their copy, but the server's is the truth; keep gameplay changes on the server.
  • Saving the leaderstats objects directly. Save your plain table, then mirror it to the values.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why keep a working copy of player data in a Lua table instead of saving on every change?

    Requests are rate-limited and take time. Editing memory is instant, and the saved copy is written on leave, shutdown and autosave.
  2. 2. What name must the folder have for Roblox to show values in the player list?

    The folder must be named exactly leaderstats and be a child of the Player.
  3. 3. What does game:BindToClose protect against?

    BindToClose runs your function before the server ends, giving you time to save every player.
  4. 4. What should happen if loading a player's data fails after retries?

    Continuing with defaults could overwrite the real save later, so block the session instead.
  5. 5. What does a reconcile function do?

    Reconcile merges defaults into the saved table so new fields appear without losing existing progress.

Summary

  • Load into memory on PlayerAdded with retries; change memory while playing; save on PlayerRemoving, in BindToClose and with an autosave.
  • leaderstats is a Folder under the Player with value objects that show in the player list.
  • Reconcile merges defaults into saved data so new features never wipe old players.
  • If loading fails, block the session instead of continuing with defaults.
  • Retry with exponential backoff, and run shutdown saves in parallel with task.spawn.

Next: DataStore Limits and Safe Updates