Ch.39: System Design: Match 100 Players Before They Quit
Outline
- 0:00 The timeout that creates two matches
- 0:31 The guarantee we can honestly make
- 1:53 Requirements before components
- 2:44 The complete architecture
- 3:38 Fence stale queue attempts
- 4:40 Partition the search space
- 5:55 Fair bounded candidate search
- 7:12 Beam search for whole parties
- 8:11 Claim the roster atomically
- 9:17 Requeue during placement
- 10:09 Persist before the remote call
- 11:05 Unknown is a real state
- 12:15 Reconcile a late reservation
- 13:10 Revalidate before issuing access
- 14:03 Clean up forward and backward
- 14:50 Make no shows product policy
- 15:56 Replay the failure end to end
Transcript
0:00 100 players have waited almost a minute. The matcher forms M 9:02, asks the game-server fleet for capacity, and the reservation call times out. Priya and Omar cancel and requeue. A second matcher finds them while the first server may still be alive. Wait: two servers and still no match. We will show how every late answer proves it still belongs before anyone gets access, then replay the timeout end to end. That gives the race one authority test at every boundary. Before drawing boxes, what can we honestly promise?
0:33 Can this system make one logical assignment even when calls cross service boundaries? The Ticket Store decides which party attempt remains valid. It gives each new attempt a generation number, and only that current attempt can be claimed into one roster, meaning recorded as one match's owner. But that does not prove the capacity provider created only one physical server. If the allocator accepted our request and its response vanished, the caller cannot infer failure from silence. So should we just retry and trust an idempotency key?
1:06 Only if that key, actually, names the same observable placement. A retry must return or discover the original reservation. If we invent a new key after every timeout, idempotency is decorative. Right. We can promise one logical roster owner, one durable placement request that recovery can find, and one user-visible assignment. We cannot call an ambiguous cross-system request physically exactly once. Think of one payment command ID crossing the network more than once: one logical operation, multiple physical requests.
1:35 Exactly. I still catch myself reaching for the retry reflex: timeout, mint a fresh ID, try again. I think that is why this bug hides so well; every retry becomes a different operation, recovery becomes archaeology, and the runbook loses the one placement ID it needs. With the bounded promise, the functional requirements are to queue one indivisible party, cancel or requeue it safely, form a 100-player roster, and connect only its current claimed attempt. Once a credential escapes, cancellation cannot unsend it.
2:08 Before that boundary, claim every current generation atomically or claim none, then persist the roster before placement. For the non-functional requirements, picture Priya inside a fictional queue of two million players. Queue and cancel feel immediate, a regional matcher failure cannot lose authoritative ticket state, and the match offer target is 60 seconds. So counting to 100 is the decoy? Searching two million moving candidates before Priya leaves is the hard part? Yes. Preferences may widen, compatibility may not, and an unknown placement must remain queryable.
2:41 Next comes the authority path that enforces those boundaries. With those requirements fixed, follow Priya instead of memorizing boxes. Her queue command advances generation in the authoritative Ticket Store, and that update reaches a rebuildable Queue Index. A Match Worker proposes 100 exact generations from the index; it cannot, actually, assign her. The Claim Coordinator commits all 100 or none into durable match M 9:02. Only then does placement send stable key place M 9:02 to the Capacity Allocator.
3:11 If Priya requeues, the Connection Broker rejects her old generation before issuing access. If the allocator answer is unclear, cleanup checks that same key. If the local record vanished, it scans capacity inventory for a reservation with no valid owner. Good. Priya crosses one authority boundary at a time. AWS and Microsoft document the public mechanisms linked in the description; this path and scale are fictional. Next: stale work survives cancellation. Now the first race is older work surviving a cancel.
3:41 For example, why does one mutable ticket row fail to settle it? Because the row's identity would outlive the intent. The party can cancel, change mode, or queue again while an outdated worker still holds a copy. We need distinct attempts. Oh, that's the shift. The service owns a counter that only ever increases. The first queue command creates ticket T seven at generation 41. A transport retry returns that same result; only a genuinely new attempt advances the generation. Then cancellation marks 41 canceled, while requeue atomically cancels 41 and creates a waiting ticket at 42?
4:20 Exactly. Any conditional write for 41 now fails. The old worker can, honestly, keep running, but its write has already lost authority. Generation is a fencing token: a number that turns cancellation into an authority check instead of a broadcast problem. Priya's old work may exist, but it cannot become truth. Once generations fence stale work, search has a different problem: which rules can widen without merging incompatible players? The axis is relaxability over wait time. Build and mode stay at zero tolerance after 60 seconds; latency can, you know, widen from 20 to 80 milliseconds.
4:58 It is a locked boarding gate versus accepting a worse seat near departure. The rebuildable index carries generation, skill, latency, and wait age. If it is stale, the Ticket Store still decides whether a claim is legal. Search can be approximate while authority stays current. What protects Priya's deadline when her pool is the hot one? Take the hot pool that contains Priya. Revisit its oldest seed every 5 seconds, giving her 12 search chances before 60. If the worker misses a cycle, scale that pool before Priya's wait grows.
5:31 Okay, so a fleet-wide average can look healthy while Priya's pool is melting? Right. Alert per pool on oldest-ticket age and missed search cycles. Those are capacity targets; the authoritative store still owns correctness. Good. Supported region and build remain hard pool boundaries; latency widens inside them. One hot pool now has an explicit clock instead of a blended average. Those hard partitions leave the softer ranking problem inside each pool. How should a worker search millions of possible groups?
6:02 Do we optimize the best global combination? No. That would be expensive, hard to bound, and unfair to old tickets. Seed from the oldest eligible ticket, then search nearby candidates under the current rule stage. Rule stage meaning the acceptable skill and latency ranges for that wait age? Right. Priya's party starts with a tight skill band and nearby region. Later stages widen skill, then permit slower connections inside supported regions. The fictional schedule stays versioned and measurable. But I can hear a product manager asking, “Priya has waited nearly the full target and a new party just arrived.
6:40 Why should that newcomer inherit her wider match?” AWS lets expansion age follow the newest or oldest ticket. Which do we choose? I think the default instinct is to restart the expansion clock whenever the group changes. That can trap the original seed, so Priya's older wait controls this design and knowingly trades some match quality for progress. That's exactly it: Priya's clock pulls the group forward; the newest party does not drag her backward. Progress, not a clock reset, wins without mixing incompatible builds.
7:12 With the oldest ticket controlling expansion, exhaustive grouping is still unbounded. How do we reach 100 without splitting parties? AWS documents sorting, splitting, and balancing for large matches. Imagine eight draft seating charts: for each incoming party, branch into add or skip, reject broken rules, and retain the eight best partial rosters. Right. Eight sounds tiny, so test it on Priya's four-person party. At 96 seats it completes a roster; at 97 that branch must reject all four, right? Exactly. Another chart may have skipped an earlier solo and kept four seats open.
7:49 Keeping only eight charts bounds the work while every party stays stapled together. Ah, we preserve several good futures instead of greedily filling the next seat. What survives after search? Proposal M 9:02 records exact generations, rule version, predicted latency, and oldest wait. It is auditable but owns nothing; only the Ticket Store can claim it. Because the index only proposes, this complete roster still owns nothing. What flips that hint into authority? Take the tempting implementation that pops selected tickets one by one.
8:22 That would be a recovery nightmare. Where does it leave us if another worker claims Priya or she cancels halfway through? With a partial roster and ambiguous ownership. Almost 100 is a great exam score and a useless match. Oof. So proposal M 9:02 goes to the Claim Coordinator, which checks that every ticket is still waiting at the exact proposed generation. Then one transaction, or one serialized command owned by that partition, changes every ticket covering those 100 players to claimed by M 9:02.
8:53 If any precondition fails, none change. Two workers may build overlapping proposals, but only one all-or-nothing claim can win? Exactly. The loser discards its complete proposal and searches again; it keeps none of the uncontested tickets. Checkpoint: one live Priya attempt now belongs to the durable match record. Ownership is settled; the next uncertainty is whether capacity was reserved. Now the roster is claimed and Priya requeues. Which authority governs everything after that? Generation 42.
9:23 One atomic write supersedes the old attempt with that new waiting state. Does that automatically undo the multi-ticket claim? It invalidates Priya's claimed generation. M 9:02 enters invalid-roster state: stop pending placement, and if a reservation appears later, release it. Every later step revalidates before exposing access. Think of generation as a changing lock number: the old key could still sit in someone's hand, but the door no longer accepts it. The Connection Broker is the doorman checking that number.
9:55 But what if the old credential already left the building? Oof. A sent credential is not retractable by wishful thinking. From that point, cancellation fences new access. That leaves seat policy to decide what happens to the empty slot. Before Priya's requeue can race the server allocation, the roster must be committed. Now show me what survives if that remote step crashes halfway through. Because the allocator is remote. Holding the transaction open would not, honestly, make that call atomic; it would only make the database wait.
10:26 Consider a crash after the claim. The Match Store writes one placement intent in the roster transaction. That intent is the committed work record authorizing one allocator request for M 9:02 under its existing placement identity. Then what if the roster commits but the first scheduling attempt never runs? A background worker scans that pending intent and schedules it again under the same placement key. The surviving row is the intent itself, so restart never invents a second request. Oh, wow. That is the receipt every on-call engineer wants at three in the morning: the roster tied to its allocator request, not a mystery request lost in logs.
11:04 Now the intent survived. What exactly goes over the wire to the Capacity Allocator? Stable key place M 9:02, plus region, build, mode, and capacity constraints. When the response disappears, did placement fail, or did only our knowledge fail? Silence cannot tell us. Failed means the allocator proved no reservation exists. Unknown means it may have accepted the request, but we have not observed the outcome. Success creates leased reservation R 9:02. Wait, really? Yes. A timeout can leave us owning a server we cannot yet see, so we store that lack of knowledge as unknown.
11:45 Imagine a 50-dollar card payment that times out but actually charges once. Zero receipt does not prove zero charge; query the same payment ID before risking another 50. Exactly. Reserve and get-by-key form one observable operation. Retry may be safe, but lookup tells recovery whether a reservation exists and what state it is in. Which means a fresh key is not a retry; it is a second capacity authorization. A timeout changes our knowledge, not the requested operation. Now the stable-key rule resolves the opening timeout.
12:18 For example, recovery records placement unknown, looks up place M 9:02, and discovers reservation R 9:02. Can we keep it? Only while the match remains active and every claimed generation is current. Priya requeued, so 41 makes the roster invalid. Oh, man. Priya has moved on, but the São Paulo server is still reserved and chargeable. Put the two clocks in order for me. The 32nd clock is for observation: look up the same key and retry only under that identity. If R 9:02 appears, release it. Meanwhile, 42 may keep queueing, but M 9:02 is barred from issuing Priya a credential.
12:58 So 30 seconds bounds our lookup effort, while the 92nd lease bounds abandoned capacity? Exactly. Physical overlap is cleanup debt, not a second assignment for Priya. With capacity found, Priya canceled while we were waiting. Are we really ready to hand her an address? The Connection Broker must revalidate that each ticket's current generation still equals the generation claimed by M 9:02. Why repeat a check the claim already performed? Because cancellation can land during placement. The claim proved the roster at one moment; credentials grant a fresh capability later.
13:33 I like that boundary: yesterday's ownership check cannot authorize today's credential. How do we bind the entitlement to that decision? Make it one-use, bound to match, reservation, ticket, and generation. In our fictional policy it expires after 30 seconds, and a stale retry returns the existing entitlement or invalid generation instead of minting another. Good. 42 gets a future roster; that old match never gets to borrow it. Cancellation authority now reaches all the way to connection. Once credentials are fenced, one cleanup question remains: does the local placement intent exist?
14:09 If yes, the forward Reconciler follows its stable key and asks the allocator what happened. And if the receipt is missing? Here's where it gets weird: the reverse Orphan Reaper starts from allocator inventory. It scans those warehouse shelves and releases R 9:02 when its owner tag points to no valid M 9:02. I mean, receipt present means forward lookup; receipt missing means reverse inventory. Can the lease still save us if both workers disappear? Yes. The fictional lease lasts 90 seconds and renews every 30 while a valid match owns it. Expiry is the last backstop, so the allocator reclaims the server instead of leaking it forever. Once leases bound capacity leaks, one failure remains outside infrastructure: only 90 humans connect.
14:56 What happens to the 10 empty seats? Why is that not just a late cancellation? Because a credential may already be in the client's hands. The backend cannot erase delivery, and perfect placement cannot make every human connect. We tend to lump no-shows in with late cancellations, but that stops working once the credential leaves our system. For example, this fictional game might start with 90 connected players after 15 seconds, offer replacements for 30 more, then abort and release if the floor still fails.
15:26 That is product policy, not distributed-systems correctness. Right. That replacement offer is backfill: a new offer under visible current rules, never resurrection of the original ticket. If waits climb while the allocator stays healthy, do more servers help? Not if the pool lacks compatible players. More servers cannot create them. Search policy owns quality, ticket authority owns assignment, and recovery owns server side effects. Now operators can distinguish player scarcity from allocator failure.
15:55 So let's run Priya through the map once more and see where duplicate access is stopped and abandoned capacity is reclaimed. Priya begins in the Queue Index under generation 41, while the Ticket Store remains authoritative. Match Workers keep parties intact and propose M 9:02. The Claim Coordinator verifies every generation and claims the full roster all or nothing. The roster and its placement intent commit together. The orchestrator submits one stable key. R 9:02 succeeds, its reply disappears, and placement becomes unknown.
16:29 The missing reply leaves physical capacity ambiguous. Can M 9:02 still issue Priya access? No. Priya's atomic requeue creates generation 42. Lookup finds R 9:02, while revalidation proves the old roster invalid. So the broker issues no stale credential. The discovered reservation is released; the reverse reaper catches it if our local intent vanished. The timeout cannot invent a second truth: one current attempt, one authoritative roster claim, one observable placement identity. That is how you match 100 players before they quit without assigning them twice.
17:04 Thanks for listening to Learning Podcasts.