Start building

Roblox DataStore tutorial: how to save player data safely

Build one save system that loads each player's data on join, saves it on leave and at shutdown, and never wipes progress when a request fails.

A rebirth in a Roblox simulator: the player's character in a ring of light under the words Rebirth 1 and x2 coins forever.
On this page
  1. Turn on DataStores in Studio
  2. How the save system is laid out
  3. Part 1: the store and the data template
  4. Part 2: load data when a player joins
  5. Part 3: save with UpdateAsync
  6. Part 4: autosave and saving on shutdown
  7. Limits: data size, request budgets and session locks
  8. Test your save system
  9. Questions

To save player data in Roblox, you get a DataStore from DataStoreService, load each player's table with GetAsync when they join, and write it back with UpdateAsync when they leave, every couple of minutes and when the server shuts down. Every request goes inside pcall, because DataStore calls can fail. This tutorial builds that whole system as one ModuleScript you can drop into any game.

Turn on DataStores in Studio

DataStores belong to a published game, so Studio can only use them once two things are true:

  1. The place is published. Use File > Publish to Roblox if it isn't yet.
  2. Studio is allowed to call Roblox's services. Open Game Settings, go to Security, turn on Enable Studio Access to API Services and save.

Without the first, even getting a DataStore throws an error. Without the second, every load and save fails with an error in the Output. The module below survives both: it warns you and lets the game run without saving, so you can still test everything else.

How the save system is laid out

One DataStore holds every player. Each player has one key, "Player_" .. player.UserId, and that key holds one table with everything about them: coins, wins, inventory, settings. User IDs never change while usernames can, so never key data by name.

One table per player beats a separate key for each stat:

  • Fewer requests. Loading a player is one call instead of one per stat, and every server has a limited request budget.
  • All or nothing. Coins and the item bought with them are saved in the same write, so a failed request can't leave half a purchase behind.
  • Easy to grow. New fields go in a template, and old saves pick them up when they load.
WhenWhat the module does
A player joinsLoads their table, with retries, and builds leaderstats from it
Every 2 minutesSaves everyone in the server
A player leavesSaves them one last time
The server shuts downSaves everyone still in it before it closes

Part 1: the store and the data template

In the Explorer, add a ModuleScript to ServerScriptService and name it PlayerData. The code comes in four parts, each pasted below the one before.

ModuleScriptServerScriptService
-- ModuleScript named PlayerData in ServerScriptService, part 1: the store and the template
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")

local MAX_TRIES = 3
local AUTOSAVE_SECONDS = 120
local LEADERSTATS = { "Coins", "Wins" } -- fields shown in the player list

-- Every field a player has, with its starting value
local TEMPLATE = {
	Coins = 0,
	Wins = 0,
	PlayMinutes = 0,
	Inventory = {},
}

local ok, store = pcall(function()
	return DataStoreService:GetDataStore("PlayerData_v1")
end)
if not ok then
	warn("DataStores are unavailable, nothing will save: " .. tostring(store))
	store = nil
end

local PlayerData = {}
local profiles = {} -- [player] = { Data = their table, CanSave = true or false }
local activeSaves = 0

-- Fills in anything the saved table is missing, using the template
local function reconcile(data, template)
	for key, default in template do
		if type(default) == "table" then
			if type(data[key]) ~= "table" then
				data[key] = {}
			end
			reconcile(data[key], default)
		elseif data[key] == nil then
			data[key] = default
		end
	end
	return data
end

TEMPLATE lists every field a player has and its starting value. When a save loads, reconcile walks through the template and fills in anything missing. A brand new player gets a full copy of the template, and a player who last joined months ago gets just the fields you added since. So when the daily rewards system adds LastClaim and Streak, no save needs a reset. Nested tables are built fresh for each player, so two players never share one Inventory.

Changing the store name, PlayerData_v1, starts everyone from zero: useful for a deliberate wipe, a disaster by accident.

Part 2: load data when a player joins

ModuleScript
-- PlayerData ModuleScript, part 2: load on join with retries (paste below part 1)
local function loadData(player)
	local key = "Player_" .. player.UserId
	for attempt = 1, MAX_TRIES do
		local success, result = pcall(function()
			return store:GetAsync(key)
		end)
		if success then
			return true, result
		end
		warn(string.format("Load failed for %s (try %d): %s", key, attempt, tostring(result)))
		if attempt < MAX_TRIES then
			task.wait(2 ^ attempt)
		end
	end
	return false, nil
end

local function onPlayerAdded(player)
	local loaded, saved = false, nil
	if store then
		loaded, saved = loadData(player)
	end
	if not player.Parent then
		return -- they left while we were loading
	end

	local data = reconcile(if type(saved) == "table" then saved else {}, TEMPLATE)
	profiles[player] = { Data = data, CanSave = loaded }
	if not loaded then
		warn(player.Name .. " is playing on fresh data that will not be saved this session")
	end

	-- Leaderstats show the data, and server changes to them are copied back into it
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	for _, name in LEADERSTATS do
		local stat = Instance.new("IntValue")
		stat.Name = name
		stat.Value = data[name]
		stat.Changed:Connect(function(value)
			data[name] = value
		end)
		stat.Parent = leaderstats
	end
	leaderstats.Parent = player
end

loadData tries up to three times, waiting 2 and then 4 seconds between tries, because most DataStore failures pass quickly. GetAsync returns nil for a player who has never saved, which is fine: reconcile turns an empty table into a full template.

The key line is CanSave = loaded. If every try fails, the player still plays, on default data, but the module never saves for them this session. Saving would write those defaults over their real progress, which is still safe in the DataStore and will load next time. If progress is the heart of your game, you can kick them instead with player:Kick("Could not load your data, please rejoin").

The last block builds the same folder as the leaderstats guide, filled from saved data. Each value's Changed connection copies new numbers into the table, so any server script that runs leaderstats.Coins.Value += 10 is now saving coins.

Part 3: save with UpdateAsync

ModuleScript
-- PlayerData ModuleScript, part 3: save with UpdateAsync (paste below part 2)
local function saveData(player, profile)
	if not profile.CanSave then
		return -- their data never loaded, so saving would wipe the real copy
	end
	local key = "Player_" .. player.UserId
	for attempt = 1, MAX_TRIES do
		local success, err = pcall(function()
			store:UpdateAsync(key, function(storedData)
				-- storedData is what is saved right now; returning nil would cancel the write
				return profile.Data
			end)
		end)
		if success then
			return
		end
		warn(string.format("Save failed for %s (try %d): %s", key, attempt, tostring(err)))
		if attempt < MAX_TRIES then
			task.wait(2 ^ attempt)
		end
	end
end

-- The last save for a player who is leaving
local function release(player)
	local profile = profiles[player]
	if not profile then
		return
	end
	profiles[player] = nil
	activeSaves += 1
	saveData(player, profile)
	activeSaves -= 1
end

UpdateAsync reads the value saved right now, passes it to your function and writes whatever the function returns. SetAsync would just overwrite. Here the function simply returns the session's table, but it is the place where safety checks go, like the session lock described below. It retries just like the load does.

release takes the profile out of profiles before saving. Whichever comes first, the player leaving or the server shutting down, does the save, and any later call finds nothing to do. activeSaves counts the saves still running, which the shutdown code waits for.

Part 4: autosave and saving on shutdown

ModuleScript
-- PlayerData ModuleScript, part 4: events, autosave, shutdown and the module's functions (paste below part 3)
Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(release)
for _, player in Players:GetPlayers() do
	task.spawn(onPlayerAdded, player)
end

-- Autosave, so a crash loses a couple of minutes at most
task.spawn(function()
	while true do
		task.wait(AUTOSAVE_SECONDS)
		for player, profile in profiles do
			task.spawn(saveData, player, profile)
		end
	end
end)

-- Shutdown: the server waits up to 30 seconds for this function before it closes
game:BindToClose(function()
	for _, player in Players:GetPlayers() do
		task.spawn(release, player)
	end
	while activeSaves > 0 do
		task.wait(0.1)
	end
end)

-- For other scripts: a player's data table, or nil until it has loaded
function PlayerData.Get(player)
	local profile = profiles[player]
	return profile and profile.Data
end

-- Waits until a player's data has loaded; nil if they leave first
function PlayerData.WaitFor(player)
	while player.Parent and not profiles[player] do
		task.wait(0.1)
	end
	return PlayerData.Get(player)
end

return PlayerData

The first lines connect joining and leaving, and load anyone who joined before the module first ran. The autosave writes everyone every two minutes, each in its own thread, so one slow request doesn't hold up the rest.

game:BindToClose matters more than it looks. When a server shuts down, players are removed, but the server can close before their saves finish. A function bound with BindToClose keeps the server open for up to 30 seconds, so this one saves everyone still in the game and waits until every save in flight is done. It also runs when you stop a playtest in Studio.

Start the module

A ModuleScript does nothing until a script requires it. Add a Script to ServerScriptService:

ScriptServerScriptService
-- Script in ServerScriptService: starts PlayerData and pays every player a little each minute
local Players = game:GetService("Players")
local ServerScriptService = game:GetService("ServerScriptService")

local PlayerData = require(ServerScriptService:WaitForChild("PlayerData"))

while true do
	task.wait(60)
	for _, player in Players:GetPlayers() do
		local data = PlayerData.Get(player)
		if data then
			player.leaderstats.Coins.Value += 10 -- shown stats: change the value
			data.PlayMinutes += 1 -- everything else: change the table
		end
	end
end

require hands the same module to every script that asks, so it only runs once however many scripts use it. This script also shows the two ways to change data: stats in leaderstats through their value, and everything else straight in the table. Pets from a simulator game go in the same way, with table.insert(data.Inventory, "Dragon"). If your game already has coin scripts, you can ask Revix to add this module and connect them to it.

Limits: data size, request budgets and session locks

Size. Each key has a size cap, currently a few megabytes once your table is encoded as text. Coins and an inventory list use a tiny part of that. What fills keys up is logs, chat history or builds saved block by block.

Request budgets. Each server gets a number of requests per minute for each kind of call, and the number grows with the player count. Writes to the same key also need a few seconds between them. Go over and requests wait in a queue and can fail. That is why the module changes data in memory and only writes on the autosave, on leave and at shutdown, never on every coin. Exact numbers change over time, so check the data store pages in the Creator Hub docs.

Session locks. When a player hops servers fast, the new server can load their data before the old one has finished its last save. Two servers then hold different copies and whichever saves last wins, which is how items get duplicated or lost. A session lock prevents it: when loading, the server writes its ID (game.JobId) and the time into the saved record inside UpdateAsync. Another server that finds a fresh lock waits and retries instead of loading, and the owner clears the lock on its final save. A lock older than a few minutes belongs to a crashed server and can be taken over. The module above is a solid start for most games, so add a lock before you add trading or anything else worth duplicating.

Test your save system

  1. Publish, turn on API access as shown above, and start a playtest.
  2. Earn some coins. Lower the starter script's 60 second wait while you test.
  3. Stop the test, start it again, and check that your coins came back.
  4. Watch the Output. Any "Load failed" or "Save failed" line says which key broke and why.
  5. Add a field to TEMPLATE, such as Gems = 0, and play. Your existing save loads with Gems added.
  6. Test a failure: add error("pretend Roblox is down") just above return store:GetAsync(key), play and earn coins. You should see the "will not be saved" warning, and once you remove the line, your real coins are still there.

Revix can run this test loop for you too: it runs playtests, reads the Output and fixes what breaks.

Questions

Why is my DataStore not saving in Studio?

Studio needs a published place and API access. Publish with File > Publish to Roblox, then open Game Settings, go to Security and turn on Enable Studio Access to API Services. Also save everyone in a BindToClose function, because Studio shuts the test server down as soon as you stop.

Should I use SetAsync or UpdateAsync to save player data?

Use UpdateAsync. It reads the value that is saved right now before it writes, so your code can refuse a write that would overwrite newer data, which is how session locks work. SetAsync just overwrites whatever is there.

How often should I save player data in Roblox?

Keep the data in a table in memory and save it on a timer every couple of minutes, when the player leaves and when the server shuts down. Saving on every change wastes your request budget and runs into the cooldown on writing the same key.

How much data can one DataStore key hold?

Each key has a size cap of a few megabytes once the data is encoded, and the current number is in the data store pages of the Creator Hub docs. Coins, stats and an inventory list use a tiny fraction of it.

What happens if a DataStore request fails?

pcall catches the error so your script keeps running. Retry a couple of times with a short wait. If a load still fails, let the player play without saving that session, so their real data is never overwritten with defaults.

Your game is
one sentence away.

Start building free

Free to start. No card needed.