Ch.81: System Design: Build a Live Sports Score Service

Outline

Transcript

0:00 A live sports score service lets fans follow a match without watching its video. A late correction can leave fans watching the wrong score. We'll design how source updates become a saved scorecard, reach a million viewers, and recover after a disconnect. Suppose a goal makes the score 1 nil, meaning 1 to 0. The referee cancels it, so we're back to 0–0. A fan already saw the first score, so a delayed correction leaves that fan celebrating a goal that no longer counts. I want that viewer to get the correction and its explanation together.

0:34 Our scorecard groups the score, match status and recent plays. The common mistake is adding one whenever a message says goal. That loses the correction. Now trace that correction through three parts of our design. On the left, we ask the chosen supplier for the whole match. The middle saves one accepted state. On the right, shared regional services send it to viewers. Does that left-hand path still work if the supplier's live feed, the connection sending us updates, disconnects? It does if we can also request a full match record.

1:08 We require our chosen supplier to number those complete copies in order, so we can tell which is newer. What if sending stops after we've saved the correction? We keep a record beside the card of what still needs sending, so another process can finish delivery. Before choosing those components, the functional requirements are what fans need: find matches, read their scorecards, receive changes and reconnect. Corrections must update the score and corresponding recent history together. The non-functional requirements set service quality.

1:38 Choose one million viewers on a popular match. For 95% of connected-viewer update checks, we want the accepted card, or a newer complete replacement, applied within 2 seconds of acceptance. Accepted here, rather than 2 seconds after the actual play, because a supplier has to observe and report it first. We'd measure that delay separately. Agreed. For example, a fan keeps a score page open while the data supplier is unavailable. We'd rather show a labeled old score than pretend the match is still current.

2:09 That stale label keeps the promise honest. No video streaming, betting or software that decides every ruling for every sport. Those would change the requirements substantially. We're building the score service behind that page. Its read traffic and write traffic won't resemble each other. A million people may ask about one match while only a few changes happen. That's why distribution needs its own design. The source also has limits: Sportradar's public guide says to request the current match to recover missed live updates. The documentation links are in the description.

2:42 So having a live feed doesn't remove the need to ask what we missed. We need both a trustworthy match state and an efficient way to share it. First, build that promised match view with 1 service where the app asks for a scorecard, and a database where we save the match records. The screen shows our API, the requests an app can make: get a match list, retrieve one scorecard, and follow its changes. So the match list returns a match identifier, M7. The app uses that identifier to request the scorecard.

3:16 Its result and matching play history come from the same saved version. Yes. Store a goal's identity and current disposition alongside the score. Disposition just means whether that play currently counts. Take a goal labeled nine. First it's awarded, then canceled. If cancellation arrives twice and we subtract twice, our zero becomes minus 1. That's a score the referee didn't award. Yep. The record should instead say goal nine is canceled. Applying that same state again doesn't subtract anything.

3:46 We're replacing our account of the match, not tallying every message as another play. I'd store the displayed result with its associated events in one versioned record. A revision number identifies that accepted state; it doesn't count goals. That gives the screen a useful check. Revision 20 can say 1 to 0 with the goal awarded. Revision 21 says 0 to 0 with that same goal canceled. And we mustn't fetch the score from 21 but the explanation from 20. The viewer would see a canceled goal still described as the winner. One complete scorecard prevents that mixed read.

4:23 We still have to establish which supplier update deserves to become the next accepted version. Establishing that version starts with the supplier contract. Our worked design requires complete match snapshots, saved copies of a match, with comparable revision numbers supplied by the same chosen provider. My first thought was to use arrival time. If the newest message gets the highest number locally, why isn't that enough? Because a retry can arrive last. Consider the three supplier states on screen: 410 has 0–0, 411 awards the goal, and 412 cancels it.

4:55 If another copy of 411 comes after 412, numbering arrivals would make the old goal look newer. The supplier's revision is what identifies that older evidence. Exactly. Our own revision 21 records acceptance of supplier 412. They're different counters. One belongs to the source; the other belongs to our service. Do the Sportradar docs actually promise that complete, increasing match revision? They don't establish that contract. We're requiring it for this exercise, not attributing it to their data interface.

5:25 An update timestamp, a recorded time of a change, isn't a guaranteed ordering rule. Then a supplier without comparable versions needs a weaker claim. Ask for its latest recorded scorecard by the method it documents, label what we can't verify, and don't pretend arrival order proves the latest result. That's the boundary. Under our chosen contract, a change notice triggers a read of the whole current state. One read runs per match at a time; extra notices request one further refresh. Periodic reads catch missed notices and status changes.

