Ch.80: System Design: Build a Twitch-Style Live Stream

Outline

Transcript

0:00 A live broadcast carries one creator's ongoing video to many viewers. A live camera can still leave them watching the past. We'll design the video's route, from letting a creator send it to playing the picture, and work out where delay grows and what recovery can preserve. Now take Maya's concert on the two clocks. Her camera has reached 8 seconds; the viewer is seeing the opening frame, with her hand raised. Some delay buys smooth playback. Slow preparation can quietly add more, until the live concert feels like an old recording.

0:31 Now trace where Maya's delay can grow: receive her feed, prepare playable video, then share it with viewers. Above it, the control path decides who may send and assigns available processing. Those big arrows carry the pictures themselves. We'll return to this complete map. First, what must the service let people do? First, our functional requirements let Maya start and stop an authorized broadcast. Viewers can join at a suitable quality and return to watching after processing fails. One creator, many receiving viewers.

1:03 We focus on video, leaving chat, calls and recorded-video libraries outside this design. The creator sends one feed. A late-arriving viewer should find current playable video. What should they see when fresh pictures stop arriving? Reconnecting, then a valid point to resume. That promise leaves room for a visible gap when the source connection fails. Next, operating limits are our non-functional requirements: healthy camera-to-screen delay within 10 seconds, plus time to the first picture and pauses during playback.

1:34 For an invented example, take 1,000 creators sending six megabits per second each. That's six gigabits per second coming in, just for the video. And 100,000 viewers averaging three megabits per second need 300 gigabits per second going out. And preparing video has to keep up with time. Stored work can wait until tomorrow. Yesterday's concert isn't a live stream anymore. Both totals leave out extra request and connection traffic. We need sustainable preparation and enough delivery capacity; scaling one doesn't automatically solve the other.

2:05 Before preparing Maya's pictures, a request to start creates a record for her broadcast and issues a publishing key: a secret permitting only that feed to send video. Maya connects to the returned receiving address. That service verifies her key, then receives video over an encrypted connection that conceals its bytes in transit. What if Maya presses Stop after that connection has already been accepted? The control service passes that stop to the receiver and publication, so neither accepts new video just because her first check passed.

2:36 So permission can end during an existing connection. More viewers change delivery, but Maya still sends one camera feed. But receiving nearby doesn't settle where processing runs. A nearby region could be overloaded while another has room. Twitch's engineers described that problem in 2022: fixed assignments overloaded one processing region while another had room. The source links are in the description. Our work-assignment service uses distance and available capacity to find room for Maya's pictures. I think moving a healthy broadcast just to find a slightly better place is too disruptive.

3:11 We can send new streams elsewhere without interrupting Maya's running one. Then we keep Maya's running broadcast steady and reserve preparation capacity when accepting a new one. Now fill that processing slot. An encoder compresses pictures. Transcoding turns the incoming feed into other quality versions, called renditions. These rows show high, medium and low quality at the same concert times, with their boundaries lined up. What picture lets a viewer start if they join halfway through the concert?

3:38 A keyframe, a picture that can be rebuilt without older pictures. We align those fresh starting points across the quality versions. That lets the player change rows while staying at the same moment in the performance. Next, how does Maya's never-ending feed become something the player can download? We cut short playable pieces called segments. A playlist is the changing list of available pieces and the addresses where the player can fetch them. We'll use HTTP Live Streaming, or HLS, whose pieces and lists are delivered through ordinary web requests.

4:11 We're choosing full 2-second segments for this exercise. We prepare each output once for the creator's feed. More viewers download copies of those same pictures; they don't repeat the preparation work. But shared preparation still has to keep up. Suppose one sequential lane needs 2.4 seconds for each 2-second piece. 10 pieces contain 20 seconds of concert, but need 24 seconds of work. The stream falls 4 seconds behind. Wouldn't storing more incoming video at least keep us from losing Maya's concert?

4:43 For a while, but we'd be preserving an increasingly late concert. We need less encoding work or sustainable processing capacity. And we don't discard arbitrary compressed frames. A deliberate skip needs a picture the system can restart from. With a different setup that keeps up, take a frame of Maya raising her hand. These clocks are invented assumptions. Capture at 0. Its 2-second piece closes at 2 seconds; compressing the video and preparing the playable piece finish 4/10 of a second later. Publication completes at 2.5.

5:16 The player discovers that piece at three and finishes downloading it at 3.5. That's already 3.5 seconds. Faster transfer can't remove the time spent collecting and preparing the piece. But it's on the viewer's device now. Why do we wait until clock eight to show the frame? Because arrivals are uneven. A buffer is downloaded video waiting to play. We collect 6 seconds, then start at clock eight. The three blocks cover video time zero through six. The later pieces published at 4.5 and 6.5 have already downloaded.

5:48 The live edge, the end of the newest published video, is at six. Starting at zero leaves 6 seconds behind it. Six is three of our chosen 2-second segment lengths, the starting margin ordinary HLS guidance recommends for this setup. That's 6 seconds of downloaded video, but 8 seconds since Maya's camera captured the frame. We're keeping those measurements separate. But my instinct is to want less delay. Take a viewer already closer to the edge, with only half a second of picture ready. At clock eight, that viewer is 5.5 seconds into the video.

6:22 The next piece finishes downloading at clock 9.5. Its ready video runs out at 8.5, so it stalls for a second. The viewer with 6 seconds ready keeps playing through that delivery. That's the cost of running closer. This is our deliberately aggressive comparison, rather than the 6-second startup we just chose. Before either player can fill its reserve, publication must make a piece safe to find. First, finish writing its bytes and check availability. Then publish a complete playlist version containing its address.

6:54 Reverse that order and a fast player can request bytes that aren't ready. Published pieces keep unchanging bytes under unchanging names. The list is replaced as one whole version, so a reader never gets a half-written update. Older pieces stay available after leaving the current list. Players with an old list can still need them; HLS specifies how long they must remain. Otherwise, a viewer can follow an older list straight to a piece we've already deleted. But even a whole playlist can be old. Take the two fast response cards: one list ends at four and the other at six.

7:29 Same response speed, different freshness. A cache, a stored copy, can reply instantly while keeping new viewers behind. Completed video gets long reuse. The discovery list must refresh promptly so Maya's viewer can find new pictures. Would you have each player bypass every stored copy to get the newest list? I'd combine overlapping refresh requests for the same list at the shared delivery layer. Nearby viewers can reuse a fresh version, rather than each asking publication separately. That protects publication from a storm of duplicate requests while keeping discovery current. Now Maya's finished piece goes to a content delivery network, or CDN, which holds copies near viewers.

8:09 If that nearby server doesn't have the requested piece, it fetches it from our media store. Then later viewers read that copy. Updating the list shows any newer finished pieces, without making Maya's encoders produce them again. But viewers' connections also vary. The player can lower its bitrate, the number of video bits per second, when downloads fall behind. Both quality rows must cover matching concert moments. Then playback can switch rows without jumping along the timeline. Matching piece numbers doesn't prove that.

8:38 The times attached to the pictures and their keyframes must agree. With the moments aligned, lower quality can protect the playback reserve. It isn't just a menu for sharper pictures. Yes, if download capacity is the problem. Lower quality doesn't fix a camera or encoder that isn't producing anything. Now consider a processing worker, the program preparing Maya's video, whose outputs stop arriving. The coordinator records the current publishing owner, the program permitted to publish. If the worker stops sending results, we allocate a replacement with a higher ownership generation, called an epoch. In our example, seven becomes eight. The old worker may return with a finished piece. So failure detection doesn't decide who is allowed to advance the published list. And permission doesn't produce a picture.

9:25 The replacement needs live input and a starting picture it can rebuild. We'll test both conditions: exclusive publication permission, and usable media reaching the new worker. With that permission, publication checks the current epoch and accepts the next list in one indivisible update. We last published piece 90. Old epoch seven offers 91 after eight takes over. Publication rejects it, so seven can't put its returned piece in Maya's next list. What if we check the epoch first, and write the playlist later in a separate step?

9:58 Ownership could change between them. The stale update would slip through. The check and acceptance must happen together. Eight uses a new piece address. Our epoch is ownership; the HLS media sequence is the pieces' order. Now that eight has permission, how does it get its first usable picture? The control service updates the receiver's assignment to eight. If Maya's feed still reaches that receiver, it forwards input to eight at the next fresh keyframe. The old worker still can't publish. Eight can rebuild pictures, create aligned qualities, and upload a complete piece.

10:30 Publication checks eight and accepts that piece's address. If Maya's connection is down, the receiver has nothing new to forward. Permission can't fill that missing interval; viewers wait for a valid picture. Once pictures resume, if their time counter restarts, HLS requires a discontinuity marker in the playlist to announce that change. That flag doesn't restore pictures that never arrived, or guarantee that every player resumes seamlessly. Keep resumed qualities aligned, and retain pieces advertised before the restart.

11:00 For example, Maya's feed disappears and her viewers see reconnecting. When pictures resume, they watch again; the missing performance stays missing. A supported player needs a valid restart. A LIVE badge over frozen footage would hide what we actually lost. With recovery accounted for, could we make the pieces much shorter and get closer to the camera? Shorter pieces can finish collection sooner, but can mean more frequent requests and different encoding tradeoffs. Our delay budget must account for the whole path.

11:30 And Low-Latency HLS uses a different set of playback rules. It offers partial segments, smaller parts available before the whole piece has finished, unlike our completed-piece row. That also changes how players get playlist updates. It requires matching publication, delivery and player behavior, so changing our 2-second setting alone wouldn't implement it. Before promising lower delay, we'd choose and test the actual delivery settings and players. Now operate that delivery choice: track whether input advances, processing keeps up, and publication offers current pieces.

12:03 Then measure the player's distance from published video, camera-to-screen delay, startup and stalls. For instance, input advances while processing falls behind: inspect encoder capacity. Publication advances but players receive old lists: inspect discovery freshness. If Maya's camera stops sending first, would adding delivery capacity bring her concert back? Delivery can't create the pictures Maya's camera isn't sending. Those separate clocks identify the stopped stage, even when little work is waiting.

12:32 Finally, this same map explains Maya's delay: processing must keep up, publication must offer complete current pieces, and delivery must leave the player enough video ready. And it explains how to recover: send the new owner a usable picture, enforce who may publish, and reveal any input gap instead of hiding it. So in a design review, show that preparation can sustain input, viewers discover recent playable bytes, and recovery maintains one publishing owner. Then follow an actual frame to the screen and measure the gap.

13:02 Thanks for listening to Learning Podcasts.