Skip to content

    Frontend System Design

    Front-End Case Study: Netflix- or YouTube-Style Video Front End

    Design the front end of a streaming video site: HLS and DASH, Media Source Extensions, adaptive bitrate, a buffering state machine and autoplay, with a lab.

    By Published 22 min read

    • frontend-system-design
    • case-study
    • video-streaming
    • performance
    Share

    What you'll learn: By the end of this lesson you will be able to design the browser side of a streaming video site: how a manifest, segments and Media Source Extensions fit together, how a player chooses the next quality from a throughput estimate and a buffer level, how the buffering state machine tells startup, stall and seek apart, how autoplay rules shape the first second, and which numbers to measure. You will also run a pure model of the quality rule and the state machine, and walk the design through a 45-minute interview.

    This is an educational reference design, not the verified internal architecture of Netflix, YouTube or any other service. It is a generic design assembled from public specifications and documentation (RFC 8216, MDN, the hls.js and dash.js projects) and from a lab you can run. It says nothing about how any named service is built, and no real media is used anywhere in the lesson. Every number marked illustrative is an assumption chosen to make the arithmetic easy to follow.

    Picture a bathtub with a tap. The tap is the network, whose flow changes from minute to minute. The water in the tub is the buffer, and the person in the bath is the viewer. As long as the tub never empties the viewer is happy. A player has one extra control the bather does not have: it can ask the tap for thinner or thicker water (lower or higher quality). Most of the engineering is deciding when to ask for which, and what to show on the one occasion the tub runs dry.

    The core idea

    1. The video is many small files, not one big one. The service cuts each video into short segments and offers each at several bitrates. The player fetches them one by one over ordinary HTTP.
    2. The player, not the server, picks the quality. A manifest lists the choices. The client measures how fast segments arrive and decides what to ask for next.
    3. The buffer is the shock absorber. Video is fetched ahead of the playhead. Quality decisions protect the buffer: step down fast when it is threatened, step up slowly when it is deep.
    4. Waiting has kinds. Starting up, stalling mid-play, and waiting after a seek are different states with different rules, and users judge them differently.
    5. Measure what the viewer feels. Time to first frame, number and length of stalls, average bitrate and number of quality switches.

    The delivery side (CDNs, origin storage and transcoding) belongs to the back-end track; the back-end case study Video Streaming covers it. This lesson stays in the browser. Related ground: Preloading, Prefetching and Priority Hints and Image and Font Optimization for the browse page, Real User Monitoring for the metrics, and State Machines with XState for the modelling style. The method (requirements, scale, architecture, deep dives, failure, evolution, interview) is the Case Study Method lesson, named here in plain text.

    Requirements and scope

    Functional requirements.

    • A browse page with posters and quick-start previews, and a watch page with a player.
    • Playback starts quickly, plays smoothly, and adapts to changing bandwidth.
    • Pause, resume, seek anywhere, quality choice (automatic or manual), captions.
    • Autoplay of a preview or the next episode where the browser allows it.
    • Resume where the viewer left off (a stored position; the storage design is in the persistence lessons).

    Non-functional requirements.

    • Fast start: the viewer sees a first frame quickly, and the page shows a poster while waiting.
    • Few and short stalls; no flapping between qualities.
    • Does not waste data: no quality above what the player's size can show.
    • Accessible: keyboard operable, captions, a status that is announced.
    • Works on devices with different decoders and memory.

    Out of scope here. DRM and licence acquisition, live streaming (the HLS specification has live behaviours; this lesson models on-demand), ad insertion, offline download, and the back-end encoding and storage pipeline.

    Scale assumptions (illustrative)

    Everything below is an assumption for the exercise, not a measurement of any service.

    Assumption (illustrative) Value Consequence
    Rendition ladder 240p 400, 360p 800, 480p 1400, 720p 2800, 1080p 5000 kbps Five choices, each about double the one below, roughly
    Segment length 4 s Quality can change at most every 4 s; a seek restarts at a 4 s boundary
    Bytes in one 1080p segment 5000 kbps x 4 s = 20,000 kbit = 2.5 MB (8 bits per byte, decimal units) One segment is a sizeable download
    Bytes in one 240p segment 400 kbps x 4 s = 1,600 kbit = 0.2 MB A 12.5 times smaller download
    Transfer time of a 1080p segment at 1200 kbps 20,000 kbit / 1200 kbps = 16.7 s More than four times the segment's playing time: the buffer drains
    Buffer target 30 s ahead of the playhead Stop fetching beyond it; about 7 to 8 segments
    Start threshold 4 s buffered One segment is enough to begin

    The fourth row is the whole problem in one line. A segment that takes longer to download than it takes to play drains the buffer, and quality selection exists to avoid choosing that segment.

    High-level architecture

    Figure 1. The browser, an API, a CDN and a metrics intake

    Video front end: system overviewBrowse, watch to Catalog API (metadata); Browse, watch to CDN (manifest, segments); CDN to Origin storage (cache miss); Browse, watch to Metrics intake (QoE beacons)Browse, watch: player in pageBrowse, watchplayer in pageCatalog API: titles, manifest URLCatalog APItitles, manifestURLCDN: manifests, segmentsCDNmanifests,segmentsOrigin storage: renditionsOrigin storagerenditionsMetrics intake: playback qualityMetrics intakeplayback qualitymetadatamanifest, segmentscache missQoE beacons

    How to read this: the page asks an API for what to play, then fetches a manifest and segments straight from a CDN, because adaptive streaming needs no special server components. The player reports what the viewer experienced to a metrics intake without blocking playback.

    MDN's guide to adaptive streaming states the shape: to stream adaptively the media is split into chunks, several quality files are provided over several time points, and no special server-side components are required for adaptive streaming over HTTP. Both MPEG-DASH and HLS use a playlist format to describe the streams, with the bitrate streams broken into segments.

    Component deep dives

    1. Manifests and segments: HLS and DASH

    HLS is specified in RFC 8216. A Master Playlist provides a set of Variant Streams, each describing a different version of the same content; a Media Playlist lists the Media Segments that make up one stream. In a Master Playlist each EXT-X-STREAM-INF tag carries a required BANDWIDTH (the peak segment bit rate of the Variant Stream) and may carry AVERAGE-BANDWIDTH (the average segment bit rate), RESOLUTION and CODECS. In a Media Playlist EXTINF gives each segment's duration, EXT-X-TARGETDURATION the maximum segment duration, and EXT-X-ENDLIST says no more segments will be added. Segment formats include MPEG-2 Transport Stream and fragmented MP4, and a fragmented MP4 segment needs an EXT-X-MAP tag that says how to obtain its initialization section. The RFC says clients should switch between Variant Streams to adapt to network conditions.

    For DASH, MDN describes a media presentation description (MPD) file that holds the streams and the bandwidths they are associated with, with the <video> element's source pointing at the MPD, and says MPEG-DASH playback relies on dash.js and browser support for Media Source Extensions. For HLS, MDN says it is an HTTP-based protocol implemented by Apple, incorporated into iOS and macOS, and that it works well on mobile and desktop Safari and most Android devices.

    Two consequences for design. First, the ladder in a manifest is data, so the player must treat it as untrusted input: validate it, and filter it by what the device can decode. Second, BANDWIDTH is a peak and AVERAGE-BANDWIDTH is optional: a rule that compares a rendition's declared bitrate with a measured throughput has to say which one it uses and whether it left headroom. The lab uses a single bitrate per rendition and a safety factor.

    2. Media Source Extensions: the player's own buffer

    When the browser cannot or should not play a manifest itself, a script can feed it. MDN describes Media Source Extensions (MSE) as functionality for plugin-free streaming that replaces the usual single src URI with a reference to a MediaSource object, which holds SourceBuffer objects for the chunks of media. MSE gives finer-grained control over how much and how often content is fetched, and some control over memory, such as when buffers are evicted, and it lays the groundwork for DASH or HLS clients.

    The calls that matter for architecture, all from MDN's reference pages:

    • appendBuffer() adds segment data to a SourceBuffer. updating is true while an append or remove() is in progress, and updateend fires after it completes, successful or not. Calling appendBuffer() while updating is true throws InvalidStateError, so appends must be queued and issued one at a time.
    • QuotaExceededError means the buffer is full, possibly at a browser-defined limit. The player's answer is to remove() data it no longer needs behind the playhead, then try again.
    • buffered returns the time ranges buffered, which is what a buffer-level calculation reads.
    • MediaSource.isTypeSupported() returns true if the type is likely supported; MDN says that is not a guarantee, so the code must be prepared for playback to fail.
    • endOfStream() signals the end, and accepts network or decode to end playback with an error.
    • A ManagedMediaSource, unlike a regular MediaSource, can evict content from its source buffers at any time because of memory or hardware limits, so a player cannot assume that what it appended is still there.

    Figure 2. Inside the player: a loop from decision to buffer and back

    Player internals: decide, fetch, append, measureManifest to ABR controller (ladder); ABR controller to Segment fetcher (choice); Segment fetcher to Append queue (segment); Append queue to MediaSource + video (appendBuffer); MediaSource + video to ABR controller (buffer level)Manifest: renditionsManifestrenditionsABR controller: next renditionABR controllernext renditionSegment fetcher: HTTP requestsSegmentfetcherHTTP requestsAppend queue: one at a timeAppend queueone at a timeMediaSource + video: buffer, playheadMediaSource +videobuffer, playheadladderchoicesegmentappendBufferbuffer level

    How to read this: the controller picks a rendition for the next segment, the fetcher downloads it, an append queue feeds the source buffer, and the buffer level from the media element flows back to the controller. The download speed measured by the fetcher is the other input, not drawn to keep the figure readable.

    3. Choosing the next quality

    Real players combine two kinds of signal. dash.js documents a set of rules whose results are aggregated into a final decision: a throughput rule (selects the quality based on the estimated throughput), a BOLA rule (buffer-based selection that maps the current buffer level to the bitrate of the next segment), an insufficient-buffer rule (avoids rebuffering by reacting to critical buffer levels), a dropped-frames rule (avoids qualities that cause dropped frames) and a switch-history rule (penalizes qualities recently abandoned). hls.js documents the throughput side in its configuration: a fast and a slow exponential moving average of bandwidth with half-lives of 3.0 and 9.0 seconds by default, a bandwidth factor of 0.95 for staying or going down and a lower 0.7 for going up, and an option that limits the usable levels by the size of the video element. Those defaults are the projects' own; the lab does not copy them and uses its own illustrative values.

    The lab's rule, in words:

    • Estimate throughput with a fast and a slow average of finished downloads and take the smaller. A drop is believed at once; a rise is believed only once it has lasted.
    • Down is quick. If the estimate times 0.9 cannot carry the current rendition, drop to the highest rendition it can carry (0.6 when the buffer is under 6 s).
    • Up is slow. Climb one step, only when the estimate times 0.7 carries a higher rendition, the buffer holds at least 12 s, and at least two segments have passed since the last change.
    • Cap by player size. Never fetch a picture taller than the player can show.

    The rules are asymmetric because the mistakes are: staying too high drains the buffer, staying too low wastes a little quality.

    A last input is capability. MDN's Media Capabilities API provides decodingInfo(), which reports whether a configuration is supported and whether playback should be smooth and power efficient, which canPlayType() and isTypeSupported() do not. A player can use it to remove from its ladder renditions the device cannot play smoothly.

    4. The buffering state machine

    The HTML media element reports how much data it has through readyState, with HAVE_NOTHING (0) up to HAVE_ENOUGH_DATA (4), where 4 means enough data is available and the download rate is high enough to play through to the end without interruption. The waiting event fires when playback has stopped because of a temporary lack of data. A product also needs its own model of what the viewer is waiting for.

    Figure 3. Player phases

    stateDiagram-v2 accTitle: Phases of the buffering state machine accDescr: From idle the player loads a manifest. With autoplay or a play request it enters startup and waits for enough buffered video, then plays. A pause moves playing to paused. If the buffer empties while playing it enters rebuffering, a stall, and resumes after a deeper threshold. A seek outside the buffered range enters seeking and returns to playing or paused when enough data arrives. At the end of the video it is ended. A failure moves to error and a retry returns to startup or paused. [*] --> Idle Idle --> Loading: load Loading --> Startup: manifest, wants to play Loading --> Paused: manifest, no autoplay Startup --> Playing: enough buffered Startup --> Paused: autoplay refused or pause Paused --> Startup: play Playing --> Paused: pause Playing --> Rebuffering: buffer empty Rebuffering --> Playing: deeper threshold reached Playing --> Seeking: seek outside buffer Seeking --> Playing: enough buffered Playing --> Ended: end reached Ended --> Playing: replay Startup --> Error: failure Playing --> Error: failure Error --> Startup: retry

    How to read this: waiting appears three times with three meanings. Startup and seeking are waits the viewer asked for; rebuffering is a stall the player failed to avoid. The stall counter counts only the third.

    The lab's reducer implements these phases. Three details are worth stating as rules. A stall resumes only after a deeper threshold than startup needs (the lab uses 8 s against 4 s, illustrative), otherwise playback would stutter in and out of the stall. A seek inside the buffered range keeps playing, and a seek outside it flushes the buffer, restarts at a segment boundary and waits in its own phase, without counting a stall. A spinner shows only after a short delay (300 ms, illustrative) so a brief wait does not flash one.

    5. The first second: preload, poster and autoplay

    MDN's <video> reference defines preload as a hint with three values: none (do not preload), metadata (fetch only metadata such as length) and auto (the whole file may be downloaded). It defines poster as an image shown while the video downloads. For the browse page this is a decision about bandwidth: a grid of previews that all preload wastes data on titles nobody opens, which the prefetching lesson weighs.

    Autoplay is controlled by the browser, not the page. MDN's guide says autoplay is allowed as a general rule only if the audio is muted or its volume is 0, the user has interacted with the site, the site is allowlisted, or a Permissions Policy grants it to an iframe; otherwise playback will likely be blocked. play() returns a promise that rejects when playback fails to begin, for example if autoplay is denied, and MDN's example checks for a NotAllowedError and shows a play button. It also notes navigator.getAutoplayPolicy() can report allowed, allowed-muted or disallowed.

    So a start must be written as a request that can fail: the model has an autoplay-blocked action that moves startup to paused and shows "Press play to start", instead of a spinner that never ends.

    6. Controls, captions and accessibility

    MDN says the controls attribute makes the browser offer controls for volume, seeking and pause or resume, and that captions can be added by nesting <track> elements pointing at WebVTT files. A custom control bar replaces all of that and must provide each function itself: a play and pause button with an accurate name, a seek slider with a readable value, a quality menu and a status region. The lab's view does those, and its tests check roles and names in jsdom; they do not prove keyboard behaviour in a real browser or what a screen reader says.

    7. Failure handling and observability

    Segment requests fail. A sound player retries a failed request a bounded number of times with backoff, may switch to a lower rendition (a smaller segment is more likely to finish), and only then reports an error. Decode errors and fatal network errors can end the stream through endOfStream('decode') or endOfStream('network'), which MDN describes as terminating playback and signalling the error type, and the interface must offer a retry.

    Measure the quality of experience from the same state machine: time to first frame, stall count, stalled time, average bitrate, switch count. They are the columns in the lab's comparison table, and they are what Real User Monitoring would ship as beacons.

    Data flow

    Figure 4. A start: from click to first frame

    sequenceDiagram accTitle: Startup of a streaming playback accDescr: The viewer opens a title. The page fetches title metadata from the catalog API, which returns a manifest address. The player fetches the manifest from the CDN, picks the first rendition from a default throughput estimate, fetches the first segment, appends it to the source buffer and starts playing when enough is buffered. If the browser refuses autoplay, the player shows a play button instead. participant V as Viewer participant P as Player participant A as Catalog API participant C as CDN V->>P: opens a title, shows poster P->>A: title metadata A-->>P: manifest address P->>C: manifest C-->>P: renditions Note over P: first choice uses a default estimate P->>C: first segment (low rendition) C-->>P: segment P->>P: append, startup threshold reached alt autoplay allowed P->>V: first frame, playing else play() rejected P->>V: Press play to start end

    How to read this: the first choice is made before any throughput has been measured, so a cautious start (a low rendition) gets the first frame earlier, and the rule climbs once the buffer is deep.

    Build it

    The lab is examples/frontend/labs/video-abr-player, a pure model of the quality rule, the throughput estimator, the buffering state machine and a deterministic session simulator, with a thin React control bar. There is no <video>, no MediaSource, no segment and no network: time arrives as tick actions, data as segment actions, and the network is a list of (until, kbps) pieces. The ladder, the thresholds and the trace are illustrative.

    cd examples/frontend/labs/video-abr-player
    ../../node_modules/.bin/vitest run   # 47 tests: the rule, the estimator, the state machine, 300 seeded random sequences, the simulator, the React view in jsdom
    node src/demo.ts

    Illustration 1: the minimal example

    One decision, many cases. With the ladder above, the cautious rule and the naive "believe the estimate" rule are compared on the same inputs.

    Expected output, captured from a real run (the first section of the demo):

    1. Which rendition for the next segment? (ladder 240p 400, 360p 800, 480p 1400, 720p 2800, 1080p 5000 kbps)
      first segment, default estimate 1000             cautious 240p  (start)   throughput-only 360p
      on 480p, estimate 1600, buffer 20s               cautious 480p  (hold)   throughput-only 480p
      on 480p, estimate 5000, buffer 20s               cautious 720p  (up)   throughput-only 1080p
      on 480p, estimate 5000, buffer 8s                cautious 480p  (hold-low-buffer)   throughput-only 1080p
      on 480p, estimate 5000, switched 1 segment ago   cautious 480p  (hold-recent-switch)   throughput-only 1080p
      on 720p, estimate 2800, buffer 20s               cautious 480p  (down)   throughput-only 720p
      on 720p, estimate 2800, buffer 4s                cautious 480p  (down)   throughput-only 720p

    In the last two rows an estimate equal to the rendition's bitrate leaves no headroom, so the cautious rule steps down. In the fourth and fifth, a shallow buffer or a recent switch holds the quality at the same 5000 kbps estimate, while the naive rule jumps to 1080p.

    Illustration 2: the realistic example

    A 120 s video, 4 s segments, one made-up network: fast for 20 s, slow (1200 kbps) until 50 s, a recovery, then three 2 s dips to 900 kbps. Three policies run on it.

    Expected output, captured from a real run (the fifth section of the demo):

    5. Three policies on the same 120 s video and the same made-up network
      network: 6000 kbps to 20 s, 1200 kbps to 50 s, 3500 to 60 s, 6000 to 80 s, three 2 s dips to 900 kbps between 80 s and 90 s, then 6000
      one 4 s segment of 1080p is 20000000 bits; at 1200 kbps its transfer takes 16667 ms
      policy                   first frame  stalls   stalled  avg kbps  switches  finished
      always 1080p                 3600 ms       2  27400 ms      5000         0    151.0s
      throughput only               800 ms       1   8700 ms      2420         5    129.5s
      throughput and buffer         500 ms       0      0 ms      1193         5    120.5s

    Fixed 1080p stalls twice and the video finishes 31 s later than its length. The naive rule stalls once. The cautious rule never stalls here, and pays for it: its average bitrate is less than half of the naive rule's. That is the trade-off in numbers, for this trace only. The next excerpt shows why the cautious policy's average is low: it climbs slowly at the start.

    Expected output, captured from a real run (part of the sixth section of the demo):

    6. What the cautious policy chose around the slow stretch (segment number, rendition, why, buffer when chosen, estimate)
      segment  3  240p  hold-low-buffer     buffer  11.2s  estimate  5993 kbps
      segment  4  360p  up                  buffer  14.8s  estimate  5993 kbps
      segment  5  360p  hold-recent-switch  buffer  18.1s  estimate  5993 kbps
      segment  6  360p  hold-recent-switch  buffer  21.4s  estimate  5993 kbps
      segment  7  480p  up                  buffer  24.7s  estimate  5993 kbps

    On this 6000 kbps stretch the rule does not reach 720p until segment 10, 40 s into the video, because the buffer gate (12 s) and the two-segment dwell slow each climb. Whether that is acceptable is a product decision, and the lab's constants are not a recommendation.

    Illustration 3: a failure and an edge

    The state machine under a stall, a pause, a seek inside the buffer and a seek outside it, one action at a time.

    Expected output, captured from a real run (the third section of the demo):

    3. The buffering state machine, one action at a time (segments of 4 s, video of 20 s)
      load, autoplay                     loading     pos  0.0s  buffer ahead  0.0s  stalls 0  "Loading"  -
      manifest arrives                   startup     pos  0.0s  buffer ahead  0.0s  stalls 0  "Buffering"  -
      wait 400 ms                        startup     pos  0.0s  buffer ahead  0.0s  stalls 0  "Buffering"  spinner
      first segment appended             playing     pos  0.0s  buffer ahead  4.0s  stalls 0  "Playing at 480p"  -
      play 3 s                           playing     pos  3.0s  buffer ahead  1.0s  stalls 0  "Playing at 480p"  -
      play 1 s (buffer is empty)         rebuffering pos  4.0s  buffer ahead  0.0s  stalls 1  "Buffering, playback will resume"  -
      wait 300 ms                        rebuffering pos  4.0s  buffer ahead  0.0s  stalls 1  "Buffering, playback will resume"  spinner
      one segment appended (4 s < 8 s)   rebuffering pos  4.0s  buffer ahead  4.0s  stalls 1  "Buffering, playback will resume"  spinner
      second segment appended            playing     pos  4.0s  buffer ahead  8.0s  stalls 1  "Playing at 480p"  -
      play 2 s                           playing     pos  6.0s  buffer ahead  6.0s  stalls 1  "Playing at 480p"  -
      pause                              paused      pos  6.0s  buffer ahead  6.0s  stalls 1  "Paused"  -
      seek back to 6 s (inside buffer)   paused      pos  6.0s  buffer ahead  6.0s  stalls 1  "Paused"  -
      play                               playing     pos  6.0s  buffer ahead  6.0s  stalls 1  "Playing at 480p"  -
      seek to 16 s (outside buffer)      seeking     pos 16.0s  buffer ahead  0.0s  stalls 1  "Jumping to 0:16"  -
      segment appended                   playing     pos 16.0s  buffer ahead  4.0s  stalls 1  "Playing at 480p"  -
      play 4 s                           ended       pos 20.0s  buffer ahead  0.0s  stalls 1  "Ended"  -
      total: 1 stall(s), 300 ms stalled, first frame after 400 ms

    When one segment arrives during the stall, 4 s ahead is enough to start but not to resume, so the player waits until 8 s. The seek outside the buffer added no stall: the counter is 1 before and after. A refused autoplay and a failure with a retry are in the fourth section of the demo.

    Verified. The tests passed and every block above is a verbatim excerpt of examples/frontend/golden/video-abr-player.txt. The React tests ran in jsdom, a JavaScript model of the DOM: no video was decoded or rendered, no real network was used, and no keyboard or screen-reader behaviour was observed. The model has one buffered range, no audio, no variable bitrate, no container overhead, no DRM and no live playback.

    Trade-offs

    Decision Gain Cost Choose when
    Native HLS playback in the browser Least code, the browser does the work Less control over quality rules and buffering; support varies by browser Small teams, simple needs
    A player library on MSE (hls.js, dash.js style) Control over ABR, buffering and memory A dependency and a larger test surface Most large sites
    Build the player yourself Total control Very large effort and many edge cases Rarely justified
    Cautious up-switching Fewer stalls, fewer flaps Slower climb, lower average quality Mobile and variable networks
    Aggressive up-switching Sharper picture sooner More stalls on a bad dip Stable wired networks
    Larger buffer target More shock absorption More memory and more wasted data if the viewer leaves Long, linear viewing
    Deeper resume threshold Fewer stutters after a stall A longer stall before resuming Always, within reason
    Preload previews on browse Instant hover start Wasted data on unwatched titles Fast networks, small previews

    Alternatives considered

    • One progressive file. Simplest, but it cannot change quality mid-stream, so a slow network means a long stall for everyone.
    • Probing bandwidth before play. Delays the first frame and can mislead; measuring real segment downloads is better.

    Cross-cutting concerns

    Security. Treat manifests and segment URLs as untrusted input from the network: validate them, restrict the allowed hosts, and handle failures without leaking details. Authorization for a title is decided by the server; hiding the play button is not enforcement. Content protection is out of scope here.

    Accessibility. Captions through WebVTT tracks, an announced status, a seek slider with a readable value, keyboard operation of every control, and no auto-moving focus when playback starts. See Keyboard, Focus and Screen Readers and Accessibility Fundamentals and WCAG.

    Performance of the page itself. Posters are images (see the image lesson), the player code is a lazy chunk loaded only on the watch page (Code Splitting, Lazy Loading and Tree Shaking), and a stable player box avoids layout shift (Core Web Vitals).

    Cost. Capping quality by player size, not preloading what nobody watches and a sensible buffer target all save bytes. Set targets by measuring, not by copying another service's numbers.

    Evolution path

    1. Version 1: progressive playback and a poster.
    2. Version 2: adaptive streaming with a library, the state machine and the metrics.
    3. Version 3: capability filtering, player-size caps, preview prefetch rules, retry and failover.
    4. Version 4: tune the rule against recorded sessions, add live and DRM if the product needs them.

    Interview outline (45 minutes)

    Minutes Topic What a strong answer includes
    0 to 5 Requirements Fast start, few stalls, adaptive quality, seek, captions, autoplay; scope limits
    5 to 10 Estimates A ladder, segment size and download time versus play time
    10 to 20 Architecture Manifest, segments over a CDN, a player on MSE or native HLS, metrics
    20 to 30 Deep dive The quality rule (throughput plus buffer, asymmetric) and the state machine
    30 to 38 Failure Stall versus seek, autoplay refusal, retry, quota errors, a hidden player
    38 to 45 Evolution and trade-offs Library versus native, cautious versus aggressive, measurement

    In practice: the staff training video portal

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A company's internal training portal plays 20-minute videos that staff watch from offices and homes. The portal serves each video as one large file. Staff on slower links wait a long time before the first frame, scrub with long pauses and sometimes give up.

    Starting architecture

    Figure 5. Starting point: one file per video

    Starting architecture: one large file per videoStaff browser to Web server (GET video); Web server to Video file (read)Staff browser: video elementStaff browservideo elementWeb server: serves the fileWeb serverserves the fileVideo file: one bitrateVideo fileone bitrateGET videoread

    How to read this: there is a single bitrate for every viewer. A viewer whose network is slower than that bitrate stalls, and a viewer with a fast network never sees better quality.

    Options considered

    Option What it fixes What it costs Risk
    Re-encode at a lower bitrate Fewer stalls Worse picture for everyone Complaints from fast-network users
    Adaptive streaming with a player library Quality follows the network A transcoding step, a CDN, a player to maintain Tuning the quality rule
    A third-party video host No player work Cost and a data-sharing review Lock-in

    The decision

    Field Decision record
    Context Mixed networks, 20-minute videos, an internal audience, no live needs.
    Decision Adaptive streaming with a maintained player library, a four-rendition ladder, a cautious up-switch rule and the state machine in this lesson for the interface.
    Consequences, good Fast first frame, few stalls, quality follows the network.
    Consequences, bad A transcoding pipeline, a manifest to host and test, and a rule to tune.
    Revisit when The audience grows beyond the internal network or live events are needed.

    Rollout and verification

    1. Test the rule and the state machine as pure functions, with recorded or synthetic traces, as the lab does.
    2. Canary the new player to a small group while the old page stays available.
    3. Verify on real devices and browsers (the lab cannot): decode support, autoplay behaviour and captions.
    4. Watch time to first frame, stall count and time, average bitrate and switches by network type.

    The 2 a.m. failure

    Reports arrive that the picture is stuck at the lowest quality on good office networks, but only on the watch page that opens in a collapsed side panel. The player caps quality by the video element's size, and while the panel is collapsed the element measures zero pixels tall, so the cap is the lowest rendition and is never recomputed when the panel opens. First three checks: (1) log the measured player height at each decision; (2) check whether the cap is recomputed on resize and visibility changes; (3) compare the chosen rendition with the estimate. Mitigation: treat a zero or hidden size as "unknown" and fall back to the largest allowed height. Follow-up: a test with the cap at zero. In the lab, a cap below the lowest rendition always selects the lowest, which is the same trap.

    Architect's notes

    • Put the state machine and the rule in pure functions. Network and clock become inputs, and bad traces become tests.
    • Make the first choice cautious. It is made without data, so a low start protects the first frame.
    • Treat waiting as three states. Startup, stall and seek are counted and shown differently.
    • Never assume autoplay works. Write the refusal path first.
    • Do not copy another service's constants. Thresholds depend on your ladder, segments and audience; measure and tune.

    Common mistakes

    • Choosing quality from throughput alone. Ignoring the buffer makes the player flap and stall.
    • Symmetric switching rules. Climbing as fast as dropping makes a single good sample cause a stall.
    • Resuming after a stall at the startup threshold. The player stutters.
    • Counting a seek as a stall. Metrics then punish the viewer for scrubbing.
    • Calling appendBuffer() while updating is true. It throws; queue the appends.
    • Ignoring quota errors. A full buffer needs eviction behind the playhead.
    • Preloading every preview on a browse page, or measuring player size while it is hidden.

    Key takeaways

    • Streaming video is many short segments at several bitrates, chosen by the client.
    • The buffer protects the viewer; quality rules protect the buffer: down fast, up slow.
    • A segment that downloads slower than it plays drains the buffer.
    • Startup, stall and seek are different waits and need different rules and counters.
    • Autoplay can be refused; the player needs a visible way to start.
    • MSE gives control and responsibility: queue appends, handle quota, expect eviction.
    • Measure time to first frame, stalls, average bitrate and switches, and tune against real sessions.

    Practice exercises

    Exercise 1: Starter (30 min). Run the demo. For each row of the first section, work out which rule decided it.

    Exercise 2: Intermediate (3 hours). Add a rule that fetches a smaller first segment to cut time to first frame, and measure it with the simulator. What does it do to the average bitrate?

    Exercise 3: Advanced (1 day). Model two buffered ranges so that seeking back into a flushed range is a hit, and decide what the append queue does when a seek abandons a request.

    Exercise 4: Interview (45 min). Whiteboard this design from the outline above, and defend a cautious up-switch rule to a product owner who wants a sharper picture sooner.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments