Skip to content

Live streaming

A live streaming service: a streamer points a camera at something, and a few seconds later hundreds of thousands of people see it. The video is made while it is watched, so nothing can be prepared in advance and nothing can wait. This lesson is about that. Video that is uploaded first and watched later is the video platform, and a live stream that is recorded becomes one of those videos afterwards, which is not covered here.

Functional requirements. A streamer connects and sends video. Viewers join a stream and watch it. Several qualities, so that a phone on a weak connection can follow. Chat, clips, ads and recording are real features and are left out.

Non-functional requirements. These are targets chosen for the lesson, not figures from a real service. About 5 seconds from camera to screen. A viewer who joins is watching within 2 seconds. A popular event does not stop the service for the others.

Scale. 1 million viewers at the peak. A stream has 100 viewers on average, but one event has 500,000 viewers on a single stream.

Mental model. Live streaming is two systems with different drivers. Getting the video in and converting it costs in proportion to the number of streams. Getting it out costs in proportion to the number of viewers, and the whole crowd of a stream asks for the same new file at the same moment.

The assumptions are in the table: segments of 2 seconds, so each viewer asks for 0.5 per second; an average quality of 3 Mbit/s; streamers sending 6 Mbit/s; and 2 vCPUs to encode one stream into its qualities in real time.

Quantity Working Result
Viewers at the peak assumption 1 million
Segment requests per second at the peak 1 million × 0.5 500,000
Design load of the lab, a busy period 400,000 viewers × 0.5 200,000 requests per second
Bytes sent at the peak 1 million × 3 Mbit/s 3 Tbit/s
Streams at once 1 million ÷ 100 viewers per stream 10,000
Bytes received 10,000 streams × 6 Mbit/s 60 Gbit/s
Real-time encoding 10,000 streams × 2 vCPUs 20,000 vCPUs, which is 1,250 servers of 16
The big event 500,000 viewers × 0.5 250,000 requests per second for one stream
What the origin sees for that event 500 edge servers × 0.5 250 requests per second, 0.1% of them

Three things follow. The bytes in are small and the bytes out are large, a ratio of 50 to 1 here. The encoding depends on 10,000 streams, not on 1 million viewers, so a single event with 500,000 viewers costs the encoder no more than a stream with 5. And the edge carries a crowd: 250,000 requests per second for one stream, all for the same few files.

The delay from camera to screen, which engineers call glass to glass, is the number that makes live different, so it comes before the design. Four steps are fixed for the lesson: capture, encoding and upload to an ingest server take about 1 second, converting and packaging 0.5 seconds, and the CDN and the download 0.5 seconds. That is 2 seconds. Then come two terms that depend on the unit of delivery. A segment cannot be published until it is complete, so the viewer waits one unit. And the player keeps a buffer: RFC 8216 says that a client should not start playing less than three target durations from the end of the playlist, because that can cause stalls. The buffer is three units.

Unit of delivery Waiting for the unit Buffer of three units Total Requests per second for 400,000 viewers
Segments of 6 seconds 6 s 18 s 26 s 66,667
Segments of 2 seconds 2 s 6 s 10 s 200,000
Parts of 0.5 seconds 0.5 s 1.5 s 4 s 800,000

The fixed 2 seconds are assumptions, and so is the use of the same three-unit buffer for parts. What the table shows is general: the segment length is the largest term, and each step down in latency multiplies the requests. Low-latency HLS, described in Apple’s documentation, publishes a segment in parts as they are encoded, and lets a player ask for the next part before it exists, which the server answers when it is ready. To stay near the 5-second target the lab uses 2-second segments, and the parts case is in the trade-offs.

A streamer pushes video to an ingest address. A viewer asks for a playlist and then for segments.

rtmp://ingest.example/live/KEY (the streamer pushes the video; SRT is the alternative)
GET /live/s42/master.m3u8 the playlist of the quality levels
GET /live/s42/3000k/index.m3u8 the last few segments of one quality
GET /live/s42/3000k/00918.m4s one 2-second segment

The playlist of a live stream has no end. It lists the last few segments and changes every 2 seconds: the player keeps asking for it. The stream key identifies the streamer, and the metadata database holds the stream’s state (offline, live), its title and its viewers’ count. The segments are short-lived: they are kept for a minute or two for the player’s buffer and, if the stream is recorded, copied elsewhere.

