Video platform
What we are building
Section titled “What we are building”An on-demand video platform: people upload a video once, and anyone can watch it later, at any time, on a phone or a laptop, on a fast or a slow connection. This lesson is about video that already exists. A video that is being filmed as it is watched is a different problem, with its own numbers, and it has its own case study: live streaming.
Functional requirements. Upload a video. See it listed once it is ready. Play it from any point. Playback adapts to the viewer’s connection. Search, recommendations, comments and ads are real features and are left out.
Non-functional requirements. These are targets chosen for the lesson, not figures from a real service. Playback starts in under 2 seconds and does not stall on a normal connection. A video is watchable within a few minutes of the upload. An uploaded video is never lost.
Scale. 10 million viewers a day, 5 videos each. One video is uploaded for every 200 plays. The average video lasts 6 minutes and a viewer watches 5 of them.
Mental model. A video platform is a machine for sending bytes. Each upload is converted once, stored for a long time, and then read many thousands of times. The conversion is heavy per video, and the reading is heavy in total.
Estimate before you design
Section titled “Estimate before you design”The bandwidth lesson turns a number of users into a rate of bytes, and Little’s law says how many viewers are on the service at once. Here is the arithmetic. The assumptions are in the table.
| Quantity | Working | Result |
|---|---|---|
| Plays per day | 10 million viewers × 5 | 50 million |
| Plays per second | 50 million ÷ 86,400 | about 580 |
| Viewers at once | 580 plays per second × 300 seconds of viewing | about 174,000 |
| Segment requests per second | 174,000 viewers ÷ one segment every 4 seconds | about 43,000, which the lab rounds up to a design load of 50,000 |
| Peak, assuming 3 times the average | 43,000 × 3 | about 130,000 requests per second |
| Bytes sent per second | 174,000 viewers × 3 Mbit/s | about 520 Gbit/s, and about 1.6 Tbit/s at the peak |
| Bytes sent per day | 50 million plays × 112.5 MB | about 5.6 PB |
| Uploads | 50 million ÷ 200 | 250,000 a day, about 3 a second |
| Storage for one video | 450 MB of source plus 527 MB of qualities | about 1 GB |
| Storage for all uploads | 250,000 × 1 GB | 250 TB a day, about 91 PB a year |
| Transcoding work | 250,000 uploads × 360 seconds ÷ 86,400 | about 1,040 slots busy at all times, 65 servers of 16 slots |
The assumptions behind these rows are all in this list. A viewer watches 5 minutes of a 6-minute video, in segments of 4 seconds (75 of them). The uploaded file is 10 Mbit/s, so 360 seconds make 450 MB. The video is converted into five qualities of 0.4, 0.8, 1.5, 3 and 6 Mbit/s, which together are 11.7 Mbit/s and make 527 MB for 360 seconds. The viewers’ average quality is 3 Mbit/s. A transcoding worker needs one second for each second of video. The factor 3 for the peak is an assumption too.
Three things follow, whatever the exact figures. The load is bytes sent: 520 Gbit/s is more than any one machine or any one data centre link is built for. The uploads are rare, 3 a second, but each one is heavy: 360 seconds of computing and 1 GB. And storage grows without end, 250 TB a day, so it is an object store that is needed and not a database. The stages below follow those three facts.
The API and the data
Section titled “The API and the data”The calls are few. The upload is the only one that carries a large body, and it does not go through the application servers.
POST /videos {"title": "My trip", "size": 450000000}201 Created {"videoId": "v123", "uploadUrl": "https://store.example/…signed…", "partSize": 8388608}
GET /videos/v123 → {"state": "ready", "manifest": "https://cdn.example/v123/master.m3u8"}GET /v123/3000k/00042.m4s (one 4-second segment, from the CDN)The metadata database holds one row per video: its owner, title, state (uploaded, processing, ready, failed) and the location of its manifest. A manifest is a small text file that lists the qualities and, for each one, its segments. In HTTP Live Streaming it is a playlist, defined in RFC 8216; the player downloads the playlist first and then the segments it points to. The segments themselves are files in object storage, named by video, quality and number, and never changed after they are written.
Six stages, each forced by a number
Section titled “Six stages, each forced by a number”Step through the stages and raise the load. Every stage runs at its own design load and then at 3 times and 10 times that load, and the engine says which component limits it. A request in the lab is one segment that a viewer downloads, and the lab’s notes say how the other work is counted.
An on-demand video service: people upload videos, the service converts each one into several qualities, and viewers watch them in 4-second segments. Step through six stages, each adding the one thing the previous stage’s numbers called for, and raise the load to see what breaks. A request here is one segment that a viewer downloads.
Start simple: one server stores and serves the files
Design load of this stage: 30 req/s
- What we add
- One app server keeps each uploaded file on its own disk and sends it to viewers, 4 seconds (one segment) at a time. A database holds the titles, owners and file names. There is no conversion: viewers get the file that was uploaded, at 10 Mbit/s.
- Why: the number that forced it
- At 30 requests per second, which is about 120 viewers watching at once, the server’s 10 Gbit/s link is at 12% of the 250 segments of 40 Mbit that it can send each second. Nothing else is close to its limit.
- What it costs
- Cheap and easy to run, and enough for a club or a school. The price: one disk holds the only copy of every video, a phone on a slow connection stalls on a 10 Mbit/s file, and all the viewers share one network link.
- What breaks next
- At 10 times the load, 300 requests per second or about 1,200 viewers, the link is asked for 120% of what it can send and a sixth of the requests fail.
Each dot stands for many requests. The numbers show the real rate.
No bottleneck: every component has headroom.
Figures at this load
- Busiest component
- App serversHealthy12% of its capacity
- p95, whole request
- 137 ms
- p99, whole request
- 189 ms
- Requests served
- 100%30 req/s
- Requests failed
- 0%0 req/s
- Bottleneck
- none
| Component | State | Utilisation | Offered (req/s) | Served (req/s) | Rejected (req/s) | p50 | p95 | p99 |
|---|---|---|---|---|---|---|---|---|
| Viewers and uploaders | Healthy | <1% | 30 | 30 | 0 | 0 ms | 0 ms | 0 ms |
| App servers | Healthy | 12% | 30 | 30 | 0 | 28 ms | 120 ms | 184 ms |
| Metadata database | Healthy | <1% | 0.4 | 0.4 | 0 | 3.5 ms | 15 ms | 23 ms |
- Traffic
- 30 req/s
- Successful
- 30 req/s
- Error rate
- 0%
- Mean latency
- 60 ms
All stages at a glance
Each cell is the engine’s steady state for that stage at that load: the busiest component, how much of its capacity it uses, and the share of requests that fail.
| Stage | Design load | Design load | 3× the design load | 10× the design load |
|---|---|---|---|---|
| 1. Start simple: one server stores and serves the files | 30 req/s | 30 req/sApp servers: 12%none fail | 90 req/sApp servers: 36%none fail | 300 req/sApp servers: 120%17% fail |
| 2. Move the files to object storage | 1K req/s | 1K req/sObject storage: 18%none fail | 3K req/sObject storage: 55%none fail | 10K req/sObject storage: 182%45% fail |
| 3. Put a CDN in front of the store | 5K req/s | 5K req/sCDN edge servers: 40%none fail | 15K req/sCDN edge servers: 120%17% fail | 50K req/sCDN edge servers: 400%75% fail |
| 4. Convert every upload into a ladder of qualities | 10K req/s | 10K req/sTranscoding workers: 38%none fail | 30K req/sTranscoding workers: 113%none fail | 100K req/sTranscoding workers: 377%58% fail |
| 5. Scale the workers with the queue | 10K req/s | 10K req/sCDN edge servers: 24%none fail | 30K req/sCDN edge servers: 72%none fail | 100K req/sCDN edge servers: 240%58% fail |
| 6. Add edge servers, close to the viewers | 50K req/s | 50K req/sObject storage: 45%none fail | 150K req/sObject storage: 136%1.3% fail | 500K req/sCDN edge servers: 300%67% fail |
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Requests arrive at random, as a Poisson process, at a constant average rate.
- Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
- Service times are random with the stated mean; by default they are exponentially distributed.
- Each node is analysed separately, with the traffic it receives treated as Poisson.
- A request is one 4-second segment that a viewer downloads. A viewer watches 5 minutes of a video, which is 75 segments, and needs one metadata request per play, so about 1 request in 75 (0.0134, upload requests included) also reaches the app servers and the database. For every 200 plays one video is uploaded, so 1 request in 15,000 starts a transcoding job. These ratios are teaching figures, not measurements of a real service.
- Bytes are modelled as time on a network link. One server slot stands for 1 Gbit/s of a 10 Gbit/s network card, so a 40 Mbit segment (4 seconds of a 10 Mbit/s uploaded file) occupies a slot for 40 ms, and a 12 Mbit segment (4 seconds at the 3 Mbit/s average of the quality ladder) for 12 ms. The 10 Mbit/s file, the ladder of 0.4, 0.8, 1.5, 3 and 6 Mbit/s and its 3 Mbit/s average are assumptions.
- A transcoding job takes one second of a worker slot for each second of video, so 360 seconds for the average upload of 6 minutes. Both the length and the one-to-one ratio are assumptions. The workers’ requests are uploads, not segments.
- The object store answers at most 5,500 read requests per second, the least that Amazon S3 documents for one prefix; a real store goes further with more prefixes. The CDN hit ratio of 95% is illustrative.
- Every number (service times, capacities, the hit ratio, the design loads) is illustrative model output, chosen to make the limit of each stage visible. None of them is a benchmark of a real server, store or CDN.
Simplifications
- Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
- Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
- A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
- A request calls its dependencies one after another. Parallel fan-out is not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
- Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
- Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
- A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
- A caller’s timeout counts the mean time its dependencies take, not their full distribution.
- Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
- Each stage is shown in a steady state: the load is held and the engine says where queues build. A burst, a newly popular video (a cold cache) and the time a job waits in the queue are not modelled.
- The workers’ calls are asynchronous in the model: when the fleet is too small the viewers see no error, the queue of jobs grows and videos take longer to appear. The lab shows that as a bottleneck, not as failed requests.
- The uploads themselves (resumable, in parts, straight to the store), the reading of the source and the writing of the renditions (about 540 store requests per upload) are left out.
- Bytes are time on a link, as described above; a real server is also limited by CPU, memory and disk. Durability, storage cost, recommendations, comments and abuse handling are not modelled.
Parameter values are illustrative. They are not benchmarks of any real product.
Stage 1, one server. One app server keeps each uploaded file on its disk and sends it to the viewers, with a database for titles. At 30 requests per second, about 120 viewers, its 10 Gbit/s link is at 12% of the 250 segments of 40 Mbit it can send each second. At 10 times that load the link is asked for 120% and a sixth of the requests fail. The forcing number is the bytes: a segment of 4 seconds of a 10 Mbit/s file is 40 Mbit, and 250 of them a second fill the link.
Stage 2, object storage. The files move into object storage and the player downloads from it directly, with a signed, time-limited link given out by the app servers. One prefix of the store answers at least 5,500 reads per second, according to the Amazon S3 documentation, and at 1,000 requests per second it is at 18% of that. At 10 times the load it is asked for 182% and 45% of the requests fail. The video no longer limits the app servers, and the store now holds several copies, but every viewer still reads from the same place.
Stage 3, a CDN. Edge servers keep copies of the segments. A segment never changes, so a copy needs no invalidation, and with 95% of the requests answered at the edge only 500 per second of the 10,000 reach the store: 9% of its capacity. At 3 times the load, 15,000 requests per second of 40 Mbit segments are 600 Gbit/s, and the 50 edge servers can send 500 Gbit/s. They are at 120%.
Stage 4, a transcoding pipeline. Each upload goes onto a queue and a fleet of workers converts it into the five qualities. The player picks a quality for each segment, so a segment averages 12 Mbit instead of 40, and the same 50 edge servers can send 41,667 segments a second. At the stage’s 10,000 requests per second they are at 24%. The new component has its own limit: 40 workers of 16 slots make 640 slots, and each upload takes 360 seconds of a slot, so they finish 1.78 uploads per second. At 3 times the load there are 2.01 uploads per second and the workers are at 113%. The viewers see no error: the queue grows, and new videos take longer and longer to appear.
Stage 5, workers that follow the queue. The number of workers goes up and down with the length of the queue, up to 300, which is 4,800 slots and 13.3 uploads per second. The same load now uses 15% of them. The edge is next: at 10 times the load, 100,000 requests per second ask 240% of the 41,667 segments the 50 servers can send, and 58% of the requests fail.
Stage 6, more edge servers. The CDN grows to 200 servers, which send 2 Tbit/s, or 166,667 segments a second; the stage’s 50,000 requests per second use 30% of that. At 3 times the load the edge is at 90%, but the 5% of misses are 7,500 requests per second, and the store is asked for 136% of its 5,500. It is the bottleneck again and 1.3% of the requests fail. A shared cache tier in front of the store, or more prefixes, takes it from there.
The transcoding pipeline
Section titled “The transcoding pipeline”A video file is made for storing, not for streaming. The pipeline changes it in four steps.
- Split. The source is cut at keyframes into chunks of a few seconds, so that each chunk can be converted alone. For a 360-second video, 36 chunks of 10 seconds on 36 slots take about 10 seconds instead of 360. Facebook’s SVE paper describes a system that splits a video and processes the pieces in parallel for this reason.
- Convert. Each chunk is encoded into each rung of the ladder of qualities. This is the expensive step, and it is why the workers need one second of a slot for each second of video in the lab.
- Package. The converted chunks become segments of 4 seconds, and a manifest lists them for every quality.
- Publish. When every quality of every segment exists, the video’s state in the metadata database changes to
ready. Not before.
The queue is what lets the pipeline absorb a burst of uploads: they wait, and the worker fleet grows with the wait. The workers are the one part of the system whose capacity must follow the number of uploads and not the number of viewers.
Adaptive bitrate
Section titled “Adaptive bitrate”The ladder exists so that a single video can be watched by a phone on a weak connection and by a television on a fast one. The player downloads the manifest, then picks a quality for each segment and can change it at the next segment. A simple rule picks the highest quality whose bitrate is below the download speed it has just measured. Huang and colleagues, in a paper on a large streaming service, argue for picking the quality from the amount of video already in the player’s buffer instead, because a throughput estimate is noisy. Either way the effect is the same: a connection that slows down goes down the ladder and keeps playing, where a single-quality file would stall.
The ladder has a second effect that shows in the lab. A viewer on average downloads 3 Mbit/s and not 10, so each segment the CDN sends is 12 Mbit and not 40, and the same servers send 3.3 times as many segments. Adaptive bitrate is an experience feature and a capacity feature.
What happens if a worker dies halfway through a video
Section titled “What happens if a worker dies halfway through a video”A job takes minutes, and workers do disappear, especially when they run on cheap machines that can be taken back. The queue delivers a job at least once: if the worker does not acknowledge it before a timeout, the job is delivered again to another worker, as the messaging module explains. That makes it possible for two workers to convert the same video, so each conversion has to be safe to repeat. Two things make it so. Every output is written under a name that depends only on the video, the quality and the segment number, so a second worker overwrites a file with the same bytes. And the video becomes ready only at the end, in a single update, which is the idempotency idea applied to a job: running it twice leaves the same state as running it once. A job that fails again and again goes to a dead-letter queue, and the video is marked failed instead of being retried for ever.
What happens if a video becomes popular at once
Section titled “What happens if a video becomes popular at once”A new video is in no edge server’s cache, so its first viewers all miss. For a rarely watched video this is rare and cheap. For one that is shared everywhere at the same time, every edge server asks the store for the same segments together. With the stage 6 figures the store has 5,500 reads a second and the misses at 3 times the load are 7,500, so a burst of new popular content is exactly what fills the store’s limit first. This is a cache stampede at the scale of a CDN. The defences are those of that lesson: one request per segment for all the viewers waiting at an edge, a shared cache tier between the edge and the store, and warming the edge with a video that is known to be coming.
Trade-offs
Section titled “Trade-offs”| Decision | What you gain | What you pay | When to choose otherwise |
|---|---|---|---|
| Uploads go straight to object storage with a signed link | The app servers never carry video, and a large upload can be resumed in parts | A link to issue and expire for each upload, and no chance to inspect the bytes on the way in | A small service with short clips, where the extra moving parts cost more than carrying the bytes |
| A ladder of five qualities | Slow connections keep playing, and the CDN sends 12 Mbit segments instead of 40 | Compute for every upload and about twice the storage | A product with one device and one network, where one quality is enough |
| Workers that follow the queue | Capacity for a burst of uploads without paying for it all day | Capacity arrives minutes late, and the jobs must survive a worker being taken away | Steady, predictable uploads, where a fixed fleet is simpler and cheaper |
| Short segments (4 seconds here) | The player can change quality quickly, and a seek starts soon | More requests and more files: half the length is twice the requests | Content that is watched from start to end on a stable network, where longer segments save requests |
| Servers in more places | Bytes leave closer to the viewer and the network cost falls | More servers to pay for and a cache that is hit less often per server | A small audience in one region |
Defend your design
Section titled “Defend your design”An interviewer asks for this system in 45 minutes. A good answer begins with the arithmetic (the load is bytes sent, the uploads are few and heavy), puts uploads on a separate path from playback, converts asynchronously, serves through a CDN, and says aloud what each choice costs. Write your answer before you read the strong one.
Interview question
Writing and reviewing an answer needs JavaScript.
The interviewer asks
Design a video platform where people upload videos and others watch them on demand, on phones and on laptops, on fast and slow connections.
Assume 10 million viewers a day who watch 5 videos each, 250,000 uploads a day, and an average video of 6 minutes. You have 45 minutes.
Write your answer first. The strong answer unlocks once you have written a real attempt.
0 of 120 characters written to unlock the strong answer
- 10 million viewers a day watching 5 videos make 580 plays per second, about 174,000 viewers at once and about 520 Gbit/s sent. Uploads are about 3 a second but heavy: 1 GB stored and 360 seconds of computing each.
- One server fills its 10 Gbit/s link at 250 segments of 40 Mbit per second. Object storage answers at least 5,500 reads per second per prefix, and a CDN with a 95% hit ratio cuts the store’s load to 5%.
- A ladder of qualities with adaptive bitrate takes the average segment from 40 to 12 Mbit, so 50 edge servers send 41,667 segments a second instead of 12,500.
- Transcoding is a queue and workers: 40 workers finish 1.78 uploads per second and are at 113% at 2.01. Workers that follow the queue, up to 300, finish 13.3.
- A job must be safe to run twice: outputs have names that do not change, and the video becomes
readyin one final update. - At 3 times the load the last stage’s edge is at 90%, but the misses ask the store for 136% of its limit.
Next: Live streaming, where the video is being made while it is watched.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.