System Design

How do video sites serve huge audiences? CDN plus peer-to-peer over WebRTC

TL;DR

Video is cut into few-second segments. Instead of the CDN serving every viewer, players watching the same segment share it with each other over WebRTC. If a peer drops out, the player falls back to the CDN for the original, so playback never stalls.

Watch on Facebook

When a livestream has tens of thousands of simultaneous viewers, CDN bandwidth becomes a major cost. One way to cut it is CDN combined with P2P over WebRTC: instead of the CDN sending every video segment to every viewer, the players of people watching the same segment share it with each other. Viewers both receive and re-send, so the CDN has to deliver fewer copies.

The mechanism by example

StepWhat happens
SegmentingVideo is split into segments a few seconds long (HLS/DASH).
Distribution9 viewers watching the same segment: the CDN sends only 2 copies, the other 7 are passed between viewers over WebRTC.
Someone leavesThe in-transit packet is dropped → the player immediately re-fetches from the CDN, and playback doesn't stall.
Result (2 segments)CDN 5 deliveries, viewers relay 14 themselves.

Components

  • Segments: short HLS/DASH video chunks; viewers watching at the same time need the same segments.
  • Tracker/signalling: a server that helps peers find each other and exchange connection details.
  • WebRTC data channel: a browser-to-browser data channel, traversing NAT via STUN/TURN.
  • The player: decides whether to fetch a segment from a peer or the CDN, and checks integrity.

When is it worth it?

  • Livestreams or content with very many simultaneous viewers: CDN bandwidth costs drop significantly.
  • Popular content: many people need the same segment in the same time window.
  • Ineffective for content with few viewers or viewers spread out in time.

Risks and trade-offs

  • Always keep the CDN as a fallback: P2P is only an optimisation layer; the experience must not depend on peers being available.
  • Latency and stability: peers can be slow or leave at any time; the player must switch to the CDN in time.
  • Privacy: peers may see each other's IP addresses; consider this and disclose it.
  • Users' bandwidth: the browser uses upload capacity to share with others; disclose this in your terms and avoid enabling it on mobile data.
  • Content integrity: segments need verification (hashes/signatures) so peers can't inject bad data; copyrighted content needs DRM as well.

How to apply it

  • Video engineers: try it on a high-audience event and measure the share of bandwidth saved.
  • Tech Lead: weigh cost against complexity before building it yourself; there are P2P libraries for HLS.js/Shaka Player and commercial hybrid CDN-P2P services.
  • PM/Legal: make sure users are informed transparently.

Sources & references

  1. WebRTC API — MDN Web Docs