Step through the stages and raise the load. A request in the lab is one segment that a viewer downloads; 1 request in 100 stands for the ingest and encoding work of the streams.

A live service: streamers send video in, the service converts it into several qualities as it arrives, and viewers download it in 2-second segments a few seconds later. Step through five 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.

Stage 1 of 5

Start simple: one media server does everything

Design load of this stage: 50 req/s

What we add
One server accepts the streamer’s feed, encodes it in real time into a few qualities, cuts it into 2-second segments and serves them to the viewers who ask. Its 16 vCPUs hold 8 streams at once.
Why: the number that forced it
The design load of 50 requests per second is one stream with 100 viewers. The encoder uses about 13% of its 8 slots, and the server’s network 3% of the 1,538 segments per second that it can send.
What it costs
One machine, one thing to run, and little delay between camera and screen. The price: encoding and serving compete for the same machine, and if it fails every stream and every viewer is cut.
What breaks next
At 10 times the load, 500 requests per second, there are 10 streams to encode and only 8 slots: the encoder is at 125% while the server’s network is at 33%. Two streamers cannot go live.
Design load (50 req/s)
20 ms20 msStreamersand viewersHealthy<1%Media serverHealthy3%Real-timeencoderHealthy13%
20 ms20 msStreamersand viewersHealthy<1%Media serverHealthy3%Real-timeencoderHealthy13%

Each dot stands for many requests. The numbers show the real rate.

No bottleneck: every component has headroom.

Figures at this load

Busiest component
Real-time encoderHealthy13% of its capacity
p95, whole request
38 ms
p99, whole request
44 ms
Requests served
100%50 req/s
Requests failed
0%0 req/s
Bottleneck
none
0 ms
Metrics
ComponentStateUtilisationOffered (req/s)Served (req/s)Rejected (req/s)p50p95p99
Streamers and viewersHealthy<1%505000 ms0 ms0 ms
Media serverHealthy3%505004.5 ms19 ms30 ms
Real-time encoderHealthy13%0.50.501.4 s6 s9.2 s
Traffic
50 req/s
Successful
50 req/s
Error rate
0%
Mean latency
27 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.