5:57 That status check matters: the linked soccer guide says its live event and statistics feed does not carry match-status transitions. Next, lock the match record so another update to this match has to wait. A transaction saves the new scorecard and its unfinished sending work together, or saves neither; that all-together save is the commit. For instance, supplier 412 becomes local revision 21, with 0 to 0 and goal nine canceled. Beside that card, we save which regions still need it. Those pending records form our outbox, the saved list of updates still to send.

6:31 A publisher, the process sending them, keeps each region's entry until that region confirms it saved the update. If we get that confirmation and the regional process immediately crashes, what survived? A regional delivery log, a saved sequence of updates that a replacement process can read. We require its storage to survive that process crash before the region acknowledges, meaning sends confirmation. The phone can still be on 20 when we get that saved confirmation. Restart the sender, read 21 from the stored log, and the whole card can be delivered.

7:04 Yes, while an absent confirmation leaves that sending entry pending. A lost reply can cause another send, but receivers replace their card only when our revision is newer. An equal revision changes nothing, and a delayed 20 can't restore the goal after 21. We don't need another subtraction to undo a retry. That survival depends on the real storage system. Our small exercise checks only the recovery logic. The correction now has somewhere to wait at both boundaries. Let's put a delivery cost on that popular match.

7:35 Let's say our compact scorecard is 2 kilobytes, with two accepted changes per second. A million viewers means 4 gigabytes per second of message data, before the extra bytes needed to deliver it. Those copies still have to reach every viewer; changing the connection software doesn't remove them. We're calculating capacity for these assumptions, not measuring a running service. If every viewer requests the current score every 2 seconds, that's 500,000 requests a second. A shared cache can serve a stored copy and avoid repeated database reads.

8:07 But we have to choose how old that shared copy can be. If we keep the old score in that cache, the canceled goal can linger even while every request finishes quickly. We need fresh shared copies as well as fewer central requests. Regional relays, services near each group of viewers, share a match update instead of making the central service send separately to every phone. Suppose we split the audience evenly across four regions. Each regional fleet, the group of servers serving that region, still carries 250,000 connections and a quarter of that outgoing data, 1 gigabyte per second.

8:43 So a box labeled region isn't one magic server. We'd measure how many connections and outgoing bytes each instance supports, then size the group and leave room for failures. Every viewer still needs that data delivered. And 2 kilobytes isn't a promise for an entire match history. Limit recent events, and load older plays in small pages, a few records per request, from that same accepted revision. Holding those requests at one saved version keeps the older plays consistent with the scorecard. Shared delivery removes repeated central work; we still deliver those bytes, and the copies must stay current.

9:22 Next, send accepted scorecards as server-sent events, where the server keeps an ordinary web response open and sends a new card when the match changes. We only need that one-way path for scores; the other transport choices on screen come with different request and connection costs. Imagine a slow phone still displaying 20 while its queue fills with 21, 22 and 23. Must it play every change before catching up? No, send the newest full replacement, including its matching recent history. That fits our catch-up target even if the phone skips an intermediate celebration.

9:56 That wouldn't work for tiny commands such as add one and subtract 1. Dropping either command would change the result. Complete state is what makes the shortcut valid. Yes, so bound that waiting list's memory. If a viewer can't keep up, replace the pending versions or disconnect it and start again from one saved card. The 2-kilobyte assumption still has to be measured against real message sizes and event limits. A full replacement isn't an excuse to stream an ever-growing match document. Exactly. Current state plus bounded recent events, with older pages tied to that version.

10:33 That gives a disconnected viewer a clean starting point, too. Now test reconnect with those complete replacements. Suppose a returning viewer reads revision 20. The relay publishes 21 before the viewer subscribes, registering to receive later updates. The screen stays 1 to 0, because the correction passed between those operations. Reading first and subscribing second didn't establish a continuous handoff. Could we reverse those operations without sending the viewer an older score after a newer one? Subscribe first and buffer changes, meaning hold them temporarily.

11:05 Confirm that the regional log is being followed without a gap, then read the current committed record directly from the database, bypassing its cached regional copy. Send that snapshot and only higher buffered revisions. Suppose 21 was already sent before we subscribed, but the regional cache still has 20. Doesn't subscribing first still leave us with an old card? It does. Our buffer is empty, so that stale read would strand us at 1 to 0. The database read must include changes committed before it begins. If that read is unavailable, keep the page labeled stale and repeat those reconnect steps.

11:42 Got it. We're listening before asking what we missed, so an earlier commit is in that read and a later change arrives through the subscription. Their overlap can give us duplicates, which the revision check handles. Yes, and the viewer applies only increasing revisions. A duplicate or delayed older card cannot restore that canceled goal once the newer state has been applied. The reconnect request includes a cursor, the viewer's last applied revision. Browser event streams have Last-Event-ID, the identifier of the last event received.

