Lesson 5 of 5
Beyond Roblox: HttpService, Secrets and your own backend
Call your own backend from a Roblox game server: HttpService, the secrets store, retries with backoff, rate limits, duplicate-safe messages and a round-summary outbox for Beacon Yard that survives an outage.
By the end you can
- Send a request from a game server with HttpService, and read what RequestAsync returns and when it throws
- Keep an API key in the experience's secrets store and use it in a header without ever seeing its value
- Post Beacon Yard's round summaries through a bounded queue with backoff, so the yard keeps playing when the backend is down
- Decide what a backend must check and what a summary may contain
Before this: Open Cloud automation: APIs, webhooks, data tools, Analytics: funnels, economy events, retention
Step 1 of 8
A drill ends. Who else should hear about it?
A Beacon Yard drill is 40 seconds of chase and 8 seconds of cooldown. When a drill starts, Roblox Analytics logs round_started for each player. Analytics answers questions inside the Creator Hub. A studio often wants more: every round from every game in one dashboard, joined with web sign-ups, with an alert in the team channel. That needs a backend of your own.
Before any code, one rule from the yard you already built. Look at how Analytics.luau calls Roblox:
local function safely(call: () -> ())
local failure = ""
-- xpcall, not pcall: a function that returns nothing gives pcall no
-- second value to read the error from.
local ok = xpcall(call, function(message: unknown)
failure = tostring(message)
end)
if ok or warned then
return
end
warned = true
warn("AnalyticsService is unavailable (" .. failure .. "). Analytics events were skipped.")
AnalyticsService starts throwing on every call during a busy evening. What happens in Beacon Yard?
Press 1 to 4 to choose, Enter to check.
The door out of Roblox is HttpServiceHttpServiceThe engine service a game server uses to send web requests to outside services and to some Open Cloud endpoints.Think of it as the yard's post room: letters go out, nothing comes in through it.. It sends web requests from game servers, never from a player's device. It is off until you turn on Allow HTTP Requests under File, Experience Settings, Security in Studio1. Beacon Yard uses it today for one thing only: QueueService calls HttpService:GenerateGUID(false) to give each match message it publishes a unique id. It has never sent a web request.
RequestAsync takes a table (Url, Method, Headers, Body) and returns Success, StatusCode, StatusMessage, Headers and Body. Success is true only for status codes 200 to 299. If the request times out or the target refuses it, RequestAsync throws instead, so it always goes inside pcall. External requests share a limit of 500 a minute per server; Open Cloud calls have a separate 2,5002.
There is no way in. Nothing in a game server listens for requests, so a backend that needs to reach live servers goes through Open Cloud, as Open Cloud automation: APIs, webhooks, data tools showed with messaging.
Suppose you posted one request per coin pickup. Six pads each respawn every 4 seconds (COIN_RESPAWN_SECONDS = 4). At most, how many pickup requests is that per minute, per server?
Step 2 of 8
Keys go in the secrets store
Your backend must only accept requests that carry a key, so strangers cannot pose as your game servers1. Where does the game keep that key? Not in a script (anyone with the place file or the repo can read it) and not in a data store.
Roblox gives every experience a secrets storeSecrets storeA per-experience store for API keys and passwords that server scripts can send in a request but never read or print.Think of it as a sealed envelope the courier carries to the door without anyone opening it.. The owner (or group owner) adds a secret on the Creator Hub under Secrets, Create Secret, with a name, the value and the domain it is for: a specific host such as my.example.com is better than *. Up to 500 secrets, 1,024 characters each3. A server script gets it with HttpService:GetSecret("BACKEND_KEY").
| In the picture | In Roblox |
|---|---|
| Dropping a letter in the tray and walking back to work | Pushing a round summary into a queue; the round loop never waits for a web request |
| The courier's rounds | A background loop that sends the queue a few times a minute, well under the 500-a-minute limit |
| A sealed envelope handed over at the door | A Secret from the secrets store: scripts carry it into a URL or header but cannot read or print it; only the receiving server sees the value |
Think of the game server's HTTP as a post room. Scripts drop letters in an outbox tray and go back to work. A courier takes them to the door. The key travels in a sealed envelope: the courier can carry it and hand it over, but nobody in the post room can open it.
Think of it as A post room's outbox tray, with the key sealed in an envelope only the courier carries
The store only works where it is safe. Live servers and collaborative testing can read it; a local playtest gets Can't find secret with given key unless you add Local Secrets in Studio's Experience Settings, Security, and a client script gets the same error3.
A live server runs this. The secret BACKEND_KEY exists in the experience's store. What does it print?
local HttpService = game:GetService("HttpService")
local key = HttpService:GetSecret("BACKEND_KEY")
print(key)
Press 1 to 4 to choose, Enter to check.
Step 3 of 8
One request, done right
A Secret goes into a request in two places only: the URL or the headers, never the body3. AddPrefix and AddSuffix build what the backend expects, such as key:AddPrefix("Bearer ") for an Authorization header.
Then read the answer. Three outcomes need three different reactions:
- It worked (2xx). Forget the batch.
- It might work later. The call threw (timeout, refused connection), or the backend said 408, 429 (too many requests) or a 5xx (it failed). Try again later.
- It will never work. Any other 4xx: a wrong key, a bad URL, a body the backend rejects. Retrying burns budget and changes nothing.
"Later" should not mean "at once". The guide recommends exponential backoffExponential backoffWaiting longer after each failed try (2 seconds, then 4, then 8) up to a cap, so a struggling service gets time to recover.Think of it as knocking again, but leaving a longer pause each time nobody answers.: wait 2 seconds, then 4, then 81. Add a cap so a long outage does not stretch the wait to hours. Run the schedule:
RequestAsync also accepts an optional Timeout in seconds, shorter than its default, which helps when you debug a request that hangs2.
With the three outcomes above, what does this print?
local function shouldRetry(status)
if status == nil then return true end
return status == 408 or status == 429 or (status >= 500 and status <= 599)
end
print(shouldRetry(429), shouldRetry(401), shouldRetry(nil))
Press 1 to 4 to choose, Enter to check.
Step 4 of 8
The yard never waits at the post office
Server sideRemember: Sending data from a game server to your own backend is a post room's outbox tray, with the key sealed in an envelope only the courier carries.
Where should the request go? Not inside RoundService. Its loop publishes each phase and then waits for the next one:
local function publish(phase: RoundPhase, endsAt: number)
Remotes.get("RoundState"):FireAllClients(phase, endsAt)
workspace:SetAttribute("RoundPhase", phase)
A request that hangs until it times out would sit in the middle of that timeline. So the round loop only drops a letter in the tray. A new BackendService listens for RoundPhase becoming Cooldown, builds a summary and pushes it into a queue. A background loop sends the whole queue in one request, at most 30 times a minute, retries with backoff and keeps at most 50 summaries, dropping the oldest when the backend has been down for a long time.
The summary carries counts, not people: an id, the end time, the round length and how many players were there. No names, no UserIds. Your backend gets what it needs for a dashboard, and nothing that identifies a player leaves Roblox.
Why does BackendService listen for the RoundPhase attribute instead of calling RequestAsync inside RoundService's runRound?
Press 1 to 4 to choose, Enter to check.
Step 5 of 8
Where the outbox picture breaks
Answer this before you open the breakdown below.
The backend saves a summary and answers 200, but the answer is lost and RequestAsync times out. BackendService retries. What should stop the round being counted twice?
Press 1 to 4 to choose, Enter to check.
Where does it break?“A post room's outbox tray, with the key sealed in an envelope only the courier carries” is a good picture of sending data from a game server to your own backend. Where does it stop being true?
It breaks here. A post room never throws a letter away and never delivers one twice. Your outbox drops the oldest summaries when it is full, and a retry after a lost answer can deliver the same summary twice, so each one carries an id the backend checks.
The true model. Outbound HTTP from a game server is unreliable by nature: queue it, send in the background, retry with backoff on transient failures only, bound the queue, give each message an id so duplicates are harmless, and keep keys in the secrets store.
The picture breaks a second way: a real post room never throws letters away, and yours does. A bounded queue that drops the oldest summary is a deliberate choice. Memory on a game server is shared with the yard, and a summary from an hour ago matters less than the drill running now. Make every message an idempotent requestIdempotent requestA request that has the same effect whether the server receives it once or several times.Think of it as a letter with a reference number: the second copy goes straight in the bin., and accept that some can be lost.
There is one more limit to the envelope. The secret is sealed inside the game, but the server you send it to sees it in full. Send it only to your own backend, and pick a domain for the secret instead of *.
Step 6 of 8
What your backend must do
The game side is half of it. The backend, whatever runs it, needs four habits:
- Check the key first. Compare the
Authorizationheader with its own copy and answer 401 to anything else. - Answer fast. Store the batch and return 2xx; do slow work afterwards.
- Drop repeats. Keep the ids it has seen and skip one it already stored.
- Return honest codes. 429 when it wants fewer requests, 5xx when it failed, 400 when the body is wrong. Your game's retry rules depend on it.
Other ways pros do this
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Serverless function | A small function the provider runs per request: Cloudflare Workers, AWS Lambda, Vercel Functions. | Low, bursty traffic like round summaries, and no server to look after. | Per-provider limits on run time and storage; the first request after a quiet spell can be slower. |
| Always-on server | Your own service on a virtual machine or container host. | Long-lived connections, custom databases, or steady heavy traffic. | You patch it, scale it and keep it up. |
| A third-party service's API | Send straight to an analytics or error-tracking product. | A quick start with a tool your team already uses. | Their key lives in your secrets store and their limits become yours; read what you may send them. |
| No backend | Roblox Analytics, data stores, MemoryStore and Open Cloud tools. | The data never needs to leave Roblox. | Nothing to run; you only get the views and joins Roblox offers. |
After you change the secret's value on the Creator Hub but not on the backend, what does BackendService do with each batch?
Press 1 to 4 to choose, Enter to check.
Step 7 of 8
Build along: the round outbox
You build this in your own copy of the finished game. First finish the level 3 challenge below, or at least its five functions, then copy challenges/work/backend_outbox.luau to src/server/Outbox.luau. This is the new service:
--!strict
-- Posts a summary of every finished drill to your own backend. The yard
-- never waits for it: a summary goes into a queue, and a background loop
-- sends the queue. If the backend is down, the yard plays on.
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Outbox = require(script.Parent.Outbox)
local Config = require(ReplicatedStorage.Shared.Config)
local BACKEND_URL = "https://httpbin.org/post" -- an echo service for now
local MAX_QUEUE = 50
local PER_MINUTE = 30
local BackendService = {}
local queue: { Outbox.Summary } = {}
local sentAt: { number } = {}
-- One POST. Returns the status code, or nil when RequestAsync threw.
local function send(key: Secret, batch: { Outbox.Summary }): number?
local ok, response = pcall(function()
return HttpService:RequestAsync({
Url = BACKEND_URL,
Method = "POST",
Headers = {
["Content-Type"] = "application/json",
["Authorization"] = key:AddPrefix("Bearer "),
},
Body = HttpService:JSONEncode({ rounds = batch }),
})
end)
if not ok then
return nil
end
return response.StatusCode
end
local function flushLoop(key: Secret)
local attempt = 0
while true do
local now = os.clock()
while sentAt[1] ~= nil and sentAt[1] <= now - 60 do
table.remove(sentAt, 1)
end
if #queue == 0 or not Outbox.underLimit(sentAt, now, PER_MINUTE, 60) then
task.wait(5)
continue
end
local batch = queue
queue = {}
table.insert(sentAt, now)
local status = send(key, batch)
if status ~= nil and status >= 200 and status <= 299 then
attempt = 0
elseif Outbox.shouldRetry(status) then
for _, summary in batch do
Outbox.push(queue, summary, MAX_QUEUE)
end
attempt += 1
warn(`BackendService: send failed ({status or "no answer"}), retry {attempt}`)
task.wait(Outbox.backoff(attempt, 2, 60))
else
warn(`BackendService: the backend refused the batch ({status}), dropped`)
end
end
end
function BackendService.start()
local ok, key = pcall(HttpService.GetSecret, HttpService, "BACKEND_KEY")
if not ok then
warn("BackendService: no BACKEND_KEY secret, so round summaries are off")
return
end
print("BackendService: key", key)
workspace:GetAttributeChangedSignal("RoundPhase"):Connect(function()
if workspace:GetAttribute("RoundPhase") ~= "Cooldown" then
return
end
local summary = Outbox.summary({
id = HttpService:GenerateGUID(false),
endedAt = os.time(),
roundSeconds = Config.ROUND_SECONDS,
players = Players:GetPlayers(),
})
local dropped = Outbox.push(queue, summary, MAX_QUEUE)
if dropped > 0 then
warn(`BackendService: queue full, dropped {dropped} old summaries`)
end
end)
task.spawn(flushLoop, key)
end
return BackendService