All stages at a glance
StageDesign loadDesign load3× the design load10× the design load
1. Start simple: one media server does everything50 req/s50 req/sReal-time encoder: 13%none fail150 req/sReal-time encoder: 38%none fail500 req/sReal-time encoder: 125%none fail
2. Separate ingest and encoding from delivery3K req/s3K req/sOrigin servers: 65%none fail9K req/sOrigin servers: 195%49% fail30K req/sOrigin servers: 650%85% fail
3. Put CDN edge servers in front of the origin30K req/s30K req/sOrigin servers: 65%none fail90K req/sOrigin servers: 195%4.9% fail300K req/sOrigin servers: 300%57% fail
4. Collapse the requests for the same segment60K req/s60K req/sCDN edge servers: 43%none fail180K req/sCDN edge servers: 130%23% fail600K req/sCDN edge servers: 433%77% fail
5. Add edge servers200K req/s200K req/sOrigin servers: 43%none fail600K req/sOrigin servers: 130%0.2% fail2M req/sCDN edge servers: 260%62% 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 2-second segment that a viewer downloads, so each viewer sends 0.5 per second. A stream has 100 viewers on average: it makes 0.5 segments per second for 50 viewer requests per second, so 1 request in 100 (0.01) stands for a piece of a stream being ingested and encoded. These ratios are teaching figures, not measurements of a real service.
  • One server slot stands for 1 Gbit/s of a 10 Gbit/s network card. A 6 Mbit segment (2 seconds at the 3 Mbit/s average quality) takes 6 ms, plus 0.5 ms of fixed work per request: 6.5 ms, which is 1,538 segments a second for a server with 10 slots. The 3 Mbit/s, the 0.5 ms and the 100 viewers per stream are assumptions.
  • Encoding one stream into its ladder of qualities in real time takes 2 vCPUs for as long as the stream lasts. A slot is one such stream, a 16-vCPU server has 8, and one 2-second segment of a stream takes 2 seconds of a slot. The 2 vCPUs are an assumption.
  • The edge answers 90% of the requests itself when it sends one request to the origin for every waiting viewer, and 99% when it sends one per segment (request collapsing). Both ratios are illustrative.
  • Every number (service times, capacities, hit ratios, 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 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 when a big streamer goes live, a viewer joining mid-stream and viewers leaving are not modelled.
  • Ingest and encoding are asynchronous in the model: an overloaded encoder shows as a bottleneck, not as failed viewer requests. In a real service a stream that cannot be encoded fails to start or stutters.
  • The delay from camera to screen is not simulated; the lesson works it out from the segment length. The segments that the transcoders write to the origin (about 5 per stream segment), playlist requests, ads, chat and recording are left out.

Parameter values are illustrative. They are not benchmarks of any real product.

Stage 1, one media server. One server accepts the stream, encodes it in real time, cuts it into segments and serves them. Its 16 vCPUs hold 8 streams. The design load, 50 requests per second, is one stream with 100 viewers: the encoder is at about 13% and the server’s network at 3% of its 1,538 segments per second. At 10 times the load, 500 requests per second, there are 10 streams to encode for 8 slots and the encoder is at 125%. Two streamers cannot go live. The network is at 33%, so the encoder runs out first.

Stage 2, separate the ingest and encoding from delivery. Streamers connect to 160 ingest servers that hold 100 connections each, and every stream gets a slot on a fleet of 2,000 encoder servers, which is 16,000 slots, room for 16,000 streams. The packaged segments go to a pool of three origin servers, which only serve viewers. At 3,000 requests per second the origin is at 65%. At 3 times the load, 9,000 requests per second, it is asked for 195% of its 4,615 segments per second and nearly half of the requests fail.

Stage 3, an edge in front of the origin. CDN edge servers answer the viewers, and only a miss goes to the origin. The lab takes 90% of the requests to be answered at the edge, and 10% to miss, for a reason that is specific to live and is the subject of the next section. The origin goes from 9,000 requests per second to 900, about 20% of its capacity. At 3 times the load, 90,000 requests per second, 10% is 9,000 and the origin is again at 195%; one request in twenty fails.

Stage 4, collapse the requests. An edge server that is asked for a segment it does not have sends one request to the origin and keeps the other viewers waiting. With 99% answered at the edge, 90,000 requests per second leave 900 for the origin. At 3 times the stage’s load, 180,000 requests per second, the origin is at 30%, and the 90 edge servers are asked for 130% of what they can send, 138,462 segments per second: 23% of the requests fail.

Stage 5, more edge servers. The edge grows from 90 to 500 servers, which can send 769,231 segments per second. The stage’s 200,000 requests per second use 26% of that. At 3 times the load, 600,000 requests per second, the edge is at 78%, but even 1% of misses is 6,000 requests per second, and the three origin servers are at 130% of 4,615. A tier of shield caches between the edge and the origin, one per region, takes it from there.

A recorded video is old: when a viewer asks for a segment, some other viewer probably asked an hour ago, and the edge has it. A live segment is new. It is published at one moment, and every viewer of the stream asks for it within the next second, because they all play the same point in time. At an edge server the first request finds nothing, goes to the origin, and the origin takes some tens of milliseconds to answer. During that time the next hundred requests also find nothing. Without a defence every one of them is sent to the origin: the cache is hit by a crowd arriving at the same moment on a key that does not exist yet. It is the cache stampede of the caching module, happening at every edge server, on every segment, every 2 seconds.

Request collapsing is the defence: the edge sends one request for the segment and holds the others until the answer arrives, then answers them all from it. In nginx the proxy_cache_lock directive does this: only one request at a time is allowed to populate a new cache element, and the others wait. The origin then sees one request per edge server and segment, whatever the number of viewers. For the big event: 500,000 viewers is 250,000 requests per second at the edge, and with 500 edge servers the origin sees 500 × 0.5 = 250 per second. That is the 0.1% in the estimate.

Collapsing has a cost, and the stage 4 text says it: the waiting viewers are as slow as the origin, and if its answer fails they all fail together. Facebook’s account of its live video describes the same shape, with caches between the viewers and the origin so that the origin is asked rarely.

The streamer’s encoder pushes the video over a connection that stays open for as long as the stream lasts. RTMP, over TCP, is the older and still common choice. SRT, a newer protocol described in an IETF draft, runs over UDP and retransmits lost packets within a latency budget that is set in advance, so that a bad network costs a little delay and not a stall. An ingest server near the streamer shortens the path on which the connection is fragile.

The encoder fleet differs from the on-demand pipeline in one respect that decides its design: it cannot queue. A video that is uploaded can wait in a queue for a minute with no harm. A live stream that waits for a minute is a stream that is a minute late, and the viewers have already left. So each stream is given a slot for as long as it lasts, the fleet must exist before the peak number of streams arrives, and capacity is sized by the number of streams: 10,000 streams are 10,000 slots whether they have 5 viewers or 500,000. The lab’s figures show it: at stage 2 the same fleet is at 0.4% of its capacity at the stage’s load and 75% of it at stage 5’s 3 times.

The stream it carries is cut, because the slot was its only copy of the encoding. The ingest server holds the connection and can be told to send the stream to another slot, so what the viewers see is a gap of a few seconds, during which their buffer drains: with 2-second segments and a buffer of three, they have about 6 seconds before the picture freezes. Fast failure detection and a hand-over that takes less than the buffer are what turns a failure into a hiccup. Keeping a second encoder running for the most watched streams, at twice the cost, removes the gap.

What happens if the streamer’s connection drops

Section titled “What happens if the streamer’s connection drops”

The ingest server stops receiving video. The viewers still have what they buffered, then the playlist stops growing. A well-behaved service keeps the stream open for a short while, shows a message or a placeholder, and resumes when the streamer reconnects; the playlist marks the break so that the player knows the timeline has a discontinuity. The streamer’s encoder reconnects on its own, and SRT recovers from short losses without the viewers noticing.

The edge servers keep the last segments they served, and the viewers have their buffers, so the first few seconds are covered. After that the playlists stop changing and the players stall. An edge that is allowed to serve a stale playlist for a few seconds when the origin does not answer gives the origin time to come back, but stale means late, which is the one thing a live stream cannot afford for long. Several origin servers in separate failure domains, and an edge that can try another, are the real answer.

Decision What you gain What you pay When to choose otherwise
Short segments or parts Less delay between camera and screen: 4 seconds instead of 26 Many more requests, and a smaller buffer, so a slow moment on the viewer’s network stalls the player sooner A stream where smoothness matters more than delay, such as a concert; use long segments
An encoder slot for each stream, kept for its whole life No queue and no delay in the encoding Capacity paid for before the peak, and a failure cuts the stream A recording that no one watches live, which can wait in a queue
Request collapsing at the edge The origin sees one request per edge and segment, not one per viewer Waiting viewers are as slow as the origin, and fail together if it fails A cache that is already warm because the content is old, where collapsing does nothing
More edge servers Viewers closer to a server, and the crowd of one event shared among many More servers to pay for, and more edge servers means more requests to the origin A small audience in one region
A shield tier of caches between the edge and the origin The origin sees the misses of a region, not of every edge server One more hop of delay and one more thing to run When the origin is already well below its capacity

An interviewer asks for this system in 45 minutes. A good answer starts with the latency budget and the split between the streams and the viewers, keeps ingest and delivery apart, explains why live cannot queue and why the edge needs collapsing, and says what low latency costs. Write your answer before you read the strong one.

Interview question

Writing and reviewing an answer needs JavaScript.

The interviewer asks

Design a live streaming service where streamers broadcast and a popular stream may have hundreds of thousands of viewers who should see it a few seconds after it happens.

Assume 1 million viewers at the peak, 100 viewers per stream on average, and one event with 500,000 viewers on a single stream. The target is about 5 seconds from camera to screen.

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

  • 1 million viewers at 0.5 requests per second each make 500,000 segment requests per second and 3 Tbit/s; with 100 viewers per stream there are 10,000 streams to ingest and encode, 20,000 vCPUs.
  • The latency from camera to screen is about 2 seconds of fixed steps plus four units of delivery: 26 seconds with 6-second segments, 10 with 2-second segments and 4 with parts of 0.5 seconds, which cost four times the requests.
  • One server runs out of encoder slots first: 10 streams against 8 at 10 times the load. Separate ingest and encoding scale with the number of streams, and the origin pool then limits delivery, at 195% of 4,615 segments per second at 3 times the load.
  • A live segment is new, so the first requests at every edge miss. With 90% answered at the edge the origin still gets 9,000 requests per second at 90,000; collapsing the requests brings it to 900.
  • Live cannot queue: each stream holds a slot, a failed encoder cuts the stream, and the viewers’ buffer of about 6 seconds is the time available to recover.
  • At 3 times the last stage’s load, 600,000 requests per second, the edge is at 78% and the origin pool, receiving 1% of the requests, is at 130%.

Next: Global messaging, which takes chat to many regions.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.