Distributed Systems ยท Chapter 04

A stadium to a billion screens

The 2018 FIFA final drew a combined 1.12 billion live viewers. This chapter follows one frame of that stream from the camera to the phone โ€” encoding, edge caching, real-time validation, Kafka's speed tricks, storage math, and how you keep the whole thing standing on game day when traffic climbs by millions of hits per minute.

๐Ÿงญ
How to read this

This is the first full system-design chapter โ€” a sports service like ESPN, Cricbuzz, and Hotstar. It's built as a pipeline you can trace end to end: the live stream's journey from stadium to screen, then the supporting systems (validation, buffering, storage) and finally the operational playbook for surviving peak traffic. Each concept is a reusable building block you'll see again in later chapters. Anything marked [+] is context I added; everything else is rewritten from the ten teaching lessons.

01

One website, six real-world systems inside it

The service covers sports internationally through articles, real-time commentary, live streaming, and more. For scale context: Cricbuzz sees ~220M monthly visitors; Hotstar handles ~420M users with 10โ€“25M concurrent during peak cricket season.

The design trick is that the homepage isn't one application โ€” each section is powered by a separate backend service, and each is itself a full-blown distributed system. Build them independently, then club them together via APIs and message queues:

Live streamingThe core feature โ€” same shape as Twitch, YouTube Live, Facebook, Hotstar. The focus of this chapter.
Video-on-demandReplays, highlights, key moments โ€” architecturally a Netflix/Prime/Hulu (Chapter 5).
CMSNews articles, write-ups, live text commentary, stats โ€” like NY Times, Bloomberg, Cricbuzz.
Content searchSearching across images, text, and video (Chapter 7).
Ads servingStitched into the stream in real time.
User subscriptionsPayments โ€” standard in nearly every online service (Chapter 8).
๐Ÿงฉ
The mental model for the whole course

This is how YouTube and Netflix are actually built: microservices/modules with distinct responsibilities, communicating over APIs and message queues. Learn to design one such service and you understand the anatomy of many others.

02

From camera to codec: encode, transcode, segment

Picture the FIFA final, England vs. France, with two traffic hotspots. Raw high-resolution video is enormous โ€” it exhausts bandwidth, burns compute and storage, and pushes latency up. The whole first-mile pipeline exists to shrink that latency.

  1. Encoding โ€” compress the file size without hurting quality, using codecs like H.264 (AVC), H.265 (HEVC), H.266 (VVC), AV1, VP9, MPEG-2. [+] Newer codecs trade more CPU for smaller files. (YouTube engineering famously moved to VP9.)
  2. Transcoding โ€” re-encode into multiple formats, resolutions, and aspect ratios so the stream plays on any device under any network. The stream should never stop; quality may drop, but playback continues.
  3. Segmentation โ€” split the stream into 1โ€“6 second chunks so the client plays the first segment immediately instead of waiting for a whole file.
  4. Decoding โ€” the client's player uncompresses each segment and plays it.

Adaptive bitrate streaming

Bitrate is data-per-unit-time (Mbps); higher bitrate = higher quality. Transcoding produces the same stream at several bitrates, and the client's adaptive bitrate algorithm switches between them at segment boundaries based on current bandwidth. Weak network โ†’ next segment comes in at a lower bitrate; the stream keeps rolling.

cameraraw encode +transcode 1080p ยท 6 Mbps 720p ยท 3 Mbps 480p 360p segments client playerpicks ladder / segment
Figure 1 โ€” Adaptive bitrate: one encode fans into several bitrate ladders, each segmented; the client swaps ladders per segment as bandwidth changes. Original diagram after Figure 3.6.

Protocols & knowing your audience

Multiple protocols cover different legs: RTMP for the first mile (camera โ†’ encoder) and often the last mile; HLS or MPEG-DASH for delivery to devices; SRT is another transport option. When designing, know the audience: typical bandwidth, rural vs. urban infrastructure, mobile vs. Smart TV, and content type (a 2D cartoon compresses far more cheaply than a live match).

03

The last mile: edge caches and the thundering herd