Select a numbered pin, or a row below, to read what it marks.
Experience Settings, Security: Allow HTTP Requests on, and a local secret for playtests.
Build along
src/server/Outbox.luausrc/server/BackendService.luausrc/server/init.server.luau
Turn on Allow HTTP Requests. Under Local Secrets, add
BACKEND_KEYwith a made-up value such ascourse-test-key, never a real key, and the domainhttpbin.orgif Studio asks for one.You should see With the place open, File, Experience Settings, Security shows Allow HTTP Requests on and BACKEND_KEY under Local Secrets.
Save the module as
src/server/BackendService.luau. Ininit.server.luau, require it and callBackendService.start()in the yard branch, afterAnnounceService.start(). Play and survive or lose one drill.You should see Press Play: the Output shows BackendService: key Secret(BACKEND_KEY), and after your first drill ends there is no warning from BackendService.
To see what httpbin received, print
response.Bodyinsidesendfor one run5. Read the echo, then remove the print. This is why the value was made up.You should see The echoed JSON shows your rounds array and an Authorization header of Bearer course-test-key: the receiving server sees the secret in full.
Set
BACKEND_URLtohttps://backend.invalid/rounds. The.invalidtop-level domain is reserved and never resolves6, so this is a backend that is always down. Play two drills, then put the httpbin URL back.You should see Drills, coins and the shop work as before. The Output shows send failed (no answer), retry 1, then retry 2 and retry 3, each after a longer wait, and the summaries wait in the queue.
Step 8 of 8
Challenges and recap
Fix the backoff in this cell. It has two bugs: the first retry waits too long, and nothing stops the wait from growing past the cap.
Level 1, Apprentice
Challenge
Fix backoff in the backoff-check cell so all three tests pass.
- Start from
- The game at milestone m14 (download)
- Check it here
- Run the code cell; the challenge completes when it passes. No Studio needed.
Done means
- Attempt 1 waits baseSeconds, and each attempt after it doubles the wait
- No wait is longer than capSeconds
- All three assertions in backoff-check pass
Put one pass of BackendService's flush loop in order, for a batch that fails with a 503.
- POST the batch with the Bearer secret inside pcall
- Take the whole queue as the batch and record the send time
- Forget request times older than 60 seconds and check the queue is not empty and the budget has room
- Wait the backoff for this attempt before the next pass
- Read 503 as worth a retry and push the summaries back into the bounded queue
Level 2, Builder
Challenge
Replace httpbin with a backend of your own. Any provider in the Alternatives above works; keep it to the four habits from the last step. There is no Luau test for this one: the proof is two rounds, stored once each.
- Start from
- The game at milestone m14 (download)
Done means
- A small HTTPS endpoint you deploy (any serverless provider) accepts POST with a JSON body
- It answers 401 unless the Authorization header is Bearer plus the key it holds
- It stores each summary by id and ignores an id it already has, answering 2xx either way
- The game's secret BACKEND_KEY in the Creator Hub secrets store holds the same key, with your endpoint's domain
- In a published test place, two drills show up once each in your endpoint's storage or logs
Meet the criteria above, then record your own result. No test grades this check.
Level 3, Professional
Challenge
Write the five rules in challenges/work/backend_outbox.luau. They send nothing, so the test needs no secret and no backend. The written solution is challenges/solutions/http-and-secrets.md. In Play, run game.ServerScriptService.RunGameTests:Invoke("http-and-secrets", "http-outbox-rules") and paste the pass code here.
- Start from
- The game at milestone m14 (download)
- Grade it
- In Studio, press Play, then run
game.ServerScriptService.RunGameTests:Invoke("http-and-secrets", "http-outbox-rules")in the server command bar. Copy the pass code from Output.
Done means
- shouldRetry retries nil, 408, 429 and 5xx, and nothing else
- backoff doubles from the base, starts at the base for attempt 1 or lower, and never passes the cap
- push appends, drops the oldest until the queue fits and returns how many it dropped
- underLimit counts only requests newer than the window and allows one more below the limit
- summary keeps exactly id, endedAt, roundSeconds and playerCount, with no names or UserIds
- challenges/http-and-secrets.luau prints TEST PASS for every check
Retiring the analogy
You no longer need “a post room's outbox tray, with the key sealed in an envelope only the courier carries”. Outbound HTTP from a game server is unreliable by nature: queue it, send in the background, retry with backoff on transient failures only, bound the queue, give each message an id so duplicates are harmless, and keep keys in the secrets store.
Recap
- HttpService sends requests from game servers only, after Allow HTTP Requests; RequestAsync throws on a timeout or refusal, so it always runs in pcall. External requests share 500 a minute per server.
- Keys live in the secrets store: GetSecret returns a Secret that prints as its name and goes only into a URL or header. Local playtests need Local Secrets; clients get an error.
- Retry no answer, 408, 429 and 5xx with exponential backoff and a cap; drop other 4xx.
- The round loop never waits: BackendService listens for RoundPhase, queues a summary with an id and no player data, and a background loop sends it within a budget.
- Duplicates and dropped summaries are normal, so the backend checks the key, answers fast and ignores ids it has seen.
Sending data from a game server to your own backend is a post room's outbox tray, with the key sealed in an envelope only the courier carries, until a post room never throws a letter away and never delivers one twice. Your outbox drops the oldest summaries when it is full, and a retry after a lost answer can deliver the same summary twice, so each one carries an id the backend checks.
Queued for review
- AnalyticsService starts throwing on every call during a busy evening. What happens in Beacon Yard?
- A live server runs this. The secret BACKEND_KEY exists in the experience's store. What does it print?
- With the three outcomes above, what does this print?
- Why does BackendService listen for the RoundPhase attribute instead of calling RequestAsync inside RoundService's runRound?
- The backend saves a summary and answers 200, but the answer is lost and RequestAsync times out. BackendService retries. What should stop the round being counted twice?
Next Architecture for a big codebase: lifecycles, dependencies, frameworks