Lesson 11 of 11
Capstone, part 3: multi-product receipts and party matchmaking
Part 3 of the Beacon Yard capstone replaces basic single-product and solo-queue drills with two harder systems from scratch: a multi-product receipt router with rollback and an atomic party matchmaker.
By the end you can
- Design and pass a multi-product ProcessReceipt router that handles catalog lookup, replay SKU deduplication, and rollback on save or receipt-write failure
- Design and pass an atomic party matchmaking planner that never splits friend groups, handles oversized parties without head-of-line blocking, and respects wait timeouts
- Grade both systems in the browser Luau runner or in Studio with challenges/capstone_catalog.luau and challenges/capstone_party_queue.luau
Before this: Capstone, part 2: cosmetic pass trail, localization and thumb targets, MemoryStore and MessagingService: matchmaking across servers, Monetization: products, passes, subscriptions, economy
1Project 5: multi-product receipts with two-step failure rollback
The Coin Pack handler had a gap before m14-ship. In m12-money and m13-art-pass it saved the profile and then wrote the purchase id as a separate r_<purchaseId> row. A server that stopped between the two writes left the coins saved and no record, so the redelivered receipt paid again. That crash window is what the drill below makes you reason about.
Stored dataRemember: ProcessReceipt is a courier who keeps coming back until you sign.
At m14-ship the id lives in the profile itself (recentPurchaseIds, the last 50). ReceiptRules.applyReceipt adds the coins and the id in one step, a repeat delivery finds the id and grants nothing, and undoReceipt takes the grant back when the save fails. Look at how MonetizationService.luau handles it1.
local applied = ReceiptRules.applyReceipt(data, receipt, Config.COIN_PACK_COINS)
if applied == nil then
-- The id appeared in the profile while the old row was being read.
return granted
end
DataService.syncCoins(player)
if not DataService.save(player) then
ReceiptRules.undoReceipt(data, receipt, Config.COIN_PACK_COINS, applied)
DataService.syncCoins(player)
return notYet
The safe order from Roblox's guide to atomic purchase handling2 keeps the receipt id inside the player's own saved data, the same order as the monetization lesson:
- Check the purchase id is not already recorded in the player's data. If it is, and that record was saved, return
PurchaseGranted. - Add the coins to the player's data in memory.
- Write the purchase id into that same player data.
- Save that one record and wait for the save to land.
- Return
PurchaseGrantedonly if the save worked. Otherwise returnNotProcessedYet.
One write carries both facts, so a crash leaves both or neither. The drill below keeps two flags, saveOk and recordOk, only so the test can fail each write on purpose. It shows the logic's shape, not that two writes are safe.
Now extend that single-product handler to a product catalog ({ [productId] = { coins = ..., sku = ... } }) that returns three values: (newBalance, decision, analyticsSku). Notice the extra rule for replays: when seen[purchaseId] is already true, return (balance, "PurchaseGranted", nil) so Roblox stops redelivering AND your economy funnel does not log the same purchase twice.
A player buys BigPack (150 coins, sku 'BigPack'). The first call succeeds and marks seen['p-9'] = true. Roblox delivers 'p-9' a second time. What must ReceiptCatalog.process return?
Answer
Unchanged balance, 'PurchaseGranted', and nil for the analytics SKU. Returning PurchaseGranted tells Roblox the delivery succeeded. Returning nil for the SKU stops your caller from logging a duplicate IAP coinSource event.
A test receipt arrives with productId = 0. What should ReceiptCatalog.process return?
Answer
Unchanged balance, 'NotProcessedYet', and nil, without adding the purchaseId to seen. Reject productId <= 0 or unknown catalog keys before touching seen or balance so a misconfigured product never consumes a receipt.
Open this step in lesson mode · Link to this step · This confused me
2Build and grade the multi-product receipt router
Complete process in the browser cell below. To grade it in Studio, copy your code into challenges/capstone_catalog_work.luau, press Play and run game.ServerScriptService.RunGameTests:Invoke("capstone_catalog", "capstone-catalog") in the server command bar.
-- Return (newBalance, decision, sku).
-- Reject productId <= 0 or missing catalog entries with NotProcessedYet.
-- Replays return (balance, "PurchaseGranted", nil).
-- If saveOk is false OR recordOk is false, roll back: leave balance and seen
-- untouched and return (balance, "NotProcessedYet", nil).
-- Two flags stand in for two writes so the test can fail each one. A real
-- server keeps the coins and the purchase id in one saved table.
local function process(balance, seen, catalog, purchaseId, productId, saveOk, recordOk)
local entry = catalog[productId]
if entry == nil then
return balance, "NotProcessedYet", nil
end
seen[purchaseId] = true
return balance + entry.coins, "PurchaseGranted", entry.sku
end
Level 3, Professional
Challenge
Pass the browser cell above (and optionally challenges/capstone_catalog.luau in Studio). Solution: challenges/solutions/capstone-systems.md.
- 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.
- Or grade it in Studio
- In Studio, press Play, then run
game.ServerScriptService.RunGameTests:Invoke("capstone_catalog", "capstone-catalog")in the server command bar. Copy the pass code from Output.
Done means
- Product id 0 or any id missing from catalog returns (balance, NotProcessedYet, nil) without touching seen
- A first valid purchase with saveOk == true and recordOk == true grants entry.coins, marks seen[purchaseId], and returns PurchaseGranted with entry.sku
- A replay of the same purchaseId adds 0 coins and returns PurchaseGranted with nil SKU
- When saveOk == false or recordOk == false, balance and seen stay unchanged and NotProcessedYet is returned so a later retry pays cleanly
Hints
- Check productId <= 0 and catalog[productId] == nil first.
- Check seen[purchaseId] == true BEFORE checking saveOk or mutating balance.
- Only set seen[purchaseId] = true and add entry.coins after both saveOk and recordOk are true.
Where does it break?“A courier who keeps coming back until you sign” is a good picture of processreceipt. Where does it stop being true?
It breaks here. You decide what a duplicate looks like: without a stored purchase id, a redelivered receipt grants twice, and a record saved apart from the coins leaves a gap.
The true model. ProcessReceipt is one callback, set once from a server script (BindReceiptHandler is the newer route). Record the purchase id in the same save as the grant, then return PurchaseGranted. NotProcessedYet leaves the receipt unresolved: it returns on a rejoin or the next purchase, not on a timer.
Why must a failed receipt write (saveOk == true, recordOk == false) roll back the coins before returning NotProcessedYet?
Answer
Because Roblox will retry the same purchaseId, and without a stored receipt record the retry would pay the coins a second time. If the profile kept the coins while the receipt write failed, the retry sees no receipt record and grants the pack a second time. Rolling back on record failure keeps the retry idempotent, as long as the server is still running to roll back.
The server crashes after the profile save succeeded but before the receipt record was written. Roblox delivers the same receipt again. Which design pays the player only once?
Answer
Store the purchase id inside the player's profile and write coins and id in one save. Two durable writes always have a gap between them, and a crash in the gap cannot be rolled back. Keeping the purchase id in the same saved table as the coins means one write carries both facts.
Open this step in lesson mode · Link to this step · This confused me
3Project 6: atomic party matchmaking from scratch
In m11-two-places, MatchRules.plan groups individual QueueItems into matches of size, launching early when the oldest player has waited waitSeconds.
function MatchRules.plan(items: { QueueItem }, now: number, size: number, waitSeconds: number): { number }?
local group: { number } = {}
local seen: { [number]: boolean } = {}
local oldest = math.huge
for _, item in items do
if not seen[item.userId] and #group < size then
seen[item.userId] = true
table.insert(group, item.userId)
oldest = math.min(oldest, item.at)
end
end
if #group == 0 then
return nil
Real multiplayer games let friends join as parties. A party { members = { 1, 2, 3 }, at = 100 } is atomic: you can never send player 1 to match A and players 2, 3 to match B. Write planMatches(parties, now, maxSize, minPlayers, waitSeconds) with five rules:
- Deduplicate
userIds across all parties in join order (first appearance wins); drop any party left empty. Never mutate the caller's input tables. - Never split a party across two matches.
- A party larger than
maxSizecannot fit in any match; leave it inwaitingwithout blocking smaller parties behind it. - Build matches greedily in join order: start a match with the earliest unused party that fits, then scan later unused parties in join order to fill remaining seats up to
maxSize. - Emit a match when
#players == maxSize, or when#players >= minPlayersandnow - oldestAt >= waitSeconds. Otherwise leave its parties inwaiting, preserving join order.
Other ways pros do this
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Pure Luau planner + MemoryStoreQueue + MessagingService | Beacon Yard's m11 architecture: pure matching logic in MatchRules wrapped by thin Roblox service calls in QueueService. | Custom party rules, skill buckets, or deterministic unit tests in Jest-Lua. | You manage queue expiry, hide windows and cross-server teleport coordination yourself. |
| Roblox MatchmakingService | Managed engine matchmaking with configurable scoring attributes. | Large games that want Roblox to group players into existing servers automatically without a custom lobby place. | Less control over custom lobby scenes, party-split edge cases and reserved-server handoffs. |
Queue: Party A {1,2,3} at t=100, Party B {4,5} at t=101, Party C {6} at t=102. With now=105, maxSize=4, minPlayers=2, waitSeconds=20, what does planMatches return?
Answer
One match {1,2,3,6} and waiting {4,5}. Party A takes 3 seats. Party B (2 players) will not fit without splitting, so it stays waiting. Party C (1 player) fills the 4th seat, launching {1,2,3,6} while {4,5} waits intact.
A 5-player party sits at the front of a queue whose maxSize is 4, followed by two 2-player parties. What should planMatches do?
Answer
Leave the 5-player party in waiting and launch a match with the two 2-player parties behind it. Skipping parties larger than maxSize keeps them intact in waiting while allowing smaller parties behind them to form matches.
Open this step in lesson mode · Link to this step · This confused me
4Build and grade the atomic party matchmaker
Write planMatches in the browser cell below. To grade it in Studio, copy it into challenges/capstone_party_queue_work.luau, press Play and run game.ServerScriptService.RunGameTests:Invoke("capstone_party_queue", "capstone-party-queue") in the server command bar.
-- Return (matches, waiting).
-- Never split a party, never mutate input tables, drop duplicate userIds
-- (first appearance wins), and skip oversized parties without blocking.
local function planMatches(parties, now, maxSize, minPlayers, waitSeconds)
return {}, parties
end
Level 3, Professional
Challenge
Pass the browser cell above (and optionally challenges/capstone_party_queue.luau in Studio). Solution: challenges/solutions/capstone-systems.md.
- 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.
- Or grade it in Studio
- In Studio, press Play, then run
game.ServerScriptService.RunGameTests:Invoke("capstone_party_queue", "capstone-party-queue")in the server command bar. Copy the pass code from Output.
Done means
- A 3-player party followed by a 2-player party and a solo produces match {1,2,3,6} and leaves {4,5} waiting intact
- After waitSeconds, a partial group with at least minPlayers launches; a group below minPlayers stays waiting
- An oversized party (> maxSize) stays in waiting and does not block smaller parties behind it
- Duplicate userIds across or inside parties count once (first appearance wins), and caller input tables are never mutated
Hints
- First build a clean list of copied parties with unique userIds so you never mutate the caller's tables.
- Track a boolean table used[i] as you greedily pack each match from index i forward.
- Only mark picked indices as used when count == maxSize or (count >= minPlayers and now - oldest >= waitSeconds).
Why do studios keep both the receipt decision logic and the party planner in pure Luau modules with zero Roblox service calls?
Answer
Every tricky edge case (save rollback, oversized parties, timeouts) can be proved in milliseconds by unit tests before wiring thin Roblox service wrappers around them. Pure functions take plain tables and timestamps, so unit tests can reproduce save failures, timeouts and oversized parties deterministically in milliseconds. The service module around them stays thin.
Open this step in lesson mode · Link to this step · This confused me
5Recap
Retiring the analogy
You no longer need “a courier who keeps coming back until you sign”. ProcessReceipt is one callback, set once from a server script (BindReceiptHandler is the newer route). Record the purchase id in the same save as the grant, then return PurchaseGranted. NotProcessedYet leaves the receipt unresolved: it returns on a rejoin or the next purchase, not on a timer.
Recap
- Project 5 builds a multi-product receipt router that rejects unknown or zero products, deduplicates analytics SKUs on replays, and rolls back cleanly on save or receipt-write failure.
- Project 6 builds an atomic party matchmaker from scratch that never splits friend groups, avoids head-of-line blocking on oversized parties, and leaves caller tables untouched.
ProcessReceipt is a courier who keeps coming back until you sign, until you decide what a duplicate looks like: without a stored purchase id, a redelivered receipt grants twice, and a record saved apart from the coins leaves a gap.
Queued for review
- A player buys BigPack (150 coins, sku 'BigPack'). The first call succeeds and marks seen['p-9'] = true. Roblox delivers 'p-9' a second time. What must ReceiptCatalog.process return?
- Why must a failed receipt write (saveOk == true, recordOk == false) roll back the coins before returning NotProcessedYet?
- Queue: Party A {1,2,3} at t=100, Party B {4,5} at t=101, Party C {6} at t=102. With now=105, maxSize=4, minPlayers=2, waitSeconds=20, what does planMatches return?
- Why do studios keep both the receipt decision logic and the party planner in pure Luau modules with zero Roblox service calls?
Next Capstone, part 4: ship it to staging (private publish, CI and deploy)
Open this step in lesson mode · Link to this step · This confused me