System Design

C9

Video upload and streaming

Upload, transcode and stream video to millions of viewers on any device. The hard parts are large uploads that fail half way, transcoding fast enough, and smooth playback on a changing network.

Not startedSaved in this browser only.
  1. 1Bytes go straight from the client to object storage with presigned multipart URLs. A dropped upload resumes from the parts already stored.
  2. 2Transcoding is a DAG of small jobs: split at keyframes, encode every segment of every rung in parallel, package, publish. A queue with a visibility timeout retries a dead worker.
  3. 3The player streams HLS segments and picks a rung per segment from measured throughput and its buffer. The buffer target trades start time for stalls.
  4. 4Segments never change, so the CDN caches them for a long time. An origin shield turns the misses of every edge into one read of the store.
C9
    A

    The prompt

    as the interviewer says it
    "Design a video platform: upload, transcode, and stream to millions of viewers on any device."
    questionanswer assumed
    How many uploads?500 k videos a day, 5 minutes on average.
    Source quality?Up to 1080p, about 10 Mbit/s.
    How many views?1 B a day, 5 minutes watched on average.
    Which devices?Phones, browsers and TVs, on networks from Wi-Fi to a weak mobile signal.
    Time to playable?Minutes after the upload ends.
    Live streaming?A follow-up. On demand only.

    I confirm upload and view volume, video length, which devices, and whether live streaming is in scope.

    B

    Requirements

    as numbers
    functional
    Upload a large file from an unreliable network.
    Transcode to a ladder of resolutions and bitrates.
    Stream on any device; adapt to its bandwidth.
    Show title, thumbnails and a view count.
    non-functionaltarget
    Upload resumeResend at most one part
    Upload to playable< 5 min for a 5-min video
    Start of playbackp95 < 2 s
    StallsRare; prefer a lower rung to a stall
    Durability of uploadsNever lose an acked upload

    An upload must survive a dropped connection, and playback must start fast and rarely stall.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Uploads500 k ÷ 86,400≈ 5.8/s; 3× peak ≈ 17/s
    Ingest500 k × 300 s × 10 Mbit/s ÷ 86,400≈ 17 Gbit/s
    Originals300 s × 10 Mbit/s ÷ 8 = 375 MB × 500 k≈ 190 TB a day
    Renditions300 s × 11,365 kbit/s (all 4 rungs) ÷ 8 = 426 MB × 500 k≈ 210 TB a day
    Storage a year(190 + 210) TB × 365≈ 146 PB, one copy
    Transcode tasks5.8/s × 207 tasks a video≈ 1,200/s; peak ≈ 3,600/s
    Transcode workers500 k × 300 s × 2.6 worker-s per source s ÷ 86,400≈ 4,500 busy on average
    Views1 B ÷ 86,400≈ 12,000/s
    Concurrent streams1 B × 300 s ÷ 86,400≈ 3.5 M
    Egress3.5 M × 2.9 Mbit/s mean rung≈ 10 Tbit/s; peak ≈ 31
    Segment requests3.5 M streams ÷ 6 s segments≈ 579,000/s at the edges

    Inputs are the assumed answers in panel A. Worker time comes from the lab's cost model: a worker encodes 1080p at real-time speed. The mean rung is the lab player's at a 24 s buffer. Method: R2.

    Egress dominates: about 10 Tbit/s on average, which only a CDN can serve. Ingest is about 17 Gbit/s, and storage grows by about 400 TB a day.

    D

    API

    metadata through the API, bytes around it
    callbodysuccesserrors
    POST /v1/videos + Idempotency-Keytitle, size, content type201 video id, upload id, part URLs400, 413
    PUT <presigned part URL>part bytes, SHA-256200 + ETag (to the store)400 bad checksum, 403 expired
    GET /v1/uploads/{id}/partsnone200 part numbers held404
    POST /v1/videos/{id}/completepart list202 processing409 part missing
    GET /v1/videos/{id}none200 status, master URL, thumbnails404
    GET cdn/v/{id}/master.m3u8, then segmentsnone200, cached for a long time403 bad signature
    POST /v1/videos/{id}/viewssession id204429
    • Complete is idempotent: a retry finds the video already in state processing and returns 202 again.
    • Part URLs expire in hours. A client that resumes later asks for new ones.

    The API signs URLs and keeps metadata. Uploads go straight to the store, and playback goes straight to the CDN.

    E

    Data model

    Postgres for metadata, the object store for bytes
    metadata: five tables in Postgres1 : n1 : n1 : n1 : ntasksPK FKvideo_idPKidkindcost_mslongest firstwaitingparents leftdone_atset onceone row per DAG nodetask_edgesPKvideo_idPK FKparentPK FKchildparent before childvideosPKidowner_idstatusprocessing, readysource_keyoriginalmaster_keyHLS entrycached by the APIrenditionsPK FKvideo_idPKnamebitrate_kbpsplaylist_keyone per ladder rungvideo_viewsPK FKvideo_idPKdayviewsbatchedflushed every minute
    object keyholdscache
    src/{video}The original uploadNever served
    v/{video}/master.m3u8The rung listMinutes
    v/{video}/{rung}/index.m3u8One rung's segment listLong; it never changes
    v/{video}/{rung}/seg007.tsSix seconds of videoLong; it never changes
    videos, renditions, tasks, task_edges, video_viewssql
    CREATE TABLE videos (
      id          bigint PRIMARY KEY,
      owner_id    bigint NOT NULL,
      title       text   NOT NULL,
      status      text   NOT NULL CHECK (status IN
                    ('uploading', 'processing', 'ready', 'failed')1),
      source_key  text   NOT NULL,     -- the original upload
      duration_s  int    NOT NULL,
      master_key  text                 -- HLS master playlist, once ready
    );
    
    -- One row per rung of the bitrate ladder.
    CREATE TABLE renditions (
      video_id     bigint NOT NULL REFERENCES videos (id),
      name         text   NOT NULL,    -- '360p', '1080p'
      width        int    NOT NULL,
      height       int    NOT NULL,
      bitrate_kbps int    NOT NULL,
      playlist_key text   NOT NULL,
      PRIMARY KEY (video_id, name)
    );
    
    -- The transcode DAG: one row per task, queued once waiting is 0.
    CREATE TABLE tasks (
      video_id bigint NOT NULL REFERENCES videos (id),
      id       text   NOT NULL,        -- 'split', 'enc/720p/007'
      kind     text   NOT NULL,
      cost_ms  int    NOT NULL2,        -- expected run time
      waiting  int    NOT NULL3,        -- parents not yet done
      done_at  timestamptz4,
      PRIMARY KEY (video_id, id)
    );
    
    CREATE TABLE task_edges (
      video_id bigint NOT NULL,
      parent   text   NOT NULL,
      child    text   NOT NULL,
      PRIMARY KEY (video_id, parent, child),
      FOREIGN KEY (video_id, parent)5 REFERENCES tasks (video_id, id),
      FOREIGN KEY (video_id, child) REFERENCES tasks (video_id, id)
    );
    
    -- Daily views, added in batches from per-minute counters.
    CREATE TABLE video_views (
      video_id bigint NOT NULL REFERENCES videos (id),
      day      date   NOT NULL,
      views    bigint NOT NULL6,
      PRIMARY KEY (video_id, day)
    );
    1. 1The video moves forward only. Playback reads ready videos.
    2. 2Ready tasks are queued longest first, so a long encode does not start last.
    3. 3A counter of parents not yet done. The task is queued when it reaches 0.
    4. 4Set once. A retried finish sees it set and does nothing.
    5. 5Edges name real tasks of the same video.
    6. 6A daily total per video, written in batches.

    Postgres holds the video row, the DAG and the queue. Every byte lives in the object store under a fixed key per video, rung and segment.

    F

    The architecture

    click a step; its path lights up
    Clientapp, browser, TVAPImetadata, sign URLsCDN edgessegment cachePostgresvideos, DAG, queueRedisview countersOrigin shieldone cache tierWorkerssplit, encode, packageObject storeoriginals, segments

    Step 1: Upload

    • The API writes a video row and starts a multipart upload.
    • The client sends parts straight to the store with presigned URLs.
    • After a drop, it lists the stored parts and sends only the rest.

    If it fails

    The client never finishes: a sweep deletes uploads still pending after a day, and a lifecycle rule aborts the parts.

    Uploads go to the object store, a DAG of jobs on a queue transcodes them, and the CDN serves segments to a player that adapts.

    G

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    Object storeMultipart upload; list partsParts in parallel and in any order; resume from what is stored.Backups, large exports
    Object storePresigned URLsThe client sends bytes straight to the store, only to the key the API chose.Downloads, avatars
    Object storeLifecycle rules, storage classesAbort stale uploads; move cold originals to a cheaper class.Log retention
    PostgresFOR UPDATE SKIP LOCKED, visibility timeThe job queue: one worker per job; a dead worker's job comes back.Email, webhooks
    PostgresData-modifying CTEsFinish a task, release its children and queue the ready ones in one statement.Workflows
    PostgresUPDATE ... WHERE done_at IS NULLA retried finish changes nothing and queues nothing.Idempotent handlers
    RedisINCRBYView counts per video per minute, flushed to Postgres.Rate limits, likes
    WorkersStateless processesAny worker runs any task; add workers for more parallel encodes.Image resizing
    ffmpegForced keyframes, segmenting, HLS outputEvery rung cut at the same times, so the player can switch.Thumbnails, audio
    HLS, DASHA manifest of rungs and segmentsOne URL that every device understands; the player chooses.Live video
    CDNEdge cache, origin shield, signed URLsServes the egress; one miss per segment reaches the store.Static assets

    The object store gives me multipart uploads and presigned URLs. Postgres gives me a queue with SKIP LOCKED and a DAG update in one statement.

    H

    Deep dive: resumable upload

    gigabytes from a phone on a train
    methodstatuswhy
    Upload through the API serversNot approvedEvery byte crosses the app tier; a restart loses the upload.
    One presigned PUTSmall filesSimple, but a drop at 90% starts over.
    Presigned multipart uploadApprovedParts in parallel; resume sends only missing parts.
    A resumable protocol (tus)Own upload serviceResume by byte offset; you run the receiving servers.
    • The lab test drops the connection after 3 of 5 parts. The resume sends parts 4 and 5 only: every byte crosses once.
    • Each part carries its SHA-256. The store refuses a corrupted part, and only that part is sent again.
    • Mechanism and presigned URLs in depth: B9.
    direct, resumable uploadpseudo code
    start_upload(user, title, size):
      video = INSERT videos (status 'uploading')
      id = store.create_multipart1(key = "src/" + video)
      RETURN video, id, a presigned PUT URL per part2
    
    client, also after a crash:
      have = store.list_parts(id)3              // what already arrived
      FOR EACH part n NOT IN have:
        PUT part n, with its SHA-256           // straight to the store
      POST /videos/{video}/complete
    
    complete(video):
      store.complete(id, parts in order)       // the object appears at once4
      INSERT the DAG; queue the tasks with no parent
    1. 1Nothing is visible under the key until complete. A half upload never looks like a video.
    2. 2Signed for one key, one method and an expiry. The client cannot write anywhere else.
    3. 3The store is the record of progress, so the client needs no local state to resume.
    4. 4Complete joins the parts in order. Readers see the whole file or nothing.
    Tested source Go: multipart upload
    Go: multipart uploadgo
    // CreateUpload starts a multipart upload for key. Nothing is visible under key until Complete.
    func (s *ObjectStore) CreateUpload(key string) string {
      s.mu.Lock()
      defer s.mu.Unlock()
      s.nextID++
      id := "u" + strconv.Itoa(s.nextID)
      s.uploads[id] = &upload{key: key, parts: map[int][]byte{}}
      return id
    }
    
    // UploadPart stores one part. Parts can arrive in any order and in parallel; sending a part again
    // replaces it. The client sends the SHA-256 of the part, and a corrupted part is refused.
    func (s *ObjectStore) UploadPart(id string, n int, data []byte, sum string) error {
      if digest(data) != sum {
        return fmt.Errorf("part %d: %w", n, ErrBadChecksum)
      }
      s.mu.Lock()
      defer s.mu.Unlock()
      u, ok := s.uploads[id]
      if !ok {
        return fmt.Errorf("upload %s: %w", id, ErrNoUpload)
      }
      u.parts[n] = slices.Clone(data)
      return nil
    }
    
    // ListParts returns the part numbers the store holds, so a client can resume after a crash.
    func (s *ObjectStore) ListParts(id string) ([]int, error) {
      s.mu.Lock()
      defer s.mu.Unlock()
      u, ok := s.uploads[id]
      if !ok {
        return nil, fmt.Errorf("upload %s: %w", id, ErrNoUpload)
      }
      nums := make([]int, 0, len(u.parts))
      for n := range u.parts {
        nums = append(nums, n)
      }
      slices.Sort(nums)
      return nums, nil
    }
    
    // Complete joins the listed parts in order into one object. The object appears all at once.
    func (s *ObjectStore) Complete(id string, parts []int) (Object, error) {
      s.mu.Lock()
      defer s.mu.Unlock()
      u, ok := s.uploads[id]
      if !ok {
        return Object{}, fmt.Errorf("upload %s: %w", id, ErrNoUpload)
      }
      var data []byte
      for i, n := range parts {
        p, ok := u.parts[n]
        if !ok {
          return Object{}, fmt.Errorf("part %d: %w", n, ErrMissingPart)
        }
        if i < len(parts)-1 && len(p) < s.MinPart {
          return Object{}, fmt.Errorf("part %d is %d bytes: %w", n, len(p), ErrSmallPart)
        }
        data = append(data, p...)
      }
      o := Object{Data: data, SHA256: digest(data), ContentType: "application/octet-stream"}
      s.objects[u.key] = o
      delete(s.uploads, id)
      return o, nil
    }
    

    I hand the client presigned part URLs. It uploads parts straight to the store, and after a drop it lists what arrived and sends only the rest.

    I

    Deep dive: the transcode DAG and its queue

    many small jobs instead of one long one
    one video: 20 segments × 4 rungs = 80 encodessplit360pseg 0360pseg 1360pseg 2…360pseg 19playlist 360p540pseg 0540pseg 1540pseg 2…540pseg 19playlist 540p720pseg 0720pseg 1720pseg 2…720pseg 19playlist 720p1080pseg 01080pseg 11080pseg 2…1080pseg 19playlist 1080pthumbnails: one per segmentpublishcritical path (bold): split → longest 1080p segment → its playlist → publish
    methodstatuswhy
    One job per video on one machineShort videos310.7 s for 2 minutes of video; a crash redoes all of it.
    One job per rungFew workers4 jobs in parallel; 1080p still runs alone and longest.
    A DAG of segment jobs on a queueApprovedHundreds of jobs in parallel; a crash redoes one segment.
    Run the DAG from memory in one coordinatorNot approvedThe coordinator dies and the state of every video is gone.
    segment lengthtasks1 worker64 workerswhy
    2 s247472.7 s15.1 sEach task pays the start cost.
    6 s87310.7 s14.5 sApple's recommended length.
    12 s47270.2 s20.5 sThe longest segment sets the floor.
    the DAG of one videopseudo code
    build_dag(video, segments, ladder):
      split                                    // cut at keyframes, no encode1
      FOR EACH rung r, FOR EACH segment s:
        encode(r, s)    after split            // all in parallel2
      thumbs            after split
      FOR EACH rung r:
        playlist(r)     after every encode(r, *)3
      publish           after every playlist and thumbs
    1. 1A stream copy at keyframes is fast. Each segment then decodes on its own.
    2. 2Segments times rungs: 80 jobs for a 2-minute video at 6 s segments.
    3. 3A playlist lists every segment, so it waits for all of them.
    Tested source Go: build the DAG
    Go: build the DAGgo
    // Tasks returns the DAG: split the source at keyframes, encode every segment to every rung in
    // parallel, make thumbnails beside them, write one playlist per rung, then publish the master
    // playlist. Every rung uses the same segment boundaries, so a player can switch at any segment.
    func (p Plan) Tasks() []Task {
      c := p.Costs
      px := func(r Rendition) float64 { return float64(r.Width*r.Height) / (1920 * 1080) }
      secs := func(s float64) time.Duration { return time.Duration(s * float64(time.Second)) }
      n := p.Segments()
      out := []Task{{ID: "split", Kind: "split", Cost: c.Overhead + secs(float64(p.Seconds)/c.SplitSpeed)}}
      publish := Task{ID: "publish", Kind: "publish", Cost: c.Overhead}
      for _, r := range p.Ladder {
        pack := Task{ID: "pack/" + r.Name, Kind: "package", Rn: r.Name, Cost: c.Overhead + c.PackagePerRn}
        for s := range n {
          length := float64(min(p.SegSeconds, p.Seconds-s*p.SegSeconds))
          out = append(out, Task{
            ID: encID(r.Name, s), Kind: "encode", Rn: r.Name, Seg: s, Parents: []string{"split"},
            Cost: c.Overhead + secs(length*px(r)/c.EncodeSpeed),
          })
          pack.Parents = append(pack.Parents, encID(r.Name, s))
        }
        out = append(out, pack)
        publish.Parents = append(publish.Parents, pack.ID)
      }
      out = append(out, Task{ID: "thumbs", Kind: "thumbs", Parents: []string{"split"}, Cost: c.Overhead + time.Duration(n)*c.ThumbPerSeg})
      publish.Parents = append(publish.Parents, "thumbs")
      return append(out, publish)
    }
    
    one workerpseudo code
    worker loop:
      job = claim one visible job              // SKIP LOCKED, hidden for 30 s1
      run the task; write output to a fixed key2
      finish(task)                             // one statement:
        mark done WHERE done_at IS NULL3
        each child: waiting = waiting - 1
        queue children with waiting = 0, longest first4
      ack job
      // crash before the ack: the job is visible again after 30 s
      // 3 failed attempts: bury in dead_jobs5, mark the video failed
    1. 1The claim hides the job. The timeout must be longer than the longest task, or a slow task runs twice.
    2. 2A repeated attempt overwrites the same object; nothing is duplicated.
    3. 3A task that already finished changes no row, so its children are not released twice.
    4. 4Long encodes start early, so they do not finish last.
    5. 5A corrupt source fails every time. Stop after 3 tries and tell the owner.
    Tested source Go: the worker loop · SQL: finish a task
    Go: the worker loopgo
    // Process runs plan on n workers until it is published or a task is buried as poison. Each idle
    // worker claims the oldest visible job. A finished task releases its children and is acked; a
    // crashed attempt is never acked, so its job comes back when the claim's visibility ends.
    func (p *Pipeline) Process(ctx context.Context, plan Plan, n int, fails Fails) (Run, error) {
      byID := map[string]Task{}
      for _, t := range plan.Tasks() {
        byID[t.ID] = t
      }
      run := Run{Workers: n}
      busy := make([]*running, n)
      var now time.Duration
      for {
        // Every idle worker claims one job, in worker order.
        for w := range n {
          if busy[w] != nil {
            continue
          }
          jobs, dead, err := p.Queue.Claim(ctx, p.at(now), workerName(w), 1)
          if err != nil {
            return run, fmt.Errorf("worker %d: %w", w, err)
          }
          for _, d := range dead {
            run.Dead = append(run.Dead, d.Payload)
          }
          if len(dead) > 0 {
            return run, p.fail(ctx, plan.Video, &run)
          }
          if len(jobs) == 0 {
            break // nothing visible: the other idle workers would get nothing either
          }
          j := jobs[0]
          t := byID[strings.SplitN(j.Payload, ":", 2)[1]]
          r := &running{job: j, task: t, start: now, end: now + t.Cost}
          if fails != nil && fails(t.ID, j.Attempts) {
            r.crash, r.end = true, now+t.Cost/2
          }
          busy[w] = r
        }
    
        // Move the clock to the next event: a task ends, or a hidden job becomes visible.
        next := time.Duration(math.MaxInt64)
        idle := false
        for _, r := range busy {
          if r == nil {
            idle = true
            continue
          }
          next = min(next, r.end)
        }
        if idle {
          var vis *time.Time
          if err := p.DB.QueryRow(ctx, stmts["next_visible"], p.at(now)).Scan(&vis); err != nil {
            return run, fmt.Errorf("next visible job: %w", err)
          }
          if vis != nil {
            next = min(next, vis.Sub(p.Epoch))
          }
        }
        if next == time.Duration(math.MaxInt64) {
          return run, fmt.Errorf("video %d at %v: %w", plan.Video, now, ErrStuck)
        }
        now = next
    
        for w, r := range busy {
          if r == nil || r.end != now {
            continue
          }
          busy[w] = nil
          run.Spans = append(run.Spans, Span{
            Worker: w, Task: r.task.ID, Kind: r.task.Kind, Start: r.start.Milliseconds(),
            End: now.Milliseconds(), Attempt: r.job.Attempts, Crashed: r.crash,
          })
          if r.crash {
            continue // no ack: the job stays hidden until its visibility ends
          }
          if err := p.do(ctx, plan, r.task, now); err != nil {
            return run, err
          }
          if _, err := p.DB.Exec(ctx, stmts["finish"], plan.Video, r.task.ID, p.at(now)); err != nil {
            return run, fmt.Errorf("finish %s: %w", r.task.ID, err)
          }
          if _, err := p.Queue.Ack(ctx, workerName(w), r.job.ID); err != nil {
            return run, fmt.Errorf("worker %d: %w", w, err)
          }
          if r.task.ID == "publish" {
            run.Status, run.Makespan = "ready", now.Milliseconds()
            return run, nil
          }
        }
      }
    }
    
    SQL: finish a tasksql
    -- In one statement: mark the task done once, release each child,
    -- and queue the children with no parent left, longest first. A
    -- retry of a finished task changes no row and queues nothing.
    WITH done AS (
      UPDATE tasks SET done_at = $3
      WHERE video_id = $1 AND id = $2 AND done_at IS NULL
      RETURNING video_id, id
    ), freed AS (
      UPDATE tasks t SET waiting = t.waiting - 1
      FROM task_edges e, done d
      WHERE e.video_id = d.video_id AND e.parent = d.id
        AND t.video_id = e.video_id AND t.id = e.child
      RETURNING t.video_id, t.id, t.cost_ms, t.waiting
    )
    INSERT INTO jobs (payload, visible_at)
    SELECT video_id || ':' || id, $3 FROM freed WHERE waiting = 0
    ORDER BY cost_ms DESC, id;

    I split the source at keyframes and encode every segment of every rung as its own job. On the lab's cost model, 32 workers finish a 2-minute video in 17.8 s against 310.7 s on one.

    J

    See it: the DAG run and the player

    recorded from the lab
    workers
    failure
    0 s10 s20 s30 s40 sw0w1w2w3w4w5w6w7split: 0 to 5 s on worker 0enc/1080p/000: 5 to 12 s on worker 0enc/1080p/001: 5 to 12 s on worker 1enc/1080p/002: 5 to 12 s on worker 2enc/1080p/003: 5 to 12 s on worker 3enc/1080p/004: 5 to 12 s on worker 4enc/1080p/005: 5 to 12 s on worker 5enc/1080p/006: 5 to 12 s on worker 6enc/1080p/007: 5 to 12 s on worker 7enc/1080p/008: 12 to 19 s on worker 0enc/1080p/009: 12 to 19 s on worker 1enc/1080p/010: 12 to 19 s on worker 2enc/1080p/011: 12 to 19 s on worker 3enc/1080p/012: 12 to 19 s on worker 4enc/1080p/013: 12 to 19 s on worker 5enc/1080p/014: 12 to 19 s on worker 6enc/1080p/015: 12 to 19 s on worker 7enc/720p/000: 19 to 22.7 s on worker 4enc/720p/001: 19 to 22.7 s on worker 5enc/720p/002: 19 to 22.7 s on worker 6enc/720p/003: 19 to 22.7 s on worker 7enc/1080p/016: 19 to 26 s on worker 0enc/1080p/017: 19 to 26 s on worker 1enc/1080p/018: 19 to 26 s on worker 2enc/1080p/019: 19 to 26 s on worker 3enc/720p/004: 22.7 to 26.3 s on worker 4enc/720p/005: 22.7 to 26.3 s on worker 5enc/720p/006: 22.7 to 26.3 s on worker 6enc/720p/007: 22.7 to 26.3 s on worker 7enc/720p/008: 26 to 29.7 s on worker 0enc/720p/009: 26 to 29.7 s on worker 1enc/720p/010: 26 to 29.7 s on worker 2enc/720p/011: 26 to 29.7 s on worker 3enc/720p/012: 26.3 to 30 s on worker 4enc/720p/013: 26.3 to 30 s on worker 5enc/720p/014: 26.3 to 30 s on worker 6enc/720p/015: 26.3 to 30 s on worker 7enc/540p/000: 30 to 32.5 s on worker 4enc/540p/001: 30 to 32.5 s on worker 5enc/540p/002: 30 to 32.5 s on worker 6enc/540p/003: 30 to 32.5 s on worker 7enc/720p/016: 29.7 to 33.3 s on worker 0enc/720p/017: 29.7 to 33.3 s on worker 1enc/720p/018: 29.7 to 33.3 s on worker 2enc/720p/019: 29.7 to 33.3 s on worker 3enc/540p/004: 32.5 to 35 s on worker 4enc/540p/005: 32.5 to 35 s on worker 5enc/540p/006: 32.5 to 35 s on worker 6enc/540p/007: 32.5 to 35 s on worker 7enc/540p/008: 33.3 to 35.8 s on worker 0enc/540p/009: 33.3 to 35.8 s on worker 1enc/540p/010: 33.3 to 35.8 s on worker 2enc/540p/011: 33.3 to 35.8 s on worker 3enc/540p/012: 35 to 37.5 s on worker 4enc/540p/013: 35 to 37.5 s on worker 5enc/540p/014: 35 to 37.5 s on worker 6enc/540p/015: 35 to 37.5 s on worker 7enc/540p/016: 35.8 to 38.3 s on worker 0enc/540p/017: 35.8 to 38.3 s on worker 1enc/540p/018: 35.8 to 38.3 s on worker 2enc/540p/019: 35.8 to 38.3 s on worker 3enc/360p/000: 37.5 to 39.2 s on worker 5enc/360p/001: 37.5 to 39.2 s on worker 6enc/360p/002: 37.5 to 39.2 s on worker 7thumbs: 37.5 to 39.5 s on worker 4enc/360p/003: 38.3 to 40 s on worker 0enc/360p/004: 38.3 to 40 s on worker 1enc/360p/005: 38.3 to 40 s on worker 2enc/360p/006: 38.3 to 40 s on worker 3enc/360p/007: 39.2 to 40.8 s on worker 5enc/360p/008: 39.2 to 40.8 s on worker 6enc/360p/009: 39.2 to 40.8 s on worker 7enc/360p/010: 39.5 to 41.2 s on worker 4enc/360p/011: 40 to 41.7 s on worker 0enc/360p/012: 40 to 41.7 s on worker 1enc/360p/013: 40 to 41.7 s on worker 2enc/360p/014: 40 to 41.7 s on worker 3enc/360p/015: 40.8 to 42.5 s on worker 5enc/360p/016: 40.8 to 42.5 s on worker 6enc/360p/017: 40.8 to 42.5 s on worker 7enc/360p/018: 41.2 to 42.8 s on worker 4pack/1080p: 41.7 to 43.2 s on worker 1pack/720p: 41.7 to 43.2 s on worker 2pack/540p: 41.7 to 43.2 s on worker 3enc/360p/019: 41.7 to 43.3 s on worker 0pack/360p: 43.3 to 44.8 s on worker 0publish: 44.8 to 45.8 s on worker 0one row per worker
    • encode one segment to one rung
    • split, thumbnails, playlists, publish
    • attempt lost in a crash
    • retry after the visibility timeout
    Total 45.8 s for a 120 s video. One worker takes 310.7 s; no number of workers beats the critical path of 14.5 s.
    Total time in seconds by segment length and workers (same video, same cost model)
    segmenttasks1 w2 w4 w8 w16 w32 w64 wcritical path
    2 s247472.7239.9123.265.436.822.415.110.5
    6 s87310.715983.345.827.317.814.514.5
    12 s47270.2138.87339.824.520.520.520.5

    Cost model, not a measurement: a worker encodes 1080p at real-time speed, smaller rungs scale with pixels, and every task pays 1 s to start.

    The transcode runs claim real jobs from a Postgres queue on simulated time; task times come from the cost model. The player runs on seeded traces. The lab checks: every task finishes exactly once, no task starts before its parents, and the published playlists list every stored segment.

    A crash costs at most one visibility timeout on that task. The player trades bitrate for stalls, and the buffer target sets how much.

    K

    Deep dive: adaptive bitrate streaming

    the player chooses, segment by segment
    master playlist, the first fetchHLS
    #EXTM3U
    #EXT-X-STREAM-INF:BANDWIDTH=3650001,RESOLUTION=640x360
    360p/index.m3u8
    #EXT-X-STREAM-INF:BANDWIDTH=2000000,RESOLUTION=960x540
    540p/index.m3u8
    #EXT-X-STREAM-INF:BANDWIDTH=3000000,RESOLUTION=1280x720
    720p/index.m3u8
    #EXT-X-STREAM-INF:BANDWIDTH=6000000,RESOLUTION=1920x1080
    1080p/index.m3u82
    1. 1Bits per second of this rung. The player compares it with what it measures.
    2. 2Each rung has its own media playlist of segments.
    media playlist of one rung, a 20 s clipHLS
    #EXTM3U
    #EXT-X-VERSION:3
    #EXT-X-TARGETDURATION:61
    #EXT-X-MEDIA-SEQUENCE:0
    #EXT-X-PLAYLIST-TYPE:VOD
    #EXTINF:6.000,
    seg000.ts
    #EXTINF:6.000,
    seg001.ts2
    #EXTINF:6.000,
    seg002.ts
    #EXTINF:2.000,
    seg003.ts
    #EXT-X-ENDLIST3
    1. 1Apple recommends 6 s segments and a keyframe every 2 s.
    2. 2Segment 1 covers the same 6 s in every rung, so a switch is seamless.
    3. 3A finished video. A live playlist has no end tag and is fetched again.
    policystatusstalls per session, 24 s buffer
    One fixed bitrateNot approved15.4
    Throughput: highest rung under 80% of measuredApproved1.3; mean 2.9 Mbit/s
    Buffer level picks the rungDeep buffer5.7; at 60 s: 0.1, 4.0 Mbit/s
    • Starting on the lowest rung shows the first frame after 0.3 s on average, against 4.6 s at 1080p.
    • With a 12 s target, a full buffer is only 6 s, yet the buffer policy maps it to 1080p. It stalls 23.6 times a session.
    • With 60 s of buffer it stalls less than the throughput policy (0.1 against 0.4) at a higher bitrate.
    the playerpseudo code
    next_rung(buffer, samples):
      throughput policy:
        IF no samples: RETURN lowest           // start fast
        est = harmonic mean of the last 3 samples1
        RETURN highest rung with bitrate <= 0.8 × est2
      buffer policy:
        RETURN rung by buffer / (target - segment)
    
    play():
      FOR EACH segment:
        wait until buffer + segment <= target3
        r = next_rung(buffer, samples)
        fetch segment at rung r                // the buffer drains meanwhile
        IF the buffer hit 0 first: a stall4
        buffer += segment; samples += bits / fetch time
    1. 1One fast segment cannot lift a harmonic mean far, so the player is slow to step up.
    2. 2A safety share: the rung must fit with room to spare.
    3. 3The buffer target. A bigger target rides out longer dips but costs bytes if the viewer leaves.
    4. 4The picture stops and the viewer sees a spinner until the segment arrives.
    Tested source Go: choose a rung · Go: play a session
    Go: choose a runggo
    // choose returns the rung for the next segment. throughput: the highest rung whose bitrate fits
    // in Safety × the harmonic mean of the last few segment throughputs. buffer: map the buffer level
    // onto the ladder, lowest when nearly empty, highest when nearly full.
    func (p Player) choose(ladder []Rendition, buffer float64, samples []float64) (int, float64) {
      top := len(ladder) - 1
      switch p.Policy {
      case Highest:
        return top, 0
      case Throughput:
        if len(samples) == 0 {
          return 0, 0 // nothing measured yet: start low
        }
        recent := samples[max(0, len(samples)-p.History):]
        var inv float64
        for _, s := range recent {
          inv += 1 / s
        }
        est := float64(len(recent)) / inv // a harmonic mean: one fast sample cannot lift it far
        rung := 0
        for i, r := range ladder {
          if float64(r.Kbps) <= p.Safety*est {
            rung = i
          }
        }
        return rung, est
      case Buffer:
        full := p.Target - p.Seg // the most the buffer holds when a request goes out
        return min(top, int(buffer/full*float64(len(ladder)))), 0
      }
      panic(fmt.Sprintf("unknown policy %q", p.Policy))
    }
    
    Go: play a sessiongo
    // Play fetches every segment of a video of n segments, one at a time. The player asks for the
    // next segment only when it fits under the buffer target. While a segment downloads, playback
    // drains the buffer; if the buffer runs dry first, the video stalls until the segment arrives.
    func (p Player) Play(tr Trace, ladder []Rendition, n int) Session {
      var s Session
      var samples []float64
      t, buffer, playing, prev := 0.0, 0.0, false, -1
      for i := range n {
        if wait := buffer + p.Seg - p.Target; playing && wait > 0 {
          t += wait // the buffer is full: let playback make room
          buffer -= wait
        }
        rung, est := p.choose(ladder, buffer, samples)
        bits := float64(ladder[rung].Kbps) * 1000 * p.Seg
        req := t
        done := download(tr, t+p.RTT, bits)
        if playing && done-t > buffer {
          s.Stalls = append(s.Stalls, Stall{At: round3(t + buffer), Dur: round3(done - t - buffer)})
          s.RebufferS += done - t - buffer
          buffer = 0
        } else if playing {
          buffer -= done - t
        }
        t = done
        buffer += p.Seg
        if !playing {
          playing, s.StartupS = true, round3(t) // playback starts once one segment is in
        }
        samples = append(samples, bits/1000/(done-req))
        if prev >= 0 && rung != prev {
          s.Switches++
        }
        prev = rung
        s.MeanKbps += float64(ladder[rung].Kbps) / float64(n)
        s.Segments = append(s.Segments, SegmentLog{I: i, Rung: rung, Req: round3(req), Done: round3(done), Est: math.Round(est), Buffer: round3(buffer)})
      }
      s.RebufferS = round3(s.RebufferS)
      s.MeanKbps = math.Round(s.MeanKbps)
      return s
    }
    

    The player picks a rung per segment from measured throughput. In the lab, adapting cut stalls from 15.4 to 1.3 per session at a 24 s buffer.

    L

    Deep dive: delivery, skew and storage cost

    where the money goes
    edge cacheTTLshieldedge hit ratiostore reads/s
    5%1 minno34%1,312
    5%1 dayno35%1,309
    5%1 dayyes35%530
    25%1 dayno62%751
    25%1 dayyes62%0.3

    The edge simulation of the CDN sheet: 20,000 segments with Zipf popularity (alpha 0.8), 2,000 requests a second over 8 edges. The top 1% of segments get 31% of requests. At a 25% edge cache, the shield holds every segment, so the store sees almost nothing.

    videokeepstorage
    New and hotEvery rung, pushed to edges ahead of demandStandard class
    Watched now and thenEvery rung; the CDN fills on demandStandard class
    Long tail, rarely watchedLow rungs; encode high rungs again on first demandInfrequent-access class
    Originals after encodingKeep for re-encodes with a better codecArchive class; restore takes hours
    • Popularity is skewed: a few new videos take most views. Hot segments stay in every edge; the tail lives at the shield and the store.
    • A viral upload sends many edges to the same segment at once. The shield collapses those misses into one store read per segment.
    • Renditions cost 426 MB a video here, more than the 375 MB original. Dropping top rungs of the tail saves the most.

    Segments never change, so the TTL is long and cache size sets the hit ratio. An origin shield cut store reads from 1,309 to 530 a second in the lab.

    M

    Metadata and view counts

    small data, large read rate
    datahow
    Video pageCache the video row and rendition list; invalidate on status change (B4).
    View countINCRBY per video per minute in Redis; a job adds each minute to the daily row.
    Unique viewersA HyperLogLog per video per day: 12 KB, about 1% error (B10).
    Counts for rankingA stream job windows view events by minute (B7).
    • 12,000 views a second as row updates would contend on hot rows. Batching turns them into one write per video per minute.

    Video rows are read on every page view, so a cache in front of Postgres serves them. Views are counted in Redis and flushed each minute.

    N

    Failure cases

    what breaks, and why nothing is lost
    eventwhy it is safesaved by
    Upload drops at 70%List parts, send the rest.Multipart
    Client never completesA sweep and a lifecycle rule delete it after a day.Lifecycle
    Worker dies mid-encodeThe job is visible again after its timeout.Visibility
    Worker dies before its ackThe retry's finish sees done_at set and queues nothing.done_at guard
    Corrupt segment fails every timeAfter 3 attempts the job is buried; the video is marked failed.Dead jobs
    Viral video, cold cachesEdge misses meet at the shield.Shield
    Viewer's bandwidth dropsThe player steps down a rung; the buffer covers the switch.ABR
    O

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1Job per video2+ upload, CDN3+ DAG, queue4+ shield, tiers5+ shardsmore load →
    Transcode tasks per second against this prompt's demand1001k10k100k1MDemand: average: 1,198 tasks per secondDemand: average1,198Demand: 3× peak: 3,594 tasks per secondDemand: 3× peak3,594Lab queue: 1 a claim: 7,667 tasks per secondLab queue: 1 a claim7,667Lab queue: 10 a claim: 40,805 tasks per secondLab queue: 10 a claim40,805tasks per second, log scale
    stepaddit handlesmove up when you see
    1One transcode job per video, uploads through the app.A few uploads an hour. A 2-minute video takes 310.7 s on one worker in the lab's model.Uploads fail on large files; time to playable grows.
    2Direct multipart upload and a CDN in front of the store.Large files from weak networks; egress at the edges.Long videos take too long to process.
    3The segment DAG on a Postgres queue, as on this sheet.About 7,700 claims a second one at a time, 41,000 in batches of 10. Demand peaks near 3,600.Store reads spike on viral videos; storage cost grows.
    4An origin shield and storage classes.One store read per segment per shield; the tail on cheaper storage.The queue nears one primary's limit; viewers far away.
    5Queues sharded by video, workers and caches per region (X2).Each shard runs its own DAGs; edges near viewers.Top of the ladder.

    Demand from panel C. Queue rates are from the queues sheet: 8 clients claim and ack on one Postgres on a shared laptop. Read them as orders of magnitude.

    I start with one transcode job per video and a CDN. I move to a segment DAG on a queue when videos take too long, then shard the queue and add a shield as volume grows.

    P

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    How does live streaming change this?The encoder writes segments as they happen and the playlist has no end tag. Players fetch it again every segment, so latency is a few segments long.B5
    How do you protect paid videos?Sign segment URLs or cookies at the CDN with a short expiry. Add DRM so the key, not the URL, controls playback.B5
    Why a visibility timeout and not a heartbeat?The timeout needs no extra traffic, but it must exceed the longest task. For long tasks, the worker extends its claim as it runs.B6
    How do you retry without a storm?Retry with backoff and jitter, cap the attempts, and bury the poison job. A burst of failures then costs a bounded amount of work.O2
    How do you count unique viewers?A HyperLogLog per video per day merges across servers. It answers within about 1% in 12 KB.B10
    The same file is uploaded twice?Hash the source; a match reuses the existing renditions. Content addressing is the same idea as chunk dedupe.B9
    How do users find videos?Index titles and tags in a search index fed from the video table's changes.B8
    Q

    Drill

    predict, then reveal

    0 of 9 known

    1. Why does the client upload to the object store and not through the API?

    2. A 2 GB upload fails at 70%. What does the client send next?

    3. Why cut the video into segments before encoding?

    4. Why does adding workers stop helping?

    5. A worker finishes an encode and dies before it acks. What happens?

    6. Why must every rung use the same segment boundaries?

    7. How does the player pick a rung?

    8. Why does a bigger buffer target mean fewer stalls?

    9. A new video goes viral. What protects the object store?

    R

    Numbers to say

    measured, derived or cited
    demand
    5.8 uploads/s; 12,000 views/s; 10 Tbit/s egress.
    storage
    About 400 TB a day; 146 PB a year.
    segments
    6 s, keyframe every 2 s (Apple HLS authoring specification).
    DAG, lab
    310.7 s on 1 worker, 45.8 s on 8, 17.8 s on 32; critical path 14.5 s.
    crash, lab
    +5.7 s on 8 workers, +26.7 s on 32: one 30.0 s timeout.
    ABR, lab
    15.4 stalls a session without adapting; 1.3 with it.
    shield, lab
    Store reads 1,309/s to 530/s.

    Transcode times use a cost model; the player uses synthetic traces; the CDN figures use a seeded simulation. Read them as shapes and ratios.