Roblox DataStores
Persist data across sessions in Roblox with DataStoreService: loading on join,
saving on leave and shutdown, safe updates, retries, and ordered stores for
leaderboards. Server-side only.
When to use
- Use to save/load player progress (coins, inventory, levels), build persistent
leaderboards, or fix data loss, overwrites, and throttling.
- Use when server code calls
DataStoreService, GetDataStore, GetAsync,
SetAsync, UpdateAsync, or GetOrderedDataStore.
When not to use: general scripting, services, remotes, the client/server
split → roblox-luau. High-frequency temporary state (matchmaking, per-round) →
memory stores (a different service). Engine-agnostic persistence theory →
save-systems.
Core workflow
- Enable Studio access once. In a published place, File → Experience Settings →
Security → Enable Studio Access to API Services (use a separate test place; Studio
hits the same live data as players). DataStores work only from server
Scripts,
never LocalScripts.
- Get a store, then read/write by key.
DataStoreService:GetDataStore("Name");
key per player is usually "Player_" .. player.UserId.
- Wrap every call in
pcall. GetAsync/SetAsync/UpdateAsync are network
calls that can fail; an unguarded failure errors the thread and risks data loss.
- Load on
PlayerAdded, save on PlayerRemoving, and also BindToClose. A
leaving player and a shutting-down server both need a final save.
- Prefer
UpdateAsync for read-modify-write (multi-server safe) over SetAsync
(blind overwrite). On a failed load, do not overwrite with defaults — abort
the save so you don't wipe good data.
- Use
OrderedDataStore for ranked data (leaderboards) via GetSortedAsync.
Test by joining, changing data, rejoining, and confirming it persisted.
Patterns
1. Load on join (pcall-guarded)
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local store = DataStoreService:GetDataStore("PlayerData")
local DEFAULT = { Coins = 0, Level = 1 }
Players.PlayerAdded:Connect(function(player)
local key = "Player_" .. player.UserId
local ok, data = pcall(function()
return store:GetAsync(key)
end)
if not ok then
-- Load FAILED (network). Do not treat as a new player; flag so we never save
-- over their real data with defaults.
warn("Load failed for", player.Name, data)
player:SetAttribute("DataLoaded", false)
return
end
player:SetAttribute("DataLoaded", true)
local profile = data or DEFAULT -- nil == genuinely new player
applyToLeaderstats(player, profile)
end)
2. Save with UpdateAsync (multi-server safe)
-- UpdateAsync reads the latest value, then writes what the callback returns.
-- The callback MUST NOT yield (no task.wait, no further Async calls inside it), and it
-- can run more than once if another server writes the key first, so keep it pure.
local function savePlayer(player)
-- Save only after a confirmed load. `~= true` also covers a player who leaves while
-- GetAsync is still in flight (attribute still nil), which `== false` would miss.
if player:GetAttribute("DataLoaded") ~= true then return end
local key = "Player_" .. player.UserId
local newData = gatherDataFor(player) -- a plain table of serializable values
local ok, err = pcall(function()
store:UpdateAsync(key, function(old)
-- merge/decide here; return nil to cancel the write
return newData
end)
end)
if not ok then warn("Save failed for", player.Name, err) end
end
3. Save on leave AND on shutdown
Players.PlayerRemoving:Connect(savePlayer)
-- BindToClose runs when the server shuts down; save everyone still in.
-- The server waits at most 30 seconds for it, so save in parallel and yield until done.
game:BindToClose(function()
local players = Players:GetPlayers()
local remaining = #players
if remaining == 0 then return end
for _, player in players do
task.spawn(function()
savePlayer(player)
remaining -= 1
end)
end
while remaining > 0 do task.wait() end
end)
4. Retry with backoff (transient failures)
local function withRetry(fn, attempts)
attempts = attempts or 3
for i = 1, attempts do
local ok, result = pcall(fn)
if ok then return true, result end
if i < attempts then task.wait(2 ^ i) end -- 2s, 4s, ... backoff
end
return false
end
local ok, data = withRetry(function() return store:GetAsync(key) end)
Retry only operations that are safe to repeat. A failed write is not proof the write did
not happen: the server may simply have missed the response. Re-running an UpdateAsync
that writes the full saved state is harmless; re-running IncrementAsync can add twice.
When the outcome matters, confirm it with an uncached read (DataStoreGetOptions with
UseCache = false) before retrying.
5. Increment a counter
-- IncrementAsync is a convenience for integer read-modify-write (still wrap it).
local ok, newTotal = pcall(function()
return store:IncrementAsync("Visits_" .. player.UserId, 1)
end)
6. Leaderboard with OrderedDataStore
local boards = DataStoreService:GetOrderedDataStore("Coins")
-- Write a player's score (call when it changes, not every frame).
pcall(function() boards:SetAsync("Player_" .. player.UserId, coins) end)
-- Read the top 10, descending.
local ok, pages = pcall(function()
return boards:GetSortedAsync(false, 10) -- ascending=false → highest first
end)
if ok then
for rank, entry in ipairs(pages:GetCurrentPage()) do
print(rank, entry.key, entry.value) -- entry.value is the number
end
end
Pitfalls
- Unhandled failure wipes progress → always
pcall Async calls; on a failed
load, mark the session and refuse to save so defaults never overwrite real data.
SetAsync race between servers → two servers writing the same key can clobber
each other. Use UpdateAsync for read-modify-write so each write sees the latest.
- Yielding inside the
UpdateAsync callback → the callback can't call
task.wait or other Async functions; compute the new value beforehand and return it.
- Side effects inside the
UpdateAsync callback → Roblox re-runs the callback when
another server changed the key between read and write, so granting items, firing
remotes, or incrementing counters there can happen twice. Act after the call returns.
- Saving a player who left mid-load →
PlayerRemoving can fire while GetAsync is
still yielding. Gate saves on "load succeeded", not on "load did not fail".
- No
BindToClose save → players in the server at shutdown lose unsaved progress;
add game:BindToClose and wait for saves to finish within its budget.
- Throttling / "too many requests" → respect per-key and per-minute limits; don't
save on every value change. Batch and save on a timer / on leave.
GetAsync is
cached for about four seconds, so immediate re-reads may be stale. Studio Run mode
uses its own lower static limits; Roblox recommends testing rate limits in Team Create.
- Storing non-serializable values → only JSON-serializable data persists: numbers,
strings, booleans, and tables with string/number keys.
Instances, Vector3,
CFrame, and functions do not — serialize them to plain tables first.
- Testing without API access → DataStore requests in Studio error (writes report
StudioAccessToApisNotAllowed) until Enable Studio Access to API Services is on (and
they don't work from a LocalScript).
DataStoreKeyInfo is nil for ordered stores → OrderedDataStore doesn't
support versioning/metadata; use a regular DataStore when you need those.
References
- For session locking (preventing duplicate data across servers), versioning/
metadata with
DataStoreSetOptions, ordered-store pagination
(AdvanceToNextPageAsync), the key error codes and request limits, and
Right-to-be-Forgotten compliance, read references/sessions-and-limits.md.
Related skills
roblox-luau — services, instances, events, and the server/client model.
save-systems — engine-agnostic serialization, slots, and migration.
1---2name: roblox-datastores3description: >4 Persist player data in Roblox with DataStoreService: GetDataStore, GetAsync/5 SetAsync/UpdateAsync/IncrementAsync wrapped in pcall, load-on-join and6 save-on-leave plus BindToClose, retries, and OrderedDataStore leaderboards. Use7 when saving or loading persistent data in a Roblox experience — when the user8 mentions DataStore, DataStoreService, GetAsync, SetAsync, UpdateAsync, save player9 data, or leaderboards. For general Luau scripting use roblox-luau.10metadata:11 source: https://skillmd.com/skills/junmystery/roblox-datastores12---1314# Roblox DataStores1516Persist data across sessions in Roblox with `DataStoreService`: loading on join,17saving on leave and shutdown, safe updates, retries, and ordered stores for18leaderboards. Server-side only.1920## When to use2122- Use to save/load player progress (coins, inventory, levels), build persistent23 leaderboards, or fix data loss, overwrites, and throttling.24- Use when server code calls `DataStoreService`, `GetDataStore`, `GetAsync`,25 `SetAsync`, `UpdateAsync`, or `GetOrderedDataStore`.2627**When *not* to use:** general scripting, services, remotes, the client/server28split → `roblox-luau`. High-frequency temporary state (matchmaking, per-round) →29memory stores (a different service). Engine-agnostic persistence theory →30`save-systems`.3132## Core workflow33341. **Enable Studio access once.** In a published place, File → Experience Settings →35 Security → *Enable Studio Access to API Services* (use a separate test place; Studio36 hits the same live data as players). DataStores work only from server `Script`s,37 never `LocalScript`s.382. **Get a store, then read/write by key.** `DataStoreService:GetDataStore("Name")`;39 key per player is usually `"Player_" .. player.UserId`.403. **Wrap every call in `pcall`.** `GetAsync`/`SetAsync`/`UpdateAsync` are network41 calls that can fail; an unguarded failure errors the thread and risks data loss.424. **Load on `PlayerAdded`, save on `PlayerRemoving`, and also `BindToClose`.** A43 leaving player and a shutting-down server both need a final save.445. **Prefer `UpdateAsync` for read-modify-write** (multi-server safe) over `SetAsync`45 (blind overwrite). On a failed load, do **not** overwrite with defaults — abort46 the save so you don't wipe good data.476. **Use `OrderedDataStore` for ranked data** (leaderboards) via `GetSortedAsync`.48 Test by joining, changing data, rejoining, and confirming it persisted.4950## Patterns5152### 1. Load on join (pcall-guarded)5354```lua55local DataStoreService = game:GetService("DataStoreService")56local Players = game:GetService("Players")57local store = DataStoreService:GetDataStore("PlayerData")5859local DEFAULT = { Coins = 0, Level = 1 }6061Players.PlayerAdded:Connect(function(player)62 local key = "Player_" .. player.UserId63 local ok, data = pcall(function()64 return store:GetAsync(key)65 end)6667 if not ok then68 -- Load FAILED (network). Do not treat as a new player; flag so we never save69 -- over their real data with defaults.70 warn("Load failed for", player.Name, data)71 player:SetAttribute("DataLoaded", false)72 return73 end7475 player:SetAttribute("DataLoaded", true)76 local profile = data or DEFAULT -- nil == genuinely new player77 applyToLeaderstats(player, profile)78end)79```8081### 2. Save with UpdateAsync (multi-server safe)8283```lua84-- UpdateAsync reads the latest value, then writes what the callback returns.85-- The callback MUST NOT yield (no task.wait, no further Async calls inside it), and it86-- can run more than once if another server writes the key first, so keep it pure.87local function savePlayer(player)88 -- Save only after a confirmed load. `~= true` also covers a player who leaves while89 -- GetAsync is still in flight (attribute still nil), which `== false` would miss.90 if player:GetAttribute("DataLoaded") ~= true then return end91 local key = "Player_" .. player.UserId92 local newData = gatherDataFor(player) -- a plain table of serializable values9394 local ok, err = pcall(function()95 store:UpdateAsync(key, function(old)96 -- merge/decide here; return nil to cancel the write97 return newData98 end)99 end)100 if not ok then warn("Save failed for", player.Name, err) end101end102```103104### 3. Save on leave AND on shutdown105106```lua107Players.PlayerRemoving:Connect(savePlayer)108109-- BindToClose runs when the server shuts down; save everyone still in.110-- The server waits at most 30 seconds for it, so save in parallel and yield until done.111game:BindToClose(function()112 local players = Players:GetPlayers()113 local remaining = #players114 if remaining == 0 then return end115 for _, player in players do116 task.spawn(function()117 savePlayer(player)118 remaining -= 1119 end)120 end121 while remaining > 0 do task.wait() end122end)123```124125### 4. Retry with backoff (transient failures)126127```lua128local function withRetry(fn, attempts)129 attempts = attempts or 3130 for i = 1, attempts do131 local ok, result = pcall(fn)132 if ok then return true, result end133 if i < attempts then task.wait(2 ^ i) end -- 2s, 4s, ... backoff134 end135 return false136end137138local ok, data = withRetry(function() return store:GetAsync(key) end)139```140141Retry only operations that are safe to repeat. A failed write is not proof the write did142not happen: the server may simply have missed the response. Re-running an `UpdateAsync`143that writes the full saved state is harmless; re-running `IncrementAsync` can add twice.144When the outcome matters, confirm it with an uncached read (`DataStoreGetOptions` with145`UseCache = false`) before retrying.146147### 5. Increment a counter148149```lua150-- IncrementAsync is a convenience for integer read-modify-write (still wrap it).151local ok, newTotal = pcall(function()152 return store:IncrementAsync("Visits_" .. player.UserId, 1)153end)154```155156### 6. Leaderboard with OrderedDataStore157158```lua159local boards = DataStoreService:GetOrderedDataStore("Coins")160161-- Write a player's score (call when it changes, not every frame).162pcall(function() boards:SetAsync("Player_" .. player.UserId, coins) end)163164-- Read the top 10, descending.165local ok, pages = pcall(function()166 return boards:GetSortedAsync(false, 10) -- ascending=false → highest first167end)168if ok then169 for rank, entry in ipairs(pages:GetCurrentPage()) do170 print(rank, entry.key, entry.value) -- entry.value is the number171 end172end173```174175## Pitfalls176177- **Unhandled failure wipes progress** → always `pcall` Async calls; on a failed178 *load*, mark the session and refuse to *save* so defaults never overwrite real data.179- **`SetAsync` race between servers** → two servers writing the same key can clobber180 each other. Use `UpdateAsync` for read-modify-write so each write sees the latest.181- **Yielding inside the `UpdateAsync` callback** → the callback can't call182 `task.wait` or other Async functions; compute the new value beforehand and return it.183- **Side effects inside the `UpdateAsync` callback** → Roblox re-runs the callback when184 another server changed the key between read and write, so granting items, firing185 remotes, or incrementing counters there can happen twice. Act after the call returns.186- **Saving a player who left mid-load** → `PlayerRemoving` can fire while `GetAsync` is187 still yielding. Gate saves on "load succeeded", not on "load did not fail".188- **No `BindToClose` save** → players in the server at shutdown lose unsaved progress;189 add `game:BindToClose` and wait for saves to finish within its budget.190- **Throttling / "too many requests"** → respect per-key and per-minute limits; don't191 save on every value change. Batch and save on a timer / on leave. `GetAsync` is192 cached for about four seconds, so immediate re-reads may be stale. Studio Run mode193 uses its own lower static limits; Roblox recommends testing rate limits in Team Create.194- **Storing non-serializable values** → only JSON-serializable data persists: numbers,195 strings, booleans, and tables with string/number keys. `Instance`s, `Vector3`,196 `CFrame`, and functions do not — serialize them to plain tables first.197- **Testing without API access** → DataStore requests in Studio error (writes report198 `StudioAccessToApisNotAllowed`) until *Enable Studio Access to API Services* is on (and199 they don't work from a `LocalScript`).200- **`DataStoreKeyInfo` is nil for ordered stores** → `OrderedDataStore` doesn't201 support versioning/metadata; use a regular `DataStore` when you need those.202203## References204205- For session locking (preventing duplicate data across servers), versioning/206 metadata with `DataStoreSetOptions`, ordered-store pagination207 (`AdvanceToNextPageAsync`), the key error codes and request limits, and208 Right-to-be-Forgotten compliance, read `references/sessions-and-limits.md`.209210## Related skills211212- `roblox-luau` — services, instances, events, and the server/client model.213- `save-systems` — engine-agnostic serialization, slots, and migration.