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.

Lab lesson, about 75 minutes, 8 steps

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

1A 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.")
Figure 1.1

AnalyticsService starts throwing on every call during a busy evening. What happens in Beacon Yard?

  1. One warning in the server log, the events are skipped, and drills, coins and the shop carry on
  2. The server shuts down so no analytics are lost
  3. Every call warns, so the log fills with thousands of lines
  4. The round loop stops at the first failed call
Answer

One warning in the server log, the events are skipped, and drills, coins and the shop carry on. Analytics is nice to have, so a failure costs one warning and nothing else. A backend you call over HTTP must follow the same rule, and it fails far more often.

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.

Requests go out, messages come back through Open CloudA copper game server box sends an arrow labelled RequestAsync to a gold backend box. A dashed arrow from the backend goes to a cyan Open Cloud box, which sends a dashed arrow back to the game server.RequestAsyncif neededmessageGame serverHttpServiceYour backendchecks the keyOpen Cloudmessaging API
Figure 1.2. The game server calls out. The backend reaches live servers only through Open Cloud 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?

Answer

90 requests. 6 × 15 = 90 a minute, from one system, before anything else in the server sends a request. Batch instead: one summary per round is about one request a minute.

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

2Keys 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").

Server sideSending 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.
In the pictureIn Roblox
Dropping a letter in the tray and walking back to workPushing a round summary into a queue; the round loop never waits for a web request
The courier's roundsA 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 doorA 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

See the whole analogy cast

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)
  1. Secret(BACKEND_KEY)
  2. The key's value
  3. nil
  4. An error: secrets cannot be printed
Answer

Secret(BACKEND_KEY). print(secret) shows Secret(BACKEND_KEY). You cannot read or slice the value; you can only add a prefix or suffix and send it.

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

3One 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:

Luau
local function backoff(attempt, baseSeconds, capSeconds)
	return math.min(capSeconds, baseSeconds * 2 ^ (attempt - 1))
end
 
local waits = {}
for attempt = 1, 6 do
	table.insert(waits, backoff(attempt, 2, 60))
end
print(table.concat(waits, " "))
Figure 3.1. Expected output: 2 4 8 16 32 60

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))
  1. true false true
  2. true true true
  3. false false true
  4. true false false
Answer

true false true. Retry the outcomes that time can fix: no answer, 408, 429 and 5xx. Log and drop anything else.

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

4The 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)
Figure 4.1

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?

  1. RequestAsync yields until an answer or a timeout, so an inline call could delay Cooldown and the next drill, and an uncaught error could end the loop
  2. RoundService cannot use HttpService because it is a ModuleScript
  3. Attributes send the summary to the backend automatically
  4. RequestAsync only works inside event handlers
Answer

RequestAsync yields until an answer or a timeout, so an inline call could delay Cooldown and the next drill, and an uncaught error could end the loop. Keep web calls off the gameplay path. RoundService already publishes RoundPhase, so a listener gets the moment for free and cannot slow a drill down.

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

5Where 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?

  1. Each summary carries an id from HttpService:GenerateGUID, and the backend ignores an id it already stored
  2. Never retry after a timeout
  3. Retry only after 60 seconds
  4. Send the summary in the URL instead of the body
Answer

Each summary carries an id from HttpService:GenerateGUID, and the backend ignores an id it already stored. Retries and lost answers make duplicates normal. Give every message an id and let the receiver drop repeats.

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

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

6What your backend must do

The game side is half of it. The backend, whatever runs it, needs four habits:

  1. Check the key first. Compare the Authorization header with its own copy and answer 401 to anything else.
  2. Answer fast. Store the batch and return 2xx; do slow work afterwards.
  3. Drop repeats. Keep the ids it has seen and skip one it already stored.
  4. 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

OptionWhat it isWhen pros pick itTrade-offs
Serverless functionA 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 serverYour 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 APISend 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 backendRoblox 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?

  1. The backend answers 401, shouldRetry says no, and the batch is logged and dropped until the keys match again
  2. It retries the batch forever with backoff
  3. Roblox refuses to send the request because the secret changed
  4. The yard pauses drills until the backend accepts the key
Answer

The backend answers 401, shouldRetry says no, and the batch is logged and dropped until the keys match again. A key mismatch is a final error. The game logs it and carries on; you fix it by making the two sides agree, and rotate with an overlap next time.

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

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

luau
--!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
Roblox Studio
Roblox Studio's Experience Settings window on the Security page, with Allow HTTP Requests switched on and the Local Secrets section listing one secret named BACKEND_KEY.

Select a numbered pin, or a row below, to read what it marks.

Figure 7.1.

Experience Settings, Security: Allow HTTP Requests on, and a local secret for playtests.

Build along

m14-ship

  • src/server/Outbox.luau
  • src/server/BackendService.luau
  • src/server/init.server.luau
  1. Turn on Allow HTTP Requests. Under Local Secrets, add BACKEND_KEY with a made-up value such as course-test-key, never a real key, and the domain httpbin.org if 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.

  2. Save the module as src/server/BackendService.luau. In init.server.luau, require it and call BackendService.start() in the yard branch, after AnnounceService.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.

  3. To see what httpbin received, print response.Body inside send for 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.

  4. Set BACKEND_URL to https://backend.invalid/rounds. The .invalid top-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.

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

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

Luau
local function backoff(attempt, baseSeconds, capSeconds)
	-- Bugs: attempt 1 should wait baseSeconds, and no wait may pass capSeconds.
	local seconds = baseSeconds * 2 ^ attempt
	return seconds
end
 
print(backoff(1, 2, 60), backoff(3, 2, 60), backoff(10, 2, 60))
Figure 8.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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 in the lesson view; 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

Hints

  1. 2 ^ (attempt - 1) is 1 for the first attempt.
  2. math.min(capSeconds, ...) keeps the cap.
Solution
luau
local seconds = math.min(capSeconds, baseSeconds * 2 ^ (attempt - 1))

Put one pass of BackendService's flush loop in order, for a batch that fails with a 503.

  1. POST the batch with the Bearer secret inside pcall
  2. Take the whole queue as the batch and record the send time
  3. Forget request times older than 60 seconds and check the queue is not empty and the budget has room
  4. Wait the backoff for this attempt before the next pass
  5. Read 503 as worth a retry and push the summaries back into the bounded queue
Answer

1. Forget request times older than 60 seconds and check the queue is not empty and the budget has room 2. Take the whole queue as the batch and record the send time 3. POST the batch with the Bearer secret inside pcall 4. Read 503 as worth a retry and push the summaries back into the bounded queue 5. Wait the backoff for this attempt before the next pass. Check the budget, send once, sort the outcome, and wait longer after each failure. A 2xx would reset the attempt count; a 401 would drop the batch.

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

Hints

  1. Test the endpoint from your terminal with curl and a wrong key first: it must answer 401.
  2. Local playtests use Local Secrets; a published test place reads the Creator Hub secret.
  3. Keep the key out of the endpoint's code too: use the provider's own secret or environment setting.

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

Hints

  1. A nil status means RequestAsync threw, so treat it like a 503.
  2. In underLimit, a request exactly windowSeconds old is outside the window: count t > now - windowSeconds.
  3. Build the summary table field by field instead of copying the round.

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

  1. 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.
  2. 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.
  3. Retry no answer, 408, 429 and 5xx with exponential backoff and a cap; drop other 4xx.
  4. 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.
  5. 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.

Next Architecture for a big codebase: lifecycles, dependencies, frameworks

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