12:13 That identifier doesn't create retained server history. The browser may receive revision 21 while the app still shows 20. Store our last applied revision beside that displayed card, advancing it only after the app applies the whole replacement. Send it explicitly on reconnect. If a relay loses its subscription position, it repeats those subscribe-first steps with a current database read rather than claiming continuous delivery. That temporary buffer also needs a memory limit: if it overflows, start again instead of draining an incomplete set.

12:44 When many viewers return together, we can group them for one fresh read, but only after every member's subscription is confirmed. A late arrival waits for the next group rather than borrowing an older read. The returning viewer ends at 0–0, with that goal canceled in its history, which matters more here than replaying every celebration. Next, check a limit that even correct reconnection can't repair: old supplier evidence. A heartbeat says the connection is alive, but doesn't say we've checked the match.

13:13 A match can stay 0–0 for ages, though. If the supplier successfully returns the same record, should its age keep increasing? No. Source age means time since a valid check with our chosen match-data provider, not since the last goal. A complete reply at the same source revision can refresh it. An older reply, or one we can't place in that source's order, cannot. We save the check separately even when the score stays unchanged. Then another 412 can show we've checked again, while a delayed 411 can't.

13:46 The card stays 21 while the successful-check number advances; no new goal is needed. We send the check time and latest card number as updates too. Each has a successful-check number, so an old message can't overwrite newer check evidence. If the phone hears we're at 22 while it still displays 21, it repeats those reconnect steps. For example, its heartbeat is current but the last successful source check was 30 seconds ago. Why not hide the score until the supplier returns? I'd keep the last known card and show its age, so the viewer can distinguish a delayed result from a current one.

14:22 Neither a heartbeat nor an unchanged cached response advances that source-check time. I think I'd put that age beside the acceptance-to-display delay on the operational dashboard, the page showing service health. Otherwise the dashboard says we're fast while the fan is still waiting for a correction. We'd also use periodic reconciliation, checking our record against the supplier again, to find notices we didn't receive. After a broken feed, ask for the complete current match rather than assume reconnection replayed what we missed.

14:53 If we change suppliers, we can't compare their revision numbers. We need a whole match record from that supplier, with its name saved beside it, before using its data. Right. Our card revision still moves forward across that change, even if the new supplier starts its numbering elsewhere. The stored card must tell us which supplier it represents. Now apply those source decisions to an ended match. Ended describes its status; it doesn't prove the recorded data will never change. Consider a later official correction after revision 22 says ended.

15:25 A newer supplier snapshot can become 23 and change the card without the match resuming. If corrections still count after play ends, what do we keep running? We'd check less often and close unnecessary connections. Our exercise keeps the regional recovery log for 24 hours after the match ends, and accepted database versions for 30 days. Those windows tell us how long we keep records, not how current the score is. So the short-lived collection helps restart delivery, while the saved versions explain what we accepted.

15:57 Older results need a longer-term store, and we'd agree on the correction interval with the supplier. Those saved versions also identify the source we relied on. Suppose that supplier becomes unavailable, and a possible replacement reports our original canceled goal as awarded. Can its 99 settle that disagreement with the original supplier's 412? No. Those numbers only order records from the same supplier. In our design, a conflicting replacement stays unselected. The fan keeps the old card labeled stale until the person responsible for source selection checks the complete match record and chooses the source.

16:32 That wait leaves fans with older evidence. Once that decision is made, we establish the chosen provider's complete starting state. Our card's next revision still follows the last accepted one. Until then, we still label the retained card stale even if its connection works. If we lose that regional log, close those streams and reconnect through the current database. Our runbook, the outage instructions, must distinguish a missing delivery copy from an unresolved source decision. An unavailable current read leaves the existing stale label in place.

17:04 Finally, return to that full architecture and follow supplier 412 through the source side. Its version is accepted under our chosen source contract, rather than because its packet happened to arrive last. The central database commits revision 21 with both 0–0 and the canceled goal. The same transaction records unfinished sending, and a region confirms only after saving its own recovery copy. Regional services distribute complete replacements and reject older ones. On the right, someone back online uses a fresh database record and the buffered updates. That read bypasses any stale regional copy.

17:39 The returning fan sees that the goal was canceled, even if a sender had to restart. The supplier can still be delayed and we still pay to reach every phone, but now we can see both which version we're displaying and when its source was last checked. The scorecard on screen now agrees with the matching event list. The goal is canceled, the score is 0–0, and an old retry can't put it back. And if we choose a different supplier or weaker ordering contract, we revisit that claim explicitly. Our internal version number records our decision; it isn't evidence the supplier never gave us.

18:15 Thanks for listening to Learning Podcasts.