The backend does far more than encode โ€” it stitches ads, embeds live scores/graphics, adds the broadcaster logo, restreams to YouTube/Facebook, runs real-time monitoring, and stores the stream for later. Once packaged, the stream is pushed from the origin data center to edge locations worldwide, nearest to each viewer. Edge nodes act as caches: fetch from origin once, serve many nearby viewers, minimizing latency and origin load.

๐Ÿ˜
The thundering herd problem

Suppose a segment isn't in the edge cache yet. Half a billion concurrent viewers hit the cache, miss, and the requests stampede toward the origin โ€” overwhelming it into lag, dropouts, and eventual collapse.

The fix is request coalescing: requests are never let through to origin. The edge node queues all requests for a missing segment, fetches from origin once, populates the cache, and fans the single response out to every waiting viewer.

viewers ร—N edge nodecache + requestqueue (coalesce) 1 fetch on miss origin DCprotected Without coalescing: N requests โ†’ origin = stampede
Figure 2 โ€” Request coalescing at the edge: duplicate requests for a missing segment are queued, collapsed into one origin fetch, then fanned back out. Original diagram after Figures 3.7โ€“3.8.
04

Is it rendering smoothly? Real-time validation with ELK

Once the stream is live, you need a system that continuously confirms it renders well on viewers' devices, watches for errors, and alerts on-call staff instantly. Viewer devices emit video playback logs into an ELK stack:

Component Role
Elasticsearch Distributed, RESTful, JSON-based full-text search & analytics engine โ€” stores and indexes the logs.
Logstash Aggregates logs from many sources, transforms them to a common format, and ships them onward.
Kibana Web UI to visualize, query, and analyze the data via graphs and charts.

Log management is just one ELK use case โ€” it's also used for app metrics, performance, endpoint security, uptime, and application search.

Archiving old data โ€” and why tape still matters [+]

Keep recent data (โ‰ค ~1 year) in Elasticsearch; archive older data to cloud archival storage, which cuts cost dramatically and frees space, while still serving archived data via API in milliseconds (no tape-style retrieval delay). But cloud storage isn't a 100% replacement for tape โ€” software bugs can inadvertently delete data. Two real Google incidents make the case:

Gmail, Feb 27 2011Despite redundancies, Gmail lost user data. GTape (global tape backup) restored 99%+ of it โ€” tape protects against disk failures and wide-scale infrastructure failures.
Google Music, Mar 6 2012A privacy-deletion pipeline bug removed ~600K audio references for 21K users. ~5K tapes holding 1.5 PB restored 436,223 tracks in 7 days; ~161K were eaten before backup (mostly recoverable promo copies).

The takeaway: combine cloud archival and tape backups for critical data. (Source: Google Research, Designing and Operating Highly Available Software Systems at Scale.)

05

Why Kafka sits between the devices and Logstash

Why not push logs straight to Logstash? During a live event the log influx is massive, and Logstash's filtering/transforming plus Elasticsearch's indexing all take time. Under that velocity, the pipeline bottlenecks. Kafka is placed in front of Logstash as a buffer โ€” Logstash consumes from Kafka topics at its own pace, exactly like the edge cache absorbing the thundering herd.

Kafka fundamentals

Because Kafka is highly available, fault-tolerant, and O(1) with respect to data size, it can durably store events for as long as you want โ€” like a distributed database that also streams.

06

What makes Kafka so fast (it leans on the disk)

Counterintuitively, Kafka relies on disk + the filesystem rather than in-memory caching. Disks are slow or fast depending on how you use them โ€” a well-designed disk structure can be as performant as you need. Four techniques do the heavy lifting:

Technique Why it's fast
Sequential I/O Kafka uses a segmented, append-only log, restricting reads/writes to sequential access. In a benchmark on a 4 GB on-disk array: sequential disk read = 53.2M values/sec vs. random memory access = 36.7M/sec โ€” sequential disk beats random memory. (Source: The Pathologies of Big Data.)
Page cache in RAM The OS keeps disk pages cached in free RAM. Kafka rides this, effectively doubling available cache; and because it uses a compact byte structure (not JVM objects), it dodges garbage-collection penalties. The page cache stays warm across restarts, unlike an in-memory cache that must rebuild.
Batch compression Compresses bundled messages together (not individually), stores them compressed, and ships a whole batch in one request โ€” uncompressed by the consumer. Batches cap by count or a short wait (10โ€“20 ms), trading a little latency for throughput. Supports GZIP, Snappy, LZ4, ZStandard.
Zero-copy transfer Normally data is copied between user-space and kernel-space buffers. Zero-copy bypasses the kernel-space buffer, moving data straight to hardware โ€” a big speed jump Kafka exploits.
โšก
Parallelism comes free

