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.

Project lesson, about 70 minutes, 5 steps

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

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:

  1. Check the purchase id is not already recorded in the player's data. If it is, and that record was saved, return PurchaseGranted.
  2. Add the coins to the player's data in memory.
  3. Write the purchase id into that same player data.
  4. Save that one record and wait for the save to land.
  5. Return PurchaseGranted only if the save worked. Otherwise return NotProcessedYet.

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?

  1. Unchanged balance, 'PurchaseGranted', and nil for the analytics SKU
  2. Unchanged balance, 'NotProcessedYet', and nil for the analytics SKU
  3. Unchanged balance, 'PurchaseGranted', and 'BigPack' so analytics logs it again
  4. Balance + 150, 'PurchaseGranted', and 'BigPack'
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?

  1. Unchanged balance, 'NotProcessedYet', and nil, without adding the purchaseId to seen
  2. Unchanged balance and 'PurchaseGranted'
  3. 50 coins and 'PurchaseGranted'
  4. An error that crashes ProcessReceipt
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.

Luau
-- 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
Figure 2.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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

  1. Check productId <= 0 and catalog[productId] == nil first.
  2. Check seen[purchaseId] == true BEFORE checking saveOk or mutating balance.
  3. 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?

  1. Because Roblox will retry the same purchaseId, and without a stored receipt record the retry would pay the coins a second time
  2. Because DataStoreService deletes the player's profile on any error
  3. Because MarketplaceService bans games that save before writing receipts
  4. Because negative coin additions are required before returning any Enum
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?

  1. Store the purchase id inside the player's profile and write coins and id in one save
  2. Keep the rollback code but add a longer retry delay
  3. Write the receipt record first and the profile second, with the same rollback
  4. Return PurchaseGranted before saving so Roblox stops retrying
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
Figure 3.1

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:

  1. Deduplicate userIds across all parties in join order (first appearance wins); drop any party left empty. Never mutate the caller's input tables.
  2. Never split a party across two matches.
  3. A party larger than maxSize cannot fit in any match; leave it in waiting without blocking smaller parties behind it.
  4. 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.
  5. Emit a match when #players == maxSize, or when #players >= minPlayers and now - oldestAt >= waitSeconds. Otherwise leave its parties in waiting, preserving join order.

Other ways pros do this

OptionWhat it isWhen pros pick itTrade-offs
Pure Luau planner + MemoryStoreQueue + MessagingServiceBeacon 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 MatchmakingServiceManaged 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?

  1. One match {1,2,3,6} and waiting {4,5}
  2. One match {1,2,3,4} and waiting {5,6}
  3. No matches yet because Party B does not fit behind Party A
  4. Two matches {1,2,3} and {4,5,6}
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?

  1. Leave the 5-player party in waiting and launch a match with the two 2-player parties behind it
  2. Split the 5-player party into 4 and 1
  3. Stop scanning so nobody behind the 5-player party ever gets a match
  4. Raise maxSize to 5 automatically
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.

Luau
-- 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
Figure 4.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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

  1. First build a clean list of copied parties with unique userIds so you never mutate the caller's tables.
  2. Track a boolean table used[i] as you greedily pack each match from index i forward.
  3. 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?

  1. 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
  2. Because Roblox forbids loops inside scripts that call MemoryStoreService
  3. Because pure modules automatically replicate to clients
  4. Because ProcessReceipt cannot call other ModuleScripts
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

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

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