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.

Concept lesson, about 70 minutes, 12 steps

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..

Figure 1.1.

Coins go up in memory, the session stops and saves, and the next session loads them.

Transcript
  1. 0:00 Coins increase in memory when you pick one up.
  2. 0:05 Stop ends the session and BindToClose saves if the key is savable.
  3. 0:10 The next Play loads the same coins.
  4. 0:20 GetAsync prints the row. The game writes it with UpdateAsync.

While you play, where does DataService.addCoins put a new coin?

  1. In the profile table in server memory; the DataStore is written later
  2. Straight into the DataStore on every pickup
  3. In leaderstats only
  4. In the client's memory
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.

Stored dataA DataStore is a bank vault in another city.
In the pictureIn Roblox
The vaultRoblox's DataStore service, outside your server
The trip to the cityA network call that takes time and can fail
The deposit slipSetAsync or UpdateAsync with a key

See the whole analogy cast

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
Figure 2.1

You play an unpublished copy of the place. What does DataService do?

  1. Warns once that the DataStore is unavailable and keeps coins in memory for this session
  2. Crashes the server script
  3. Saves to a local file instead
  4. Kicks the player
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.

Stored dataUpdateAsync is a teller who shows you the balance before you write the new amount.
In the pictureIn Roblox
The tellerUpdateAsync
The balance shown firstThe previous value passed to your transform
Being handed the slip backThe transform running again after a conflict

See the whole analogy cast

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(),
Figure 3.1
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

The DataStore race: a still of the simulation
Figure 4.1.

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.

  1. Server A saves 120 on leave
  2. The player hops to server B, which loads 100 before A has saved
  3. Server B saves 100 later, overwriting 120
  4. Server A loads 100 coins
  5. The player earns 20 more in A (120 in A's memory)
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.

Stored dataSession lock is the vault sign-out sheet: Server A has this account, signed at 14:02.
In the pictureIn Roblox
The sign-out sheetThe sessionJob and sessionAt fields in the record
Another teller reading the sheet and waitingAnother server seeing a fresh lock and leaving the record alone
The sheet going staleThe lock expiring after 45 seconds

See the whole analogy cast

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
Figure 5.1
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?

  1. false: sessionAt is ten minutes old, past the 45-second window, so B may claim the key
  2. true: A still holds the player
  3. It throws, because two servers cannot read one key
  4. true, because JobId never expires
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)
  1. Returns false without writing; the stored record keeps its real coins
  2. Writes 30 coins over the stored record
  3. Retries the load, then saves
  4. Writes 0 coins
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.

Stored dataDataStore budget is a prepaid data plan that tops up every minute.
In the pictureIn Roblox
The planThe per-minute request budget, such as 300 + 40 x concurrent users reads
Running outCalls queuing, up to 30 per queue
Calls being droppedErrors 301 to 306 once a queue is full

See the whole analogy cast

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

Luau
-- 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")
Figure 7.1. Expected output: reads 2300 writes 1300 writes per player per minute 26 burst of 12 saves uses 12 reads and 12 writes

Keys 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:

text
{"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?

  1. game.JobId is an empty string in Studio, so a Studio server writes "" even while holding the lock
  2. The last save released the lock and set sessionAt to 0
  3. The save failed
  4. The player is banned
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

OptionWhat it isWhen pros pick itTrade-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.
ProfileStoreloleris'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?

  1. Wrap every DataStore call in pcall
  2. Refuse to save a key whose load failed
  3. Release the lock in the final save
  4. Autosave every few minutes to renew the lock
  5. Try a save up to 4 times when it fails
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

m06-drone-wrench

  • src/server/DataService.luau
  1. 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.

  2. 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.

  3. 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.

  4. 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

  1. DataService.save already saves without releasing.
  2. task.spawn one loop in DataService.start.
  3. 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

  1. The day is workspace:GetAttribute("TestDailyDay") when set, else math.floor(os.time() / 86400).
  2. Add lastDailyDay: number? to ProfileData in src/server/DataMigration.luau so strict Luau allows the field on m14-ship.
  3. 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?

  1. The transform's return value replaces the whole record, so a field it leaves out is erased
  2. Because UpdateAsync only stores numbers
  3. To make the daily reward faster
  4. It does not need to; Roblox merges records
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

  1. Keep the profile in server memory; load with UpdateAsync in pcall, and never save a key whose load failed.
  2. 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.
  3. 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.

Next ProfileStore: the library pros use

Open this step in lesson mode · Link to this step · This confused me