Because topics are partitioned across brokers, Kafka processes data in parallel โ€” the same throughput lever every distributed system pulls.

07

Saving the stream for replays (object storage + a DB map)

For replays, highlights, and key moments, persist the live stream to cloud object storage (how YouTube stores video). The critical design point:

๐Ÿ—„๏ธ
Video files go to storage, not the database

Store the video files on disk via object storage; keep a database table that maps video ids โ†’ disk locations plus metadata (sport, date, venue). Objects live in globally-named buckets tied to a region; each object holds video data + metadata.

A file's disk path might be https://livestream.ourwebsite.com/football/engvsfrance_fifa_20220417.mp4. The host part goes into a config/property file; the path part (/football/engvsfrance_fifa_20220417.mp4) goes into the MySQL LiveStream table. You can even factor /football into config and assemble the full path at fetch time โ€” it depends on the use case.

Storage estimation for one game [+]

A 2-hour match at ultra-HD 8K compresses to ~28 GB. Transcoding into lower ladders adds up:

Resolution Approx. file size
8K (7680ร—4320) 28 GB
4K (3840ร—2160) 14 GB
1080p (1920ร—1080) 6 GB
720p (1280ร—720) 3 GB
360p (480ร—360) 2 GB
Total / game โ‰ˆ 53 GB

Rough numbers โ€” actual size varies with bitrate, bit depth, codec, resolution, and frame rate (size references from Netflix). Cloud storage cost depends on data size, instance types, number of operations, bandwidth, cross-region replication, daily backups, and storage class.

08

Game-day readiness: observability and injecting chaos

These practices apply to any distributed service, not just streaming. Step one is deep visibility with no blind spots โ€” every module monitored.

Synthetic traffic, then chaos

Before the real load hits, send synthetic traffic from different cloud regions to test availability, performance, and transaction flows (login, subscription) under artificial peak load โ€” surfacing bottlenecks and regional errors early.

๐Ÿ’
Chaos engineering โ€” Netflix's Simian Army

Netflix built Chaos Monkey to randomly kill production instances, then watch whether services survived โ€” driving them to build automatic recovery. The wider "Simian Army": Latency Monkey (injects delays), Conformity Monkey (kills non-conforming instances), Doctor Monkey (removes unhealthy ones), Janitor Monkey (now Swabbie โ€” reaps unused resources), and Chaos Kong (kills an entire AWS region). Many now live inside Spinnaker, Netflix's open-source continuous-delivery platform.

09

Don't trust autoscaling: ladders, degradation, throttling

Capacity planning & ladder-based scaling

Estimate average and peak game-day traffic from past game data and load tests. Then here's the key warning: don't rely on autoscaling for sudden spikes. New instances need provisioning, warm-up, and cluster registration โ€” minutes you don't have when traffic climbs by millions of hits per minute. Worse, the cloud may not have the instance types you need in that region right then.

Instead use ladder-based scaling with pre-provisioned buffers:

50Kโ€“100K hits/min   โ†’  x instances running (even if underutilized)
100Kโ€“150K hits/min  โ†’  x + 20 instances
150Kโ€“300K hits/min  โ†’  x + 40 instances
...as traffic climbs the ladder, pre-defined instances spring to life

A ready buffer means no warm-up wait. Even so, there's a financial ceiling on instances/clusters โ€” so two more levers matter.

Graceful degradation

Services have priorities. During the event, streaming, sign-in, and subscription payment are high-priority; movie recommendations, feedback, and search are not. Under exceptional load, reallocate resources from non-priority services to priority ones โ€” the low-priority services still respond, just more slowly. That's graceful degradation.

Throttling & rate limiting

Throttling controls the rate of events to keep servers from being overwhelmed. Applied on the backend to an API it's called rate limiting โ€” it caps requests per time window, adds a security layer against bots/scraping/DDoS, and underpins SaaS request-based pricing. Algorithms: token bucket, leaky bucket, fixed window counter, sliding window, sliding window counter.

๐Ÿค
Server-side and client-side, together

Rate limiting alone isn't enough โ€” clients keep sending, wasting bandwidth and forcing the backend to keep running its limiting logic. Pair it with client-side rate-throttling: when the client starts getting HTTP 429 (too many requests), it slows down. Two guardrails: keep the average retry rate minimum (few 429s, saving bandwidth) and the maximum sleep time minimum (don't make users wait longer than necessary) โ€” while never leaving the API under-consumed.

10

Recap

Modular serviceSix independent distributed systems (live, VOD, CMS, search, ads, subscriptions) clubbed via APIs and message queues.
Stream pipelineEncode โ†’ transcode โ†’ segment; adaptive bitrate switches ladders per segment. RTMP first mile, HLS/DASH last mile.
Edge + coalescingPush to worldwide edge caches; queue duplicate requests on a miss and hit origin once to beat the thundering herd.
ELK + KafkaDevices log playback โ†’ Kafka buffer โ†’ Logstash โ†’ Elasticsearch โ†’ Kibana. Archive old data to cloud + tape.
Kafka speedSequential I/O on an append-only log, OS page cache, batch compression, zero-copy, partition parallelism.
Persist for VODVideo files in object storage buckets; a DB table maps ids โ†’ paths + metadata. ~53 GB per multi-resolution game.
ReadinessObservability (metrics/logs/traces), synthetic traffic, chaos engineering (Simian Army).
Surviving peaksLadder scaling over autoscaling, graceful degradation for priority services, server + client throttling.
๐Ÿ’ก
The single idea underneath it all

Every hard problem in live streaming is the same problem wearing a different mask: a wave of demand arriving faster than a downstream system can absorb it. The camera outruns the network (transcode + segment). Viewers outrun the origin (edge + coalescing). Devices outrun Logstash (Kafka buffer). Game-day traffic outruns provisioning (ladders + degradation + throttling). The whole chapter is one technique applied over and over โ€” put a buffer between the surge and the thing that would break, and let the slow side pull at its own pace.

11

Further reading

The links below all resolve live, grouped by topic. The author's own course cross-links and one source that failed to load (a scaleyourapp.com blog on 100M-user scale) are omitted.

Streaming & codecs

[1]
YouTube rolls out VP9 encoding โ€” ZDNet Why read it: the real-world codec example from Section 02 โ€” YouTube's move to VP9.
[2]
Internet connection speed recommendations โ€” Netflix Why read it: the file-size / bitrate reference behind Section 07's storage estimates.

Observability & the ELK stack

[3]
The Elastic (ELK) Stack โ€” Elastic Why read it: Elasticsearch + Logstash + Kibana, the monitoring backbone of Sections 04โ€“05.
[4]
Zipkin Why read it: distributed tracing tool from Section 08 (note it reports over HTTP or Kafka).
[5]
Jaeger Why read it: the other distributed tracing platform named in Section 08.

Kafka performance

[6]
The Pathologies of Big Data โ€” ACM Queue Why read it: the sequential-disk-beats-random-memory benchmark cited in Section 06.

Reliability, chaos & storage

[7]
Designing and Operating Highly Available Software Systems at Scale โ€” Google Research Why read it: the source for Section 04's Gmail/Google Music tape-restore incidents.
[8]
Chaos Monkey โ€” Netflix (GitHub) Why read it: the original chaos-engineering tool behind Section 08's Simian Army.
[9]
Spinnaker Why read it: Netflix's open-source CD platform that now houses much of the Simian Army (Section 08).
[10]
Swabbie โ€” Spinnaker (GitHub) Why read it: the successor to Janitor Monkey that reaps unused cloud resources (Section 08).
[11]
Cloud Storage pricing โ€” Google Cloud Why read it: how storage cost is calculated across factors, per Section 07.
[12]
Amazon S3 pricing โ€” AWS Why read it: object-storage pricing (storage classes, requests, retrieval) referenced in Section 07.