Lesson 1 of 5
DataStores: saving without losing a single coin
Save Roblox player data safely by reading Beacon Yard's hand-rolled DataService, with UpdateAsync, session locks, failed-load protection, request budgets and when to save.
By the end you can
- Load and save a player's profile with GetDataStore, UpdateAsync and pcall, and explain why a failed load must never be saved over
- Explain last-write-wins, session locks and why a lock must be renewed while the player is in the server
- Work out the request budgets and limits that apply to Beacon Yard, and pick when to save
Before this: Security: never trust the client, Coins: touch, debounce, respawn, leaderstats
1Stop, play again, and the coins are still there
Collect a few coins in a published copy of Beacon Yard, stop the playtest, and press Play again. The leaderboard shows the same number. Between those two sessions the server that held your coins shut down, and a new one started with nothing in memory. The coins came back from a DataStoreDataStoreRoblox's persistent key-value storage for saving player data between sessions.Think of it as a bank vault in another city..
Coins go up in memory, the session stops and saves, and the next session loads them.
Transcript
- 0:00 Coins increase in memory when you pick one up.
- 0:05 Stop ends the session and BindToClose saves if the key is savable.
- 0:10 The next Play loads the same coins.
- 0:20 GetAsync prints the row. The game writes it with UpdateAsync.
While you play, where does DataService.addCoins put a new coin?
Answer
In the profile table in server memory; the DataStore is written later. addCoins changes profile.coins in memory and copies it to leaderstats. Saving every pickup would burn the request budget; the profile is written on leave, on shutdown and at checkpoints.
Open this step in lesson mode · Link to this step · This confused me
2A bank vault in another city
A DataStore is a key-value store that lives outside your game server. You get one by name with DataStoreService:GetDataStore("BeaconYard_v1"), and Beacon Yard keeps one record per player under the key tostring(player.UserId)1.
| In the picture | In Roblox |
|---|---|
| The vault | Roblox's DataStore service, outside your server |
| The trip to the city | A network call that takes time and can fail |
| The deposit slip | SetAsync or UpdateAsync with a key |
The DataStore is a bank vault in another city. Every visit is a trip: it takes time, and it can fail. You keep a working copy at home (the profile in server memory) and only go to the vault when you need to.
Think of it as A bank vault in another city
Every call can throw, so every call is wrapped in pcall. Even GetDataStore throws in Studio when Enable Studio Access to API Services is off, and in a place that was never published. DataService handles that by keeping the profile in memory for the session and warning once.
local function getStore(): DataStore?
if storeResolved then
return store
end
storeResolved = true
local ok, result = pcall(function()
return DataStoreService:GetDataStore(Config.DATASTORE_NAME)
end)
if not ok then
store = nil
warnOnce("DataStore unavailable (" .. tostring(result) .. "). Profiles stay in server memory for this session.")
return nil
end
store = result :: DataStore
You play an unpublished copy of the place. What does DataService do?
Answer
Warns once that the DataStore is unavailable and keeps coins in memory for this session. getStore catches the error, warns once and returns nil. Every later save sees no store and does nothing, so the session keeps working.
Open this step in lesson mode · Link to this step · This confused me
3UpdateAsync: the teller shows you the balance first
SetAsync(key, value) writes blindly. UpdateAsync(key, transform) reads the current value, passes it to your function, and writes whatever the function returns. Return nil and nothing is written1. DataService loads a player with one UpdateAsync that reads the record and takes the session lock in the same step.
| In the picture | In Roblox |
|---|---|
| The teller | UpdateAsync |
| The balance shown first | The previous value passed to your transform |
| Being handed the slip back | The transform running again after a conflict |
UpdateAsync is a teller who shows you the balance before you write the new amount. If someone changed the account while you were writing, the teller hands you the newer balance and asks you to write again.
Think of it as A teller who shows you the balance before you write the new amount
Stored dataRemember: UpdateAsync is a teller who shows you the balance before you write the new amount.
dataStore:UpdateAsync(tostring(userId), function(previous: unknown): SavedRecord?
-- A test sets this so the transform throws before any write.
-- UpdateAsync then leaves the stored record untouched.
if workspace:GetAttribute("TestDataStoreLoadError") == true then
error("TestDataStoreLoadError")
end
local coins = 0
local speedOwned = false
if typeof(previous) == "table" then
local record = previous :: StoredProfile
local loadedCoins = record.coins
if typeof(loadedCoins) == "number" and loadedCoins >= 0 and loadedCoins == loadedCoins then
coins = math.floor(loadedCoins)
end
if typeof(record.speedOwned) == "boolean" then
speedOwned = record.speedOwned
end
if lockHeld(record) then
profile = { coins = coins, speedOwned = speedOwned }
owned = false
return nil
end
end
profile = { coins = coins, speedOwned = speedOwned }
owned = true
return {
coins = coins,
speedOwned = speedOwned,
sessionJob = game.JobId,
sessionAt = os.time(),
Where does it break?“A teller who shows you the balance before you write the new amount” is a good picture of updateasync. Where does it stop being true?
It breaks here. The transform may run more than once, so it must not yield or do anything you cannot repeat, such as granting a badge.
The true model. UpdateAsync reads the current value, calls your function with it and writes the result. If the value changed while the write was in flight, it calls the function again with the newer value. Returning nil cancels the write.
Because the teller may hand the slip back, the transform can run more than once. So it must not yield, and it must not have side effects you cannot repeat, such as granting a badge.
Which line makes this transform unsafe?
store:UpdateAsync(key, function(old)
old = old or { coins = 0 }
BadgeService:AwardBadgeAsync(userId, FIRST_SAVE_BADGE)
old.coins += 5
return old
end)
Answer
Line 3: BadgeService:AwardBadgeAsync(userId, FIRST_SAVE_BADGE). Fixed: -- award the badge after UpdateAsync returns successfully. AwardBadgeAsync yields and talks to another service. If UpdateAsync retries the transform, it runs again. Keep the transform pure: read the old value, return the new one.
Open this step in lesson mode · Link to this step · This confused me
4Two servers, one key
Here is the question the vault picture hides: what happens when two servers write the same key?
Stored dataRemember: A DataStore is a bank vault in another city.
Where does it break?“A bank vault in another city” is a good picture of a datastore. Where does it stop being true?
It breaks here. The vault keeps only the last write for a key, so two servers writing the same key can silently undo each other.
The true model. A DataStore is a remote key-value store with request budgets. Calls are slow and can throw, so code wraps them, retries carefully and uses UpdateAsync or a session lock when more than one server might write.
A DataStore keeps only the last write. If server A writes 120 coins and server B then writes 80, the key says 80 and A's coins are gone. This happens for real when a player leaves one server and joins another before the first one has saved.
The DataStore race

Two servers and one key. Drag GetAsync, SetAsync, UpdateAsync, leave and crash onto each timeline and press Run.
Order these events so the player loses coins.
Answer
1. Server A loads 100 coins 2. The player earns 20 more in A (120 in A's memory) 3. The player hops to server B, which loads 100 before A has saved 4. Server A saves 120 on leave 5. Server B saves 100 later, overwriting 120. B loaded before A's save landed, so B's copy is stale. Whatever B writes last replaces A's 120. A session lock stops B from loading until A has saved and let go.
Open this step in lesson mode · Link to this step · This confused me
5A sign-out sheet on the vault
DataService writes two extra fields into the record: sessionJob, the JobId of the server that holds the player, and sessionAt, when it took the lock. Another server that finds a lock younger than 45 seconds, owned by a different JobId, leaves the record alone and keeps that visit's coins in memory only.
| In the picture | In Roblox |
|---|---|
| The sign-out sheet | The sessionJob and sessionAt fields in the record |
| Another teller reading the sheet and waiting | Another server seeing a fresh lock and leaving the record alone |
| The sheet going stale | The lock expiring after 45 seconds |
A session lock is a sign-out sheet on the vault door: "Server A has this account, signed at 14:02." Another server reads the sheet and waits. The 45-second expiry is there because a crashed server never comes back to sign the account back in.
Think of it as The vault sign-out sheet: Server A has this account, signed at 14:02
Stored dataRemember: Session lock is the vault sign-out sheet: Server A has this account, signed at 14:02.
local function lockHeld(record: StoredProfile): boolean
local owner = sessionOwner(record)
local at = sessionAge(record)
return owner ~= nil and owner ~= "" and owner ~= game.JobId and at ~= nil and os.time() - at < LOCK_SECONDS
Where does it break?“The vault sign-out sheet: Server A has this account, signed at 14:02” is a good picture of session lock. Where does it stop being true?
It breaks here. Nobody enforces the sheet; it only works because every server that touches the key checks it, and an unrenewed lock looks expired.
The true model. A session lock records which server holds a player's data so two servers do not write it at once. Beacon Yard's hand-rolled lock expires after 45 seconds so a crashed server cannot hold a key forever. ProfileStore renews its lock with an autosave every 300 seconds.
Nobody enforces the sheet. It works only because every server that touches the key checks it. And a lock needs renewing: Roblox's guide says to keep accessing the key while the data is in memory, usually from an autosave loop2. DataService takes its lock at join and refreshes it only when something calls DataService.save, such as a Coin Pack purchase. Read lockHeld with that in mind.
A player has been in server A for ten minutes, and no save has refreshed sessionAt since they joined. Server B checks the key. What does lockHeld return on B?
Answer
false: sessionAt is ten minutes old, past the 45-second window, so B may claim the key. The check only looks at age and owner. Without an autosave that refreshes sessionAt, a long session's lock looks expired. This is the gap ProfileStore closes in the next lesson: it saves and renews every few minutes.
Open this step in lesson mode · Link to this step · This confused me
6Never save over a failed load
The worst DataStore bug is quiet. A load fails, the server gives the player a blank profile, and on leave it saves that blank profile over their real one. DataService prevents this with one table, savable: a player's key is only written if the load succeeded and this server owns the lock.
The load for player 42 throws a network error. What does onPlayerRemoving do later?
savable[42] = false -- the claim failed
-- ... player plays, earns 30 coins ...
saveUser(42, profile, true)
Answer
Returns false without writing; the stored record keeps its real coins. saveUser returns false at once when savable is not true. The player loses the 30 coins from this visit, which is bad, but keeps everything they had, which matters far more.
Open this step in lesson mode · Link to this step · This confused me
7A prepaid data plan
Every DataStore call spends from a budget that refills each minute. For standard stores, the whole experience gets 300 + 40 × concurrent users reads per minute and 300 + 20 × concurrent users writes per minute, shared with Open Cloud. UpdateAsync spends one of each. Each server also has its own default limit of 60 + 40 × players per minute for reads and for writes. Past the budget, calls queue; each queue holds 30 requests, and beyond that they fail with errors 301 to 3063.
| In the picture | In Roblox |
|---|---|
| The plan | The per-minute request budget, such as 300 + 40 x concurrent users reads |
| Running out | Calls queuing, up to 30 per queue |
| Calls being dropped | Errors 301 to 306 once a queue is full |
The budget is a prepaid data plan that tops up every minute. Spend it all and your calls wait in line; if the line is full, they are dropped.
Think of it as A prepaid data plan that tops up every minute
-- Per-minute standard DataStore budgets for the whole experience.
local function reads(ccu) return 300 + 40 * ccu end
local function writes(ccu) return 300 + 20 * ccu end
local ccu = 50
print("reads " .. reads(ccu) .. " writes " .. writes(ccu))
print("writes per player per minute " .. writes(ccu) / ccu)
-- A server shutting down saves all its players at once:
-- each UpdateAsync spends one read and one write.
local onShutdown = 12
print("burst of " .. onShutdown .. " saves uses " .. onShutdown .. " reads and " .. onShutdown .. " writes")
reads 2300 writes 1300
writes per player per minute 26
burst of 12 saves uses 12 reads and 12 writesKeys and store names are limited to 50 characters, and a value to 4,194,304 characters. One key can also move at most 25 MB a minute when read and 4 MB a minute when written, across all servers. The whole experience has a storage limit of 500 MB plus 1 MB for each player who has ever joined3. Beacon Yard's record is a few numbers, so size is never the risk. The budget looks generous per player, about 26 writes a minute at 50 players, but it is shared by every server and by Open Cloud, and it is spent in bursts: everyone leaving at once, or a shutdown saving a full server. Save at the moments that matter, not on every coin.
A Beacon Yard server has 8 players. What is its default per-server limit for standard reads per minute?
Answer
380. 60 + 40 × 8 = 380 reads per minute on that server, inside the larger experience-wide budget.
Open this step in lesson mode · Link to this step · This confused me
8When to save
Roblox's best practices give four moments: load once when the player joins, save when they leave, save when the server shuts down, and save at checkpoints that matter, such as a purchase4. Add an autosave every few minutes so a crash loses little and the lock stays fresh.
DataService saves on PlayerRemoving and in game:BindToClose, tries a failed save up to 4 times (1 initial try and 3 retries) one second apart, and releases the lock in the final save by writing sessionJob = "" and sessionAt = 0.
During Play in Studio, reading the stored record back from the server command bar with GetAsync prints JSON in this shape:
{"coins":15,"speedOwned":false,"sessionJob":"","sessionAt":<current os.time()>}
During Play in Studio, GetAsync prints a record with sessionAt set to the current os.time() and sessionJob equal to "". Why is sessionJob empty here?
Answer
game.JobId is an empty string in Studio, so a Studio server writes "" even while holding the lock. A releasing save writes both sessionJob = "" and sessionAt = 0. When sessionAt is non-zero and sessionJob is "", the record was written by Studio, where game.JobId is always "".
Open this step in lesson mode · Link to this step · This confused me
9What pros use
Beacon Yard writes its own data layer so you can see every moving part. Most shipped games use a library that has already met every edge case.
Other ways pros do this
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Hand-rolled (DataService) | Your own GetDataStore, UpdateAsync, lock and retry code. | Learning, very small games, or unusual data that no library fits. | Every edge case is yours: lock renewal, autosave, shutdown, duplicates. |
| ProfileStore | loleris's session-locked profile module, the successor to ProfileService. | Most games with player data; the next lesson migrates Beacon Yard to it. | Its own record format and rules to learn; not for leaderboards or global state. |
| ProfileService (legacy) | ProfileStore's predecessor. | Only in games that already use it. | Superseded by ProfileStore; do not start new work with it. |
| DataStore2 (legacy) | An older caching and backup wrapper by Kampfkarren. | Maintaining an older game. | Repository last updated in 2023; no session locking. |
Which of these does Beacon Yard's DataService already do?
Answer
Wrap every DataStore call in pcall; Refuse to save a key whose load failed; Release the lock in the final save; Try a save up to 4 times when it fails. It has pcall everywhere, the savable guard, the releasing save and up to 4 save attempts. It has no autosave loop, which is why its lock can look expired during a long session.
Open this step in lesson mode · Link to this step · This confused me
10Build along: see your record
Build along
src/server/DataService.luau
Publish your copy of the place to Roblox as a private experience (File, Publish to Roblox). DataStores only work in a published place.
You should see Creator Hub lists the place, and Studio's title bar shows its name instead of a local file.
Open File > Experience Settings, choose Security, and turn on Enable Studio Access to API Services. Use a test experience, never a live one: Studio now writes to real keys.
You should see Experience Settings, Security shows Enable Studio Access to API Services switched on.
Play, collect three coins, stop, and play again. Check the leaderboard.
You should see Output shows your coin count, then the same count after you stop and play again.
During Play, switch the command bar to the server and run
print(game:GetService("HttpService"):JSONEncode(game:GetService("DataStoreService"):GetDataStore("BeaconYard_v1"):GetAsync(tostring(game.Players:GetPlayers()[1].UserId)))).You should see Output prints one JSON string with coins, speedOwned, sessionJob and sessionAt.
Open this step in lesson mode · Link to this step · This confused me
11Challenges
Level 2, Builder
Challenge
Add the autosave DataService is missing, so its lock stays fresh during long sessions.
- Start from
- The game at milestone m06 (download)
Done means
- DataService saves every player's profile on a timer shorter than LOCK_SECONDS without releasing the lock (for example, raise LOCK_SECONDS to 180 and save every 120 seconds, or save every 30 seconds for the 45-second lock)
- The loop skips players whose key is not savable
- A save failure only warns; the loop keeps running
Hints
- DataService.save already saves without releasing.
- task.spawn one loop in DataService.start.
- LOCK_SECONDS starts at 45 in m06. Your autosave interval must be shorter than LOCK_SECONDS, or the lock expires between saves.
Level 3, Professional
Challenge
Add a daily reward that is saved with the profile. Grade it on a branch from m14-ship (where ProfileStore runs DataService, covered in the next lesson) in a published place with API Services enabled. The test is challenges/datastores.luau, and the solution is challenges/solutions/datastores.md.
- Start from
- The game at milestone m14 (download)
- Grade it
- In Studio, press Play, then run
game.ServerScriptService.RunGameTests:Invoke("datastores", "datastores-daily")in the server command bar. Copy the pass code from Output.
Done means
- DataService.claimDaily(player) returns granted and the new coin count
- The first claim of a day adds 15 coins, updates leaderstats and saves via DataService.save(player); a second claim the same day adds nothing
- Self-check, the test does not grade it: if DataService.save(player) fails, claimDaily rolls back the coins and lastDailyDay
- DataService.readSaved(player.UserId) returns the saved lastDailyDay and coins, and challenges/datastores.luau prints TEST PASS for every check
Hints
- The day is workspace:GetAttribute("TestDailyDay") when set, else math.floor(os.time() / 86400).
- Add lastDailyDay: number? to ProfileData in src/server/DataMigration.luau so strict Luau allows the field on m14-ship.
- Call DataService.save(player) right after granting (in a published place with Studio Access to API Services enabled), and roll back if it returns false.
Suppose you add a lastDailyDay field to the record that m06's hand-rolled DataService saves. Why must its UpdateAsync transform copy that field into the table it returns?
Answer
The transform's return value replaces the whole record, so a field it leaves out is erased. The returned table is the new record. Any field you do not copy across is gone, which is how a forgotten field silently resets.
Open this step in lesson mode · Link to this step · This confused me
12Recap
Retiring the analogy
You no longer need “a teller who shows you the balance before you write the new amount”. UpdateAsync reads the current value, calls your function with it and writes the result. If the value changed while the write was in flight, it calls the function again with the newer value. Returning nil cancels the write.
Recap
- Keep the profile in server memory; load with UpdateAsync in pcall, and never save a key whose load failed.
- The last write wins, so a session lock (sessionJob and sessionAt, 45 seconds) stops a second server; it must be renewed while the player stays.
- Budgets refill every minute: 300 + 40 × CCU reads, 300 + 20 × CCU writes, 60 + 40 × players per server; save on leave, on shutdown and at checkpoints.
A DataStore is a bank vault in another city, until the vault keeps only the last write for a key, so two servers writing the same key can silently undo each other.
UpdateAsync is a teller who shows you the balance before you write the new amount, until the transform may run more than once, so it must not yield or do anything you cannot repeat, such as granting a badge.
Session lock is the vault sign-out sheet: Server A has this account, signed at 14:02, until nobody enforces the sheet; it only works because every server that touches the key checks it, and an unrenewed lock looks expired.
DataStore budget is a prepaid data plan that tops up every minute, until running out is not an immediate error: requests wait in a queue and get slower, and only fail once the queue is full.
Queued for review
Open this step in lesson mode · Link to this step · This confused me