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.
- 1Bytes go straight from the client to object storage with presigned multipart URLs. A dropped upload resumes from the parts already stored.
- 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.
- 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.
- 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.
"Design a video platform: upload, transcode, and stream to millions of viewers on any device."
| question | answer 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.
| 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-functional | target |
|---|---|
| Upload resume | Resend at most one part |
| Upload to playable | < 5 min for a 5-min video |
| Start of playback | p95 < 2 s |
| Stalls | Rare; prefer a lower rung to a stall |
| Durability of uploads | Never lose an acked upload |
An upload must survive a dropped connection, and playback must start fast and rarely stall.
| quantity | arithmetic | result |
|---|---|---|
| Uploads | 500 k ÷ 86,400 | ≈ 5.8/s; 3× peak ≈ 17/s |
| Ingest | 500 k × 300 s × 10 Mbit/s ÷ 86,400 | ≈ 17 Gbit/s |
| Originals | 300 s × 10 Mbit/s ÷ 8 = 375 MB × 500 k | ≈ 190 TB a day |
| Renditions | 300 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 tasks | 5.8/s × 207 tasks a video | ≈ 1,200/s; peak ≈ 3,600/s |
| Transcode workers | 500 k × 300 s × 2.6 worker-s per source s ÷ 86,400 | ≈ 4,500 busy on average |
| Views | 1 B ÷ 86,400 | ≈ 12,000/s |
| Concurrent streams | 1 B × 300 s ÷ 86,400 | ≈ 3.5 M |
| Egress | 3.5 M × 2.9 Mbit/s mean rung | ≈ 10 Tbit/s; peak ≈ 31 |
| Segment requests | 3.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.
| call | body | success | errors |
|---|---|---|---|
| POST /v1/videos + Idempotency-Key | title, size, content type | 201 video id, upload id, part URLs | 400, 413 |
| PUT <presigned part URL> | part bytes, SHA-256 | 200 + ETag (to the store) | 400 bad checksum, 403 expired |
| GET /v1/uploads/{id}/parts | none | 200 part numbers held | 404 |
| POST /v1/videos/{id}/complete | part list | 202 processing | 409 part missing |
| GET /v1/videos/{id} | none | 200 status, master URL, thumbnails | 404 |
| GET cdn/v/{id}/master.m3u8, then segments | none | 200, cached for a long time | 403 bad signature |
| POST /v1/videos/{id}/views | session id | 204 | 429 |
- 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.
| object key | holds | cache |
|---|---|---|
| src/{video} | The original upload | Never served |
| v/{video}/master.m3u8 | The rung list | Minutes |
| v/{video}/{rung}/index.m3u8 | One rung's segment list | Long; it never changes |
| v/{video}/{rung}/seg007.ts | Six seconds of video | Long; it never changes |
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)
);- 1The video moves forward only. Playback reads ready videos.
- 2Ready tasks are queued longest first, so a long encode does not start last.
- 3A counter of parents not yet done. The task is queued when it reaches 0.
- 4Set once. A retried finish sees it set and does nothing.
- 5Edges name real tasks of the same video.
- 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.
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.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Object store | Multipart upload; list parts | Parts in parallel and in any order; resume from what is stored. | Backups, large exports |
| Object store | Presigned URLs | The client sends bytes straight to the store, only to the key the API chose. | Downloads, avatars |
| Object store | Lifecycle rules, storage classes | Abort stale uploads; move cold originals to a cheaper class. | Log retention |
| Postgres | FOR UPDATE SKIP LOCKED, visibility time | The job queue: one worker per job; a dead worker's job comes back. | Email, webhooks |
| Postgres | Data-modifying CTEs | Finish a task, release its children and queue the ready ones in one statement. | Workflows |
| Postgres | UPDATE ... WHERE done_at IS NULL | A retried finish changes nothing and queues nothing. | Idempotent handlers |
| Redis | INCRBY | View counts per video per minute, flushed to Postgres. | Rate limits, likes |
| Workers | Stateless processes | Any worker runs any task; add workers for more parallel encodes. | Image resizing |
| ffmpeg | Forced keyframes, segmenting, HLS output | Every rung cut at the same times, so the player can switch. | Thumbnails, audio |
| HLS, DASH | A manifest of rungs and segments | One URL that every device understands; the player chooses. | Live video |
| CDN | Edge cache, origin shield, signed URLs | Serves 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.
| method | status | why |
|---|---|---|
| Upload through the API servers | Not approved | Every byte crosses the app tier; a restart loses the upload. |
| One presigned PUT | Small files | Simple, but a drop at 90% starts over. |
| Presigned multipart upload | Approved | Parts in parallel; resume sends only missing parts. |
| A resumable protocol (tus) | Own upload service | Resume 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.
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- 1Nothing is visible under the key until complete. A half upload never looks like a video.
- 2Signed for one key, one method and an expiry. The client cannot write anywhere else.
- 3The store is the record of progress, so the client needs no local state to resume.
- 4Complete joins the parts in order. Readers see the whole file or nothing.
Tested source Go: multipart upload
// 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.
| method | status | why |
|---|---|---|
| One job per video on one machine | Short videos | 310.7 s for 2 minutes of video; a crash redoes all of it. |
| One job per rung | Few workers | 4 jobs in parallel; 1080p still runs alone and longest. |
| A DAG of segment jobs on a queue | Approved | Hundreds of jobs in parallel; a crash redoes one segment. |
| Run the DAG from memory in one coordinator | Not approved | The coordinator dies and the state of every video is gone. |
| segment length | tasks | 1 worker | 64 workers | why |
|---|---|---|---|---|
| 2 s | 247 | 472.7 s | 15.1 s | Each task pays the start cost. |
| 6 s | 87 | 310.7 s | 14.5 s | Apple's recommended length. |
| 12 s | 47 | 270.2 s | 20.5 s | The longest segment sets the floor. |
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- 1A stream copy at keyframes is fast. Each segment then decodes on its own.
- 2Segments times rungs: 80 jobs for a 2-minute video at 6 s segments.
- 3A playlist lists every segment, so it waits for all of them.
Tested source Go: build the DAG
// 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)
}
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- 1The claim hides the job. The timeout must be longer than the longest task, or a slow task runs twice.
- 2A repeated attempt overwrites the same object; nothing is duplicated.
- 3A task that already finished changes no row, so its children are not released twice.
- 4Long encodes start early, so they do not finish last.
- 5A corrupt source fails every time. Stop after 3 tries and tell the owner.
Tested source Go: the worker loop · SQL: finish a task
// 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
}
}
}
}
-- 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.
- encode one segment to one rung
- split, thumbnails, playlists, publish
- attempt lost in a crash
- retry after the visibility timeout
| segment | tasks | 1 w | 2 w | 4 w | 8 w | 16 w | 32 w | 64 w | critical path |
|---|---|---|---|---|---|---|---|---|---|
| 2 s | 247 | 472.7 | 239.9 | 123.2 | 65.4 | 36.8 | 22.4 | 15.1 | 10.5 |
| 6 s | 87 | 310.7 | 159 | 83.3 | 45.8 | 27.3 | 17.8 | 14.5 | 14.5 |
| 12 s | 47 | 270.2 | 138.8 | 73 | 39.8 | 24.5 | 20.5 | 20.5 | 20.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.
#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- 1Bits per second of this rung. The player compares it with what it measures.
- 2Each rung has its own media playlist of segments.
#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- 1Apple recommends 6 s segments and a keyframe every 2 s.
- 2Segment 1 covers the same 6 s in every rung, so a switch is seamless.
- 3A finished video. A live playlist has no end tag and is fetched again.
| policy | status | stalls per session, 24 s buffer |
|---|---|---|
| One fixed bitrate | Not approved | 15.4 |
| Throughput: highest rung under 80% of measured | Approved | 1.3; mean 2.9 Mbit/s |
| Buffer level picks the rung | Deep buffer | 5.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.
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- 1One fast segment cannot lift a harmonic mean far, so the player is slow to step up.
- 2A safety share: the rung must fit with room to spare.
- 3The buffer target. A bigger target rides out longer dips but costs bytes if the viewer leaves.
- 4The picture stops and the viewer sees a spinner until the segment arrives.
Tested source Go: choose a rung · Go: play a session
// 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))
}
// 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.
| edge cache | TTL | shield | edge hit ratio | store reads/s |
|---|---|---|---|---|
| 5% | 1 min | no | 34% | 1,312 |
| 5% | 1 day | no | 35% | 1,309 |
| 5% | 1 day | yes | 35% | 530 |
| 25% | 1 day | no | 62% | 751 |
| 25% | 1 day | yes | 62% | 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.
| video | keep | storage |
|---|---|---|
| New and hot | Every rung, pushed to edges ahead of demand | Standard class |
| Watched now and then | Every rung; the CDN fills on demand | Standard class |
| Long tail, rarely watched | Low rungs; encode high rungs again on first demand | Infrequent-access class |
| Originals after encoding | Keep for re-encodes with a better codec | Archive 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.
| data | how |
|---|---|
| Video page | Cache the video row and rendition list; invalidate on status change (B4). |
| View count | INCRBY per video per minute in Redis; a job adds each minute to the daily row. |
| Unique viewers | A HyperLogLog per video per day: 12 KB, about 1% error (B10). |
| Counts for ranking | A 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.
| event | why it is safe | saved by |
|---|---|---|
| Upload drops at 70% | List parts, send the rest. | Multipart |
| Client never completes | A sweep and a lifecycle rule delete it after a day. | Lifecycle |
| Worker dies mid-encode | The job is visible again after its timeout. | Visibility |
| Worker dies before its ack | The retry's finish sees done_at set and queues nothing. | done_at guard |
| Corrupt segment fails every time | After 3 attempts the job is buried; the video is marked failed. | Dead jobs |
| Viral video, cold caches | Edge misses meet at the shield. | Shield |
| Viewer's bandwidth drops | The player steps down a rung; the buffer covers the switch. | ABR |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One 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. |
| 2 | Direct 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. |
| 3 | The 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. |
| 4 | An 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. |
| 5 | Queues 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.
| question | answer | deeper |
|---|---|---|
| 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 |
0 of 9 known
Why does the client upload to the object store and not through the API?
A 2 GB upload fails at 70%. What does the client send next?
Why cut the video into segments before encoding?
Why does adding workers stop helping?
A worker finishes an encode and dies before it acks. What happens?
Why must every rung use the same segment boundaries?
How does the player pick a rung?
Why does a bigger buffer target mean fewer stalls?
A new video goes viral. What protects the object store?
- 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.