The Problem#
Design a video conferencing service like Zoom, Google Meet or Microsoft Teams. People join a meeting from a link, see and hear each other with very little delay, share their screens, chat, and record the meeting. A meeting may have 2 people or 1,000, and a webinar may have tens of thousands watching.
An analogy: a conference call through a switchboard. Imagine everyone in a meeting phoning a switchboard operator. The operator does not repeat what each person says (that would be slow and tiring). Instead, the operator plugs each caller's line into the lines of everyone who should hear them, and turns down the volume on the lines of people with bad connections. The operator also decides who gets the "big screen" when someone speaks. The media server in a video meeting is that operator: it forwards packets to the right people, chooses which quality each person gets, and does almost no processing of the content itself.
What makes this problem different from video streaming (the case study Design a Video Streaming Platform (YouTube / Netflix)):
- Latency is everything. A streaming service can buffer 10 seconds of video. A conversation breaks down if the delay from one person's mouth to another's ear goes much above 150–300 ms. There is no time for retries over TCP, large buffers, or transcoding on the server.
- Everyone sends and everyone receives. In streaming, one source serves millions. In a meeting of 20, there are 20 sources and 20 receivers, and each receiver may want a different mix of sources at a different quality.
- Networks are hostile. Users sit behind home routers, corporate firewalls, hotel Wi-Fi and mobile networks that drop packets, change addresses and block UDP. Just connecting two devices is a real problem.
- Load arrives in synchronised waves. Meetings start on the hour and half hour, so join requests spike at 9:00 and 9:30 in every time zone.
Background: a few terms used in this design#
- WebRTC (Web Real-Time Communication): a set of browser APIs and IETF protocols for sending audio, video and data between devices with low latency. Google released it as an open-source project in May 2011, based on technology from Global IP Solutions, which it had bought in 2010. The W3C made WebRTC 1.0 a Recommendation in January 2021.
- RTP and RTCP: the Real-time Transport Protocol carries media in small packets with sequence numbers and timestamps. Its companion RTCP carries reports about loss, delay and receiver state.
- SRTP and DTLS: Secure RTP encrypts media packets. The keys are agreed using DTLS (TLS over UDP), so this is called DTLS-SRTP.
- NAT (Network Address Translation): a home or office router that shares one public IP address among many devices. Devices behind a NAT cannot be reached from outside unless they send packets out first.
- ICE, STUN and TURN: the toolkit for getting through NATs. STUN tells a device what its public address looks like. TURN is a relay server that forwards packets when a direct path is impossible. ICE (Interactive Connectivity Establishment) gathers all possible addresses and tests them to find a working path.
- Signalling: the out-of-band channel (usually a WebSocket to the service) used to set up and control a session: who is in the meeting, what codecs and addresses to use, mute and unmute, and so on.
- SDP (Session Description Protocol): the text format used in WebRTC to describe media sessions (codecs, tracks, encryption fingerprints) in an offer and answer exchange.
- SFU (Selective Forwarding Unit): a media server that receives each participant's streams and forwards selected streams to other participants without decoding them.
- MCU (Multipoint Control Unit): a media server that decodes all streams, mixes them into one picture and one audio signal, and re-encodes the result for each participant.
- Simulcast: a sender encodes the same video at several qualities (for example 1080p, 360p and 180p) and sends them all, so the server can forward the best one each receiver can handle.
- SVC (Scalable Video Coding): one encoded stream built in layers; lower layers give a basic picture and higher layers add resolution or frame rate. The server can drop upper layers for a weak receiver.
- Jitter: variation in packet arrival times. A jitter buffer on the receiver holds packets briefly to play them smoothly.
- Keyframe (I-frame): a video frame that can be decoded alone. Other frames depend on earlier ones, so a receiver that joins late or loses packets needs a new keyframe.
- Mouth-to-ear latency: the time from someone speaking to a listener hearing it. ITU-T Recommendation G.114 suggests keeping one-way delay below about 150 ms for good interactivity.
- Opus: the standard audio codec for WebRTC (RFC 6716), good from about 6 kbps to over 128 kbps, with built-in tools for packet loss.
Clarifying Questions#
| Question | Assumed answer |
|---|---|
| What clients must be supported? | Desktop apps, mobile apps and browsers (WebRTC). Phone dial-in is a nice-to-have. |
| How large can a meeting be? | Up to 1,000 interactive participants. Webinars of up to 10,000 view-only attendees, and live streaming beyond that. |
| What is the typical meeting? | 2–10 people, 30–60 minutes. Most meetings are small; a few are huge. |
| What latency target? | Mouth-to-ear under 150 ms within a region, under about 300 ms between continents. Join in under 3 seconds. |
| Do we need screen sharing? | Yes, with readable text, and optional computer audio. |
| Is in-meeting chat required? | Yes, with messages visible to late joiners, plus reactions and raised hands. |
| Recording? | Cloud recording on request, with transcripts; local recording optional. |
| Encryption? | All media and signalling encrypted in transit. Optional end-to-end encryption for smaller meetings, with some features disabled. |
| Which regions? | Global, with users choosing which regions may handle their meetings for data residency. |
| Do we need breakout rooms, polls, captions and whiteboards? | Breakout rooms and captions yes; others can be mentioned briefly. |
| Scale? | Roughly Zoom's pandemic peak: about 300 million daily meeting participants. |
| Do we need to scale bandwidth to poor networks? | Yes. Meetings must work on 3G, lossy Wi-Fi and networks that block UDP. |
Requirements#
Functional requirements#
- Create and join meetings. A host schedules or starts a meeting and gets a link with a meeting ID and passcode. Others join from the link, possibly through a waiting room.
- Real-time audio and video among all participants, with views such as active speaker and gallery.
- Screen sharing by one or more participants, with optional audio.
- In-meeting chat to everyone or to one person, plus reactions and raised hands.
- Host controls: mute others, remove participants, lock the meeting, admit from the waiting room, assign co-hosts, create breakout rooms.
- Cloud recording of audio, video, screen share and chat, with a transcript, available after the meeting.
- Large meetings and webinars: 1,000 interactive participants, and many more view-only attendees.
- Reconnection: if a network drops for a few seconds, the participant rejoins automatically without losing their place.
Non-functional requirements#
- Latency: mouth-to-ear p95 under 150 ms in the same region and under 300 ms across continents. Video in sync with audio (lip sync within about 50 ms).
- Join time: under 3 seconds from clicking the link to seeing video.
- Quality under bad networks: usable audio at 20% packet loss; video quality adapts within a second when bandwidth drops.
- Availability: 99.99% for joining and in-meeting media. A failed media server must not end the meeting; participants should reconnect within seconds.
- Scalability: tens of millions of concurrent participants at peak, with join spikes at the top of each hour.
- Security and privacy: encrypted media; unguessable meeting links; hosts can stop uninvited guests; optional end-to-end encryption; data residency controls.
- Cost efficiency: media servers forward instead of transcoding whenever possible, because bandwidth and CPU are the main costs.
Capacity Estimation#
The method is from Back-of-the-Envelope Estimation. The goal is to find which resource limits the design: here it is media forwarding bandwidth and packet rate, not storage or database load.
Assumptions.
- In April 2020 Zoom reported about 300 million daily meeting participants. That counts each person once per meeting joined, so one person in four meetings counts four times. We use 300 M participant-sessions a day.
- An average session lasts 40 minutes. The average meeting has about 5 participants, so there are about 60 M meetings a day.
- 60% of participants have video on at any moment. Everyone has audio, but most are muted most of the time.
- Business hours dominate. Peak concurrency is about 3× the daily average.
Concurrency.
- Participant-minutes per day = 300 M × 40 = 12 billion.
- Average concurrent participants = 12 B ÷ 1,440 ≈ 8.3 M. Peak ≈ 25 million concurrent participants in about 5 million concurrent meetings.
- Joins at peak: meetings cluster at :00 and :30. If 20% of an hour's 25 M joins land in the 2 minutes around the hour, that is 5 M joins in 120 s ≈ 40,000 joins per second for short bursts.
Bandwidth per participant (typical settings).
| Stream | Bitrate |
|---|---|
| Audio (Opus, with headers) | 30–50 kbps |
| Camera, simulcast sent as three layers: 720p, 360p, 180p | about 1,200 + 350 + 100 ≈ 1.65 Mbps |
| Screen share (1080p+, low frame rate) | 0.5–2 Mbps, mostly when the content changes |
| Download in gallery view: 1 large tile at 720p plus 8 tiles at 180p, plus audio | about 1.2 + 8 × 0.1 + 0.1 ≈ 2.1 Mbps |
| Download in speaker view: one 720p stream plus thumbnails | about 1.5 Mbps |
Media server load.
- Upload into servers: 25 M × (0.6 × 1.65 Mbps + 0.04 Mbps) ≈ 25 M × 1.03 Mbps ≈ 26 Tbps.
- Download from servers: 25 M × about 1.8 Mbps ≈ 45 Tbps.
- Together about 70 Tbps through the media tier at peak. This is larger than a big music service's entire output, and it is real-time: none of it can be cached, because every packet is new.
- Packet rate matters more than bytes. Video packets are about 1,100 bytes, audio packets about 100–150 bytes every 20 ms (50 per second per speaker). 45 Tbps ÷ 8,800 bits ≈ 5 billion packets per second out of the media tier.
- A well-tuned media server forwards perhaps 1–2 million packets per second per server (about 10–15 Gbps), limited by per-packet CPU work (decrypting and re-encrypting SRTP, rewriting headers, choosing layers). So peak needs roughly 5 B ÷ 1.5 M ≈ 3,500 media servers busy. With 2× headroom for failover and spikes, about 7,000 media servers across 20–40 data centres.
Relays (TURN).
- Many corporate and public networks block UDP or have strict NATs. Industry experience is that a minority of WebRTC sessions (often quoted as somewhere around 10–20%, varying widely by audience) need a relay or a TCP/TLS fallback.
- In an SFU design, the media server already has a public address, so most "relay" cases become "connect to the media server over TCP or TLS on port 443". We still size TURN-like capacity for about 15% of participants: 25 M × 0.15 × 3 Mbps ≈ 11 Tbps of relayed or TCP-wrapped traffic.
Signalling.
- Each participant keeps one WebSocket. 25 M concurrent connections. At about 50,000–100,000 idle-heavy WebSockets per server, that is 250–500 signalling servers.
- Messages: joins, leaves, mute changes, active speaker changes (several per minute in a busy meeting), roster updates, chat, reactions. Averaging one message every 10 seconds per participant gives 2.5 million messages per second, mostly fan-out within a meeting.
Recording and storage.
- Assume 5% of meetings are cloud-recorded: 3 M recordings a day × 40 minutes.
- A composite recording at 720p is about 1 Mbps, or 450 MB per hour, so 300 MB per 40-minute meeting. Audio-only and transcript files are small.
- 3 M × 300 MB ≈ 900 TB a day, or about 330 PB a year if kept forever. This is why recordings have retention limits by plan and move to cheaper storage tiers.
- Transcoding: each recording needs one composite encode (roughly 1 core per real-time stream with a fast preset), so about 3 M × 40 min ≈ 120 M core-minutes a day ≈ 83,000 cores if done in real time during the meeting, or a cheaper batch afterwards.
Metadata.
- Meetings: 60 M a day × about 2 KB (settings, host, schedule, security options) ≈ 120 GB a day. Participants: 300 M × 500 bytes ≈ 150 GB a day. A sharded relational or wide-column store handles this easily.
- Chat: perhaps 1 message per participant per meeting on average, so 300 M messages a day at 200 bytes ≈ 60 GB a day.
What the numbers say.
- The media plane (about 70 Tbps, 5 billion packets per second) is the design's centre. Every design choice should reduce bytes and per-packet work: forwarding instead of mixing, simulcast or SVC instead of transcoding, sending only the streams each receiver will display.
- Media must be close to users. At 150 ms budgets, a server on the wrong continent uses most of the budget on distance alone.
- The control plane (meetings, users, chat) is ordinary web-scale work; it just must not be on the media path.
Core Entities#
- User: an account with a plan, settings and an organisation.
- Meeting: a scheduled or instant meeting with an ID, passcode, host, settings (waiting room, recording, encryption mode) and allowed regions.
- MeetingInstance (session): one actual occurrence of a meeting, with start and end times and the media servers assigned. A recurring meeting has many instances.
- Participant: a user (or guest) in a meeting instance, with a role (host, co-host, attendee, panellist), device, state (waiting, joined, in breakout room), and media state (muted, video on, sharing).
- Track: one media stream from a participant: microphone, camera (with simulcast layers or SVC layers), screen share.
- MediaServer / Cluster: an SFU instance with its region, capacity and current load.
- ChatMessage: a message in a meeting with sender, recipients (everyone or one person), sequence number and time.
- Recording: a recording of a meeting instance, with its files (video, audio, transcript, chat), status and retention.
- BreakoutRoom: a sub-meeting within a meeting instance, with its own participants and media routing.
API Design#
The API has three parts: a REST control API, a signalling protocol over WebSocket, and the media itself over RTP.
REST control API.
POST /v1/meetings
{ "topic": "Weekly sync", "start_time": "2026-12-07T09:00:00Z", "duration_min": 45,
"settings": { "waiting_room": true, "passcode": "auto", "e2ee": false,
"allowed_regions": ["eu"], "auto_record": "cloud" } }
-> 201 { "meeting_id": "8471 2290 3315", "join_url": "https://zoom.example/j/84712290331?pwd=...",
"host_key": "..." }
POST /v1/meetings/{meeting_id}/join
{ "passcode": "...", "display_name": "Asha", "client": { "type": "web", "version": "6.2" } }
-> 200 { "session_token": "<signed, 5 min>", "signalling_url": "wss://sig-eu-3.example/ws",
"ice_servers": [ { "urls": ["turns:turn-eu-3.example:443?transport=tcp"],
"username": "...", "credential": "..." } ],
"media_region": "eu-central" }
GET /v1/meetings/{meeting_id}/recordings
-> 200 { "recordings": [ { "id": "...", "type": "composite_video", "size_bytes": 312000000,
"download_url": "<presigned, 1 h>" } ] }Signalling messages (JSON over WebSocket). The client keeps one connection for the whole meeting.
-> join { session_token, capabilities: { codecs, simulcast, svc } }
<- joined { participant_id, roster, media_server: { address, ice_ufrag, dtls_fingerprint }, seq }
-> offer / <- answer { sdp } (WebRTC offer and answer, or a compact equivalent)
-> publish { track: "camera", layers: ["f","h","q"] }
-> subscribe { participant_id, track: "camera", max_resolution: "360p" }
<- roster_update { seq, changes: [ { participant_id, state: "joined" } ] }
<- active_speaker{ seq, participant_ids: [ ... ] }
-> chat_send { client_msg_id, to: "everyone", text }
<- chat { seq, msg_id, from, text, ts }
-> host_action { action: "mute", target: participant_id }
<- keepalive / -> keepalive- Every server-to-client message has a sequence number per meeting, so a client that reconnects can say "I have everything up to seq 4,812" and receive only what it missed.
client_msg_idmakes chat sends idempotent if the client retries after a reconnect.- The session token is short-lived and signed. It names the meeting, the participant's role, and the allowed region, so signalling and media servers can check it without calling a central database.
Media (RTP over UDP, or wrapped in TCP or TLS when UDP is blocked). Not an API in the usual sense, but its "contract" matters: Opus audio, VP8, VP9, H.264 or AV1 video, RTP header extensions for audio level, transport-wide sequence numbers (for bandwidth estimation) and layer identifiers, and RTCP feedback for loss, keyframe requests and bandwidth estimates.
High-Level Design#
The design splits into a control plane (meetings, users, signalling, chat, recording management) and a media plane (SFUs and relays that move RTP packets). The control plane decides who talks to whom and where. The media plane moves the packets and must never wait on the control plane for each packet.
1) Create and join a meeting#
- The meeting service stores meetings and settings. Creating one is an ordinary write; joining reads settings, checks the passcode, and puts the user in the waiting room if enabled.
- The placement service decides where the meeting's media lives. For the first joiner it picks the nearest healthy region and a media server with spare capacity, and records the assignment. Later joiners get the same server (or a cascaded one in their own region; see Deep Dive 6).
- The client receives a short-lived session token plus the address of the signalling server and ICE server credentials, and then opens a WebSocket to signalling.
The token lets later steps avoid a database. The signalling server and the SFU both verify the token's signature, meeting ID, role and expiry locally.
2) Real-time audio and video through an SFU#
- Every participant sends one upstream set of tracks to the SFU (audio, plus camera as simulcast layers or SVC).
- The SFU forwards to each receiver only the tracks and layers that receiver will show, at the quality its downlink can handle.
- The SFU does not decode or encode video. It reads RTP headers, picks packets, rewrites sequence numbers so each receiver sees a continuous stream, and encrypts again for each receiver's DTLS-SRTP session.
- Two-person meetings can go peer-to-peer when the network allows, removing the server from the media path. The newsletter summary of Zoom's architecture says Zoom does this for meetings with two participants. If a third person joins, the call moves to the SFU.
3) Screen sharing#
Screen share is just another track, but with very different encoding (high resolution, low frame rate, sharp text) and a higher priority than cameras. When someone shares, the SFU usually gives the screen most of each receiver's bandwidth and drops camera tiles to thumbnails.
4) In-meeting chat, reactions and raised hands#
Chat uses the signalling connection rather than the media path. Messages are ordered by a per-meeting sequence number assigned by the signalling server that owns the meeting, stored for late joiners and the recording, and fanned out to everyone connected.
5) Host controls and meeting state#
The meeting state (roster, roles, mute and video flags, who is sharing, lock and waiting room) lives in memory on the signalling server that owns the meeting, with a replica in a fast store for failover. Host actions are checked against the sender's role, applied in order, and broadcast. Enforcement happens on the server: if the host mutes someone, the SFU stops forwarding that person's audio, so a modified client cannot ignore it.
6) Cloud recording#
A recorder joins as a hidden participant and receives every track the SFU forwards, like any client. It writes the raw media to object storage in chunks during the meeting. After the meeting, a batch pipeline composes the layout (who was on screen when), transcodes to MP4, produces a transcript, and notifies the host.
7) Large meetings and webinars#
Large meetings use cascaded SFUs: one SFU per region per meeting, connected to each other, so each region's participants connect locally and each stream crosses continents once. Webinars separate a small set of interactive panellists from a big audience that only receives. Beyond tens of thousands, the meeting is composed into one stream and broadcast with HLS or DASH through a CDN, as in live streaming, accepting a few seconds of delay.
8) Reconnection#
A participant whose network changes keeps the same participant ID. The client resumes signalling with its last sequence number and performs an ICE restart to find a new path to the same SFU. The SFU keeps the participant's slot for a grace period (say 30 seconds) before telling others they left.
The full high-level design#
Components:
- Clients capture, encode, encrypt, send, receive, decode and render media. They also run bandwidth estimation, echo cancellation and noise suppression, and choose which streams to subscribe to based on the layout. A lot of the system's intelligence lives here.
- API gateway and meeting service handle accounts, scheduling, join authorisation and settings, as in any web service. See API Gateway and Backend-for-Frontend.
- Placement service keeps a live view of every media server's load and health, chooses regions and servers for meetings, and handles cascading and failover.
- Signalling servers hold one WebSocket per participant, own the meeting state for the meetings assigned to them, order state changes and chat, and tell SFUs what to forward. See Polling, Long Polling, SSE, WebSockets and Webhooks.
- SFUs forward media with layer selection, bandwidth estimation, packet loss recovery (NACK and retransmission), and keyframe requests.
- TURN and TCP/TLS relays get media through restrictive networks.
- Recorders, composers and packagers produce recordings and large-audience streams.
- Chat service stores chat history for late joiners and the recording.
- Telemetry collects per-call quality statistics (loss, jitter, round-trip time, freezes, bitrates) from clients and servers, for alerts, routing improvements and support.
Key Flows#
Flow 1: joining a meeting and connecting media to the SFU#
The target is under 3 seconds from click to video. A rough budget: the join API about 100–200 ms, the WebSocket and join about 100 ms, ICE checks one or two round trips (50–150 ms), DTLS one or two round trips (50–150 ms), then the first keyframe from each remote sender, which the SFU can request immediately. The biggest delays come from device permissions, camera start-up and slow first keyframes, not from the servers.
Flow 2: a two-person call that goes peer-to-peer#
ICE tries the cheapest working path first: direct local addresses, then public addresses learned from STUN, then the TURN relay. Candidates are sent as they are found ("trickle ICE"), so checks start before gathering finishes.
Flow 3: a receiver's bandwidth drops#
The SFU estimates each receiver's downlink from feedback, and chooses layers so the total fits. A switch to a different simulcast layer must start at a keyframe of that layer, so the SFU asks the sender for one, which costs a short burst of extra bits. With SVC, dropping to a lower layer needs no keyframe.
Flow 4: a media server fails during a meeting#
Users see a freeze of a few seconds, but the meeting continues with the same roster and chat, because that state lives in the signalling tier rather than the SFU. Clients may also detect the failure themselves (no media for about 2 seconds) and ask signalling for a new server.
Flow 5: cloud recording#
Every participant is shown a recording indicator, which is a legal requirement in many places. Writing chunks during the meeting means a recorder crash loses at most a few seconds.
Flow 6: a participant in another region joins (cascading)#
Each stream crosses the long-haul link once, however many people are on the other side, and every participant gets a short first hop to a nearby server, where packet loss is detected and repaired quickly.
Data Model#
The control plane holds modest amounts of data with clear relationships: meetings, instances, participants, recordings. A relational database sharded by account (or meeting) is the natural choice for meeting and account data. Live meeting state is in memory on signalling servers with a fast replicated store as backup. Chat and participant events are append-heavy and keyed by meeting instance, so they suit a wide-column store. Recordings are files in object storage.
Chat and recording files hang off the meeting instance:
The meeting table, with the fields the join path needs:
CREATE TABLE meeting (
meeting_id BIGINT PRIMARY KEY, -- 10-11 digits, random, not sequential
account_id BIGINT NOT NULL,
host_user_id BIGINT NOT NULL,
passcode_hash BYTEA, -- never store the passcode itself
waiting_room BOOLEAN NOT NULL DEFAULT TRUE,
e2ee BOOLEAN NOT NULL DEFAULT FALSE,
allowed_regions TEXT[] NOT NULL, -- data residency
recurrence JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX meeting_by_host ON meeting (host_user_id, created_at DESC);
-- Wide-column table for chat, partitioned by meeting instance:
-- PRIMARY KEY ((instance_id), seq)Where each kind of data lives:
| Data | Store | Why |
|---|---|---|
| Accounts, meetings, settings, recordings metadata | Sharded relational database (PostgreSQL or MySQL with Vitess) | Relationships, transactions for settings and billing, moderate volume |
| Live meeting state (roster, roles, mute flags, seq) | Memory on the owning signalling server, replicated to Redis | Microsecond access, millions of updates per second, lost state rebuildable from clients |
| Media server load and assignments | In-memory placement service backed by etcd or a similar store | Small, strongly consistent, changes every second |
| Chat history and participant events | Wide-column store (Cassandra or similar) keyed by instance | Append-only, partitioned by meeting, time-ordered |
| Recordings, transcripts | Object storage with lifecycle rules | Large immutable files, cheap tiers, presigned downloads |
| Call quality telemetry | Event stream into an analytics store (ClickHouse, BigQuery) | Billions of rows, aggregate queries |
See Choosing a Database: A Decision Guide for the reasoning behind each choice.
Deep Dives#
1. WebRTC connectivity: NATs, ICE, STUN and TURN#
The problem. Two laptops on two home networks both have private addresses like 192.168.1.20. Neither can send a packet to the other's private address, and each home router only lets packets in if they answer something sent out. Corporate firewalls may block UDP entirely or allow only ports 80 and 443. Mobile networks put thousands of phones behind one carrier-grade NAT. Before any media can flow, the two ends (or a client and a media server) must find a path that works.
How NATs behave. When a device sends a UDP packet out, the NAT creates a mapping from (private address, private port) to (public address, public port). Two properties matter:
- Mapping behaviour. "Endpoint-independent" NATs reuse the same public port for every destination. "Address- or port-dependent" NATs (often called symmetric NATs) give a different public port for each destination, so the port a STUN server sees is not the port a peer would see.
- Filtering behaviour. Some NATs accept packets from any outside address once a mapping exists; others only accept packets from addresses the device has already sent to.
With endpoint-independent mapping, two peers can usually connect directly with hole punching: each learns its public address from STUN, they exchange addresses through signalling, and both send packets to each other at the same time, which opens mappings on both NATs. With symmetric NATs on both sides, hole punching usually fails and a relay is needed.
STUN (RFC 8489). A client sends a Binding request to a STUN server on the public internet. The server replies with the source address and port it saw, which is the client's server-reflexive address. STUN is tiny and stateless, so a STUN server can handle huge request rates.
TURN (RFC 8656). When no direct path works, the client asks a TURN server for an allocation: a relay address on the server. Packets sent to the relay address are forwarded to the client, and the client sends packets to peers through the server. Details from the RFC that matter for capacity and design:
- The default allocation lifetime is 10 minutes; clients must refresh it before then, or delete it with a lifetime of zero.
- Permissions (which peer addresses may send to the relay) last 5 minutes and must be refreshed.
- The default port is 3478 for UDP and TCP, and 5349 for TURN over TLS or DTLS. Running TURN over TLS on port 443 gets through most firewalls, because it looks like ordinary HTTPS.
- TURN servers need credentials, otherwise they become free open relays. Use short-lived credentials minted per session by the service (an HMAC of an expiry time and user ID with a shared secret is a common scheme).
TURN is expensive: every byte passes through the server twice (in and out), and TCP-wrapped media suffers from head-of-line blocking. Losing one TCP segment delays everything behind it. That is why relays are the last resort.
ICE (RFC 8445). ICE ties it together.
- Gather candidates. Each side collects host candidates (its own interface addresses), server-reflexive candidates (from STUN) and relayed candidates (from TURN). A browser may also discover peer-reflexive candidates during checks.
- Prioritise. Each candidate gets a priority from its type, its local preference and its component. The formula is 2²⁴ × type preference + 2⁸ × local preference + (256 − component ID), with recommended type preferences of 126 for host, 110 for peer-reflexive, 100 for server-reflexive and 0 for relayed. Relayed candidates are therefore tried last.
- Pair and check. Local and remote candidates are paired. The pair priority is 2³² × min(G, D) + 2 × max(G, D) + (1 if G > D else 0), where G and D are the two sides' candidate priorities, so both sides sort pairs in the same order. A STUN Binding request is sent on each pair, paced by a timer Ta, 50 ms by default in RFC 8445.
- Nominate. The controlling side picks a working pair (regular nomination in RFC 8445; RFC 5245's "aggressive nomination" is no longer allowed in the new version).
- Keep alive. The pair is kept open with periodic packets, because NAT mappings expire after tens of seconds to minutes without traffic. WebRTC also uses consent checks so that one side cannot keep blasting media at an address that no longer wants it.
Trickle ICE sends candidates through signalling as soon as each is found, rather than waiting for all of them. Host candidates are available in microseconds, STUN in one round trip, TURN in two; trickling lets checks on fast candidates start before slow ones arrive, saving hundreds of milliseconds at join.
ICE with an SFU is simpler. When the other end is a media server with a public IP address, the server does not need STUN or TURN for itself. It offers its public address as a host candidate (often with "ICE lite", a simplified ICE where the server only responds to checks). The client's server-reflexive address is learned by the server from the first check. Most clients connect on the first try over UDP. For the rest:
- Try UDP to the SFU on a well-known port.
- Then TCP to the SFU on port 443.
- Then TLS on 443 through a TURN-style relay, or through an HTTP proxy if the corporate network forces one.
The newsletter summary of Zoom's architecture notes that Zoom uses UDP for media with TCP, HTTP and HTTPS as fallbacks, which follows this order.
ICE restart. When a phone moves from Wi-Fi to mobile data, its address changes and the selected pair dies. The client gathers new candidates and does an ICE restart over the existing signalling channel. The DTLS session can often be kept, so media resumes in a round trip or two.
Operations lessons.
- Run STUN and TURN in every region, close to users. A TURN relay on another continent adds its round trip to every packet.
- Watch the share of relayed sessions per network (corporate customers often have far higher rates). A sudden rise usually means a firewall or ISP change somewhere.
- Use anycast or DNS steering for STUN/TURN addresses, and issue credentials with lifetimes of minutes to hours.
- Expect UDP blocked cases in enterprises, schools and hotels. A "works on TCP 443" test in the client's pre-join screen catches them early.
2. Topologies: mesh, SFU and MCU#
RFC 7667 catalogues RTP topologies. Three matter for conferencing: mesh (every participant sends to every other), the selective forwarding middlebox (the SFU), and the media-mixing mixer (the MCU).
Mesh. Each of N participants sends its stream directly to the N − 1 others and receives N − 1 streams.
- Upload per participant = (N − 1) × bitrate. At 1 Mbps per video stream and N = 6, each person uploads 5 Mbps and encodes 5 times (or encodes once and encrypts 5 times, with no per-receiver adaptation).
- Works for 2–4 people, needs no media servers, and gives the lowest latency (one network hop). Fails badly beyond that, especially on home uplinks of 5–20 Mbps and mobile devices with weak CPUs.
MCU. Each participant sends one stream to the server; the server decodes all of them, composes a single layout and mixes the audio, then encodes one output per participant (or per layout).
- Upload and download per participant = one stream each. Excellent for weak clients and legacy room systems (SIP and H.323 endpoints) that can decode only one stream.
- The server does heavy work: decoding N streams and encoding up to N outputs. Each 720p encode needs a CPU core or a hardware encoder. Mixing also adds a few frames of delay (often 50–200 ms) and forces a single layout on everyone.
- Cost grows with N × resolution, so MCUs are expensive to scale.
SFU. Each participant sends one set of tracks (with simulcast or SVC layers) to the server. The server forwards selected tracks to each receiver without decoding.
- Upload per participant: one set of layers (for example 1.65 Mbps). Download: only what that receiver shows.
- Server work per packet: SRTP decrypt, choose, rewrite header, SRTP encrypt, send. No codec work. One server can handle hundreds to thousands of participants, depending on how many streams each receives.
- Each receiver can have its own layout and quality.
- Receivers must decode several streams (for example 9 or 25 tiles), which costs client CPU and battery; layer selection keeps tiles small.
Bandwidth comparison for a meeting of N participants, each video at about 1 Mbps.
| Topology | Upload per client | Download per client | Server work |
|---|---|---|---|
| Mesh | (N − 1) × 1 Mbps | (N − 1) × 1 Mbps | None |
| SFU | about 1.6 Mbps (simulcast) | sum of shown streams (e.g., 1 large + 8 small ≈ 2 Mbps) | Forwarding: O(N × streams shown) packets |
| MCU | 1 Mbps | 1 Mbps | Decode N, compose, encode up to N |
For N = 10, mesh needs 9 Mbps up and down per client; the SFU needs 1.6 Mbps up and about 2 Mbps down; the MCU needs 1 Mbps each way but about 10 decodes and up to 10 encodes on the server.
Why the industry converged on SFUs. Zoom, Google Meet, Microsoft Teams, Discord, and open-source servers such as Jitsi Videobridge, mediasoup, Janus and LiveKit all use selective forwarding as the main model. The newsletter summary of Zoom says its servers route streams rather than process them, sending each participant's streams separately and letting clients decode, which is the SFU model. The reasons:
- CPU cost. Forwarding is cheap compared with decoding and encoding video.
- Latency. No decode, mix or encode stage on the server.
- Flexibility. Each receiver chooses its own layout.
- End-to-end encryption is possible, because the SFU does not need to read the media (Deep Dive 11). An MCU must decrypt everything to mix it.
Where mixing still wins.
- Audio in big meetings. Forwarding 50 audio streams to everyone is wasteful when only 1–3 people speak. SFUs forward only the loudest few speakers (Deep Dive 7). Some systems mix audio on the server for very large calls or for phone dial-in.
- Phone and room-system gateways. A PSTN caller needs one mixed audio stream. A legacy room system may need one composed video. These are MCU-style gateways at the edge of an SFU system.
- Recording and broadcasting need one composed output, done by a composer (Deep Dive 10).
Hybrids. A real system uses several topologies:
- Peer-to-peer for two people when the network allows, switching to the SFU when a third person joins. This saves server bandwidth for the very common 1:1 call, at the cost of a switch-over glitch.
- SFU for the meeting, with cascading across regions for distributed meetings.
- MCU-style gateways for phones and legacy rooms, and composers for recording and streaming.
3. Simulcast and SVC: one sender, many receivers#
The problem. In a 20-person meeting, one receiver is on fibre with a large screen and another is on a train with a weak 3G signal. Both want to see the same speaker. If the speaker sends one 720p stream at 1.2 Mbps, the train passenger cannot receive it. If the speaker sends 180p for everyone, the fibre user sees a blurry picture. Transcoding on the server for each receiver would bring back MCU costs.
Simulcast. The sender encodes the camera several times at different resolutions and bitrates and sends all of them:
| Layer (RID) | Resolution | Frame rate | Bitrate |
|---|---|---|---|
| f (full) | 1280 × 720 | 30 | 1.2–1.5 Mbps |
| h (half) | 640 × 360 | 30 | 300–500 kbps |
| q (quarter) | 320 × 180 | 15 | 80–150 kbps |
- The SFU picks one layer per receiver per sender, based on the receiver's bandwidth estimate and the tile size it is showing. Sending 720p to a 180p thumbnail wastes bandwidth and client CPU.
- Cost to the sender: about 1.4× the upload of the top layer alone, and three encodes. Modern phones and laptops handle this, often with hardware encoders.
- Switching layers requires a keyframe on the new layer, because frames in one layer depend only on earlier frames in that layer. The SFU asks for one (an RTCP PLI or FIR message). Keyframes are 5–10× larger than other frames, so frequent switching creates bursts, and SFUs add hysteresis (for example, only switch up after bandwidth has been stable for several seconds).
- Senders pause unused layers. If no receiver needs the 720p layer (for example everyone has the person as a thumbnail), the SFU tells the sender, which stops encoding it, saving upload and battery.
- Rewriting for continuity. Each layer has its own RTP sequence numbers and timestamps. When the SFU switches a receiver from h to f, it rewrites sequence numbers and timestamps so the receiver's decoder sees one continuous stream.
SVC (scalable video coding). Instead of separate encodings, the encoder produces one layered stream:
- Temporal layers: frames are arranged so that dropping the top layer halves the frame rate without breaking decoding. For example, with three temporal layers at 30 fps, layer 0 is 7.5 fps, layers 0–1 are 15 fps, and all three are 30 fps.
- Spatial layers: a base layer at low resolution and enhancement layers that add detail, each predicted from the layer below.
- A mode like L3T3 in VP9 or AV1 means 3 spatial × 3 temporal layers.
SVC benefits:
- No keyframe needed to go down. The SFU just stops forwarding upper layers. Going up may still need a keyframe for the higher spatial layer, depending on the structure.
- One encode on the sender, although SVC encoding costs more than a single-layer encode, and the total bitrate is a little higher than single-layer coding at the top quality (often quoted around 10–30% overhead).
- Finer adaptation: the SFU can choose frame rate and resolution independently.
The newsletter summary of Zoom's architecture describes Zoom's use of SVC: one stream with hierarchical layers, from which each client gets the layers that match its device and network. Zoom's codec is proprietary, so details are not public.
Codec support. H.264 is supported everywhere and has hardware encoders, but has limited SVC support in browsers, so it is used with simulcast. VP8 supports temporal layers with simulcast. VP9 and AV1 support full SVC in Chromium-based browsers. AV1 gives the best compression (roughly 30% fewer bits than VP9 at the same quality) but costs more CPU to encode; it is especially attractive for screen content and low-bandwidth users.
How the SFU picks layers: an allocation problem. For each receiver, the SFU has:
- a bandwidth estimate B (Deep Dive 4);
- a list of tracks the receiver wants, each with a priority and a maximum resolution (screen share > active speaker > recent speakers > other tiles);
- the available layers for each track and their current bitrates.
A simple greedy allocator:
allocate(receiver):
budget = receiver.bandwidth_estimate * 0.9 # keep headroom
budget -= sum(audio bitrates of forwarded speakers) # audio first, always
for track in receiver.subscriptions sorted by priority:
track.layer = lowest available layer # everyone gets something
budget -= track.layer.bitrate
for track in receiver.subscriptions sorted by priority:
while track.next_layer exists and
track.next_layer <= track.max_resolution and
budget >= track.next_layer.bitrate - track.layer.bitrate:
budget -= track.next_layer.bitrate - track.layer.bitrate
track.layer = track.next_layer
if budget < 0: pause lowest-priority video tracks until budget >= 0Real allocators add hysteresis, smooth changes over time, and account for the burst cost of a keyframe when switching up.
Trade-offs: simulcast versus SVC.
| Aspect | Simulcast | SVC |
|---|---|---|
| Sender CPU | Several independent encodes | One layered encode, more complex |
| Sender upload | Sum of layers (about 1.4× top layer) | About 1.1–1.3× a single stream |
| Switching down | Needs a keyframe on the lower layer | Just drop upper layers |
| Codec support | All codecs, including H.264 with hardware encoders | VP9, AV1 (and proprietary codecs) |
| Robustness | Losing a layer's packets affects only that layer | Loss in the base layer affects all layers |
| SFU complexity | Choose a stream, rewrite headers | Parse layer descriptors, drop packets by layer |
4. Bandwidth estimation, congestion control and loss recovery#
Why the media plane needs its own congestion control. TCP's congestion control reacts to packet loss and fills queues until loss happens, which adds hundreds of ms of queuing delay on a home router. That is fine for downloads but fatal for conversation. Real-time media uses UDP and its own controller, which tries to keep queues almost empty by reacting to delay before loss occurs.
Google Congestion Control (GCC). Described by Holmer and colleagues in the IETF RMCAT draft "A Google Congestion Control Algorithm for Real-Time Communication", it is the controller in libwebrtc, which Chrome and many native apps use. It has two parts:
- Delay-based controller. It compares the gaps between packet send times with the gaps between their arrival times. If packets arrive more and more spread out, a queue is building at the bottleneck. A filter (originally a Kalman filter, later a trend-line estimator in implementations) estimates this delay gradient m(i). An over-use detector compares m(i) with an adaptive threshold (initially 12.5 ms in the draft) and signals over-use only after it has lasted at least 10 ms. A small state machine (Increase, Hold, Decrease) then controls the rate:
- In Increase, the estimate grows multiplicatively by at most 8% per second when far from the last congestion point, and additively (about half a packet per round trip plus 100 ms) when close to it.
- On over-use, the estimate is cut to a fraction (commonly 0.85) of the measured incoming rate.
- The threshold itself adapts, which keeps the controller from being starved by competing TCP flows.
- Loss-based controller. Roughly: if loss is above 10%, reduce the rate in proportion to the loss; if it is below 2%, allow increases; in between, hold. The final estimate is the minimum of the delay-based and loss-based estimates.
Modern implementations run the estimator on the sender using transport-wide congestion control feedback: every packet carries a transport-wide sequence number in an RTP header extension, and the receiver reports arrival times for each one. The sender (or the SFU, for its downstream legs) then runs the estimator with full information. An older approach, REMB, had the receiver compute the estimate and send just a number.
Where estimation happens in an SFU design. There are two independent legs per stream:
- Sender → SFU (uplink). The sender's estimator decides how many simulcast layers it can afford and at what bitrates.
- SFU → each receiver (downlink). The SFU runs an estimator per receiver and allocates layers within it (Deep Dive 3). This is the key benefit: one slow receiver never slows down the sender or other receivers.
Loss recovery: four tools.
| Tool | How it works | Cost | Best for |
|---|---|---|---|
| NACK and retransmission (RTX) | Receiver reports missing sequence numbers; sender or SFU resends | One round trip of delay | Short round trips (under about 100 ms) |
| Forward error correction (FlexFEC, ULPFEC) | Send parity packets so lost packets can be rebuilt | 10–50% extra bandwidth | Random loss, long round trips |
| Opus in-band FEC and RED | Audio packets carry a low-bitrate copy of the previous frame (FEC) or full redundant copies (RED) | Small for audio | Audio under loss, which is the priority |
| Keyframe request (PLI) | Ask the sender for a fresh keyframe | A large frame | Recovery when too much is lost |
The SFU keeps a short history (about 1 second) of packets it has forwarded to each receiver. When a receiver NACKs, the SFU retransmits from its buffer, so the repair crosses only the receiver's last-mile link. This is another reason for nearby servers: a 20 ms round trip to the SFU allows retransmission within the latency budget; a 200 ms round trip to a distant one does not.
The jitter buffer. The receiver holds packets for a short, adaptive time to absorb arrival variation and to give retransmissions a chance. Too short, and late packets are lost; too long, and delay grows. Adaptive buffers in WebRTC typically settle at 20–80 ms on good networks and grow to 200 ms or more on bad ones. Audio buffers also use time stretching (playing slightly faster or slower without changing pitch) to catch up after a burst, and packet loss concealment to fill gaps with synthesised audio.
A mouth-to-ear latency budget (same region).
| Stage | Typical time |
|---|---|
| Audio capture and processing (echo cancellation, noise suppression) | 10–20 ms |
| Encoding (Opus, 20 ms frames) | 20–25 ms |
| Network: client → SFU | 10–30 ms |
| SFU forwarding | under 1 ms |
| Network: SFU → client | 10–30 ms |
| Jitter buffer | 20–60 ms |
| Decode and playout | 10–20 ms |
| Total | about 80–185 ms |
Across continents, add 100–150 ms of propagation for the long-haul leg, which is why cross-region meetings feel slower even when everything else is perfect.
Audio always comes first. Humans tolerate frozen video far better than broken audio. Rules that follow:
- Audio is never paused for bandwidth; video is paused first.
- Audio packets are prioritised in the SFU's send queue and paced separately from video bursts.
- Opus can drop to 10–16 kbps and still sound intelligible, with in-band FEC on lossy links.
- Discontinuous transmission (DTX): when someone is silent, Opus sends very few packets (one every 400 ms or so), saving bandwidth and SFU work for the many muted or silent participants.
5. Signalling: meeting state, ordering and scale#
What signalling does. WebRTC deliberately does not define signalling; each service designs its own. Ours carries:
- session setup: the offer and answer (SDP) or a compact equivalent, ICE candidates, DTLS fingerprints;
- the roster and each participant's state (joined, waiting room, muted, video on, sharing, hand raised, in breakout room 3);
- subscriptions: which tracks each client wants and at what size;
- host actions, chat, reactions, captions, active speaker changes, recording status.
One owner per meeting. Meeting state changes many times per second in a busy meeting, and the order matters ("unmute" then "mute" is not "mute" then "unmute"). The simplest correct design is a single owner for each meeting's state: one signalling process holds it in memory, applies changes in order, assigns sequence numbers and broadcasts them.
How participants on other servers reach that owner is the same routing problem a chat system has when users connect to many servers:
- Naive load balancing does not work. If each client connects to a random signalling server, a host's "mute X" arrives at a server that does not hold X's connection.
- Consistent hashing of meetings to servers. Hash the meeting ID onto a ring of signalling servers. The client is told to connect directly to the owner. All participants of a meeting then share one server, so fan-out is local and ordering is trivial. A registry (ZooKeeper or etcd) holds the ring membership. Trade-offs: adding or removing servers moves meetings, so connections must be drained and clients reconnected gradually to avoid a thundering herd; and during a move, events must reach both the old and new owner. See Consistent Hashing and ZooKeeper and etcd.
- Edge connections plus a pub/sub backbone. Clients connect to any nearby edge server, which subscribes to a channel for the meeting on a pub/sub system (for example sharded Redis pub/sub) and forwards messages. The meeting's owner publishes ordered updates on the channel. This decouples connections from ownership, at the cost of an extra hop and at-most-once delivery from the pub/sub layer, which the sequence numbers repair. See Pattern: Pushing Realtime Updates and Pub/Sub and Event Streaming.
For meetings up to a few hundred people, assigning the whole meeting to one server (the consistent-hashing design) is simple and efficient. For very large meetings and webinars, edge servers with a backbone are better, because one server cannot hold 10,000 connections for one meeting and also serve its other meetings fairly.
Ordering and gap repair. Every update from the owner carries seq, which increases by one per meeting. A client that sees seq 501 after 499 knows it missed 500 and asks for it (or for a fresh snapshot). On reconnect, the client sends its last seq; the server replays from a short in-memory log (say the last 1,000 updates) or sends a full snapshot if the gap is too old. This is cheaper and more robust than trying to guarantee delivery of every message on every path. A client can piggyback "my last seq" on its keepalives, so the server notices silent gaps quickly.
Liveness. TCP alone can take minutes to notice a dead connection. The signalling protocol uses application-level heartbeats every 5–10 seconds in each direction. Missing two or three means the connection is presumed dead. The server then marks the participant "reconnecting" (not "left") for a grace period, so a brief network change does not show everyone a leave and rejoin. See Heartbeats, Failure Detection and Gossip.
Failover of the owner. If the server owning a meeting dies, the meeting's state must survive:
- The owner writes each state change (or a snapshot every few seconds plus a log) to a replicated store such as Redis with replicas.
- A new owner is chosen by the registry, loads the state, and increments an epoch number. Clients reconnect, and messages from the old epoch are rejected, preventing a "zombie" owner that was only partitioned from applying changes.
- Anything lost (for example a hand raise in the last 100 ms) is rebuilt from clients, which re-announce their own state on reconnect.
Join storms. At 9:00 many meetings start at once. The join path must avoid shared hot spots: the token is checked locally, placement decisions are cached, and meeting records are read from replicas. Admission control on the placement service returns "retry in 1 second" rather than collapsing when a region is saturated.
Size of the signalling tier. With 25 M concurrent participants and about 60,000 WebSockets per server, about 400 servers. CPU is spent mostly on TLS and on fan-out: a single active-speaker change in a 1,000-person meeting is 1,000 messages. Batching small updates (for example sending roster changes at most every 200 ms in big meetings) cuts this sharply.
6. Global media server placement#
Why placement decides quality. Light in fibre travels about 200 km per millisecond, and real routes are longer than straight lines. London to Frankfurt is about 15 ms round trip; London to Singapore is about 160–180 ms round trip. If a meeting of Londoners is hosted in Singapore, every packet makes that trip twice, and the budget is gone before encoding starts.
The structure. Media servers are grouped into zones, each a set of servers in one data centre or region. The newsletter summary of Zoom's architecture describes this as meeting zones, each with a zone controller that manages activity within the zone, and says clients connect to the nearest data centre. Zoom has its own co-located data centres and also uses public cloud capacity (the summary mentions AWS). A generic version:
Choosing the zone for a participant.
- Where is the client? GeoDNS or anycast sends the client to a nearby edge for its first API call. The client can also probe a few candidate zones (a small UDP ping to each) and report round-trip times. Probes are more accurate than IP geolocation, especially for VPN users.
- Which zones are allowed? Data residency rules from the account (for example "EU only") filter the list. Wikipedia's article on Zoom notes that, after its 2020 security review, Zoom gave users the ability to choose which data centres their calls are routed through.
- Which have capacity? The zone controller knows the load on each server and gives a server with spare capacity in CPU, packets per second and NIC bandwidth.
Choosing the server for a meeting. All participants in one zone should be on the same SFU where possible, so their streams are forwarded inside one process. The zone controller places a new meeting on a server with headroom for the meeting's expected size (from the schedule or past instances of a recurring meeting). If the meeting grows past one server's capacity, it spills to a second server in the zone, linked by a fast local cascade.
Cascading across zones. If the meeting has participants in Frankfurt and Singapore:
- Each zone gets its own SFU node for the meeting. Each participant connects locally.
- The SFUs are connected by server-to-server links. Each stream crosses each long link once.
- Each SFU forwards only what the other side needs. If nobody in Singapore displays a Frankfurt participant at 720p, the link carries 180p.
- Loss repair happens per hop: a NACK from a Singapore receiver is answered by the Singapore SFU from its buffer, not by the sender in Frankfurt.
- The long links can run over a private backbone with better loss and jitter than the public internet.
With many zones, the cascade becomes a tree or a mesh of SFUs per meeting. A meeting spread over 5 continents might have 5 SFU nodes, each linked to the others (a full mesh of 5 nodes is 10 links), or in a star around the zone with most participants.
Moving a meeting. If the first joiner was the only person in Frankfurt and 50 people then join from Virginia, the meeting's "home" should move to Virginia. Hosting decisions are revisited as participants join, and new participants connect to the best zone even if the meeting started elsewhere.
Capacity planning for zones. Each zone is sized for its local peak plus failover from a neighbouring zone. Business-hour peaks move around the globe, so zones in different time zones can lend capacity through cascading, at a latency cost. In March and April 2020, demand for conferencing grew many times over in weeks. Zoom added public cloud capacity to cope; a large deal with Oracle Cloud was widely reported in April 2020. The architectural lesson is that the media tier must run on both owned and rented servers, with the same software and placement logic.
7. Scaling large meetings and webinars#
Why large meetings are different. Forwarding cost in an SFU grows with the number of (receiver, stream) pairs. In a meeting of N people where everyone receives everyone, that is N × (N − 1) streams: about 90 for N = 10, but nearly 1 million for N = 1,000. No client can display or decode 999 videos anyway. Large meetings are therefore about sending each person much less than everything.
Audio: forward only the loudest speakers. Each client includes its audio level in every audio packet (an RTP header extension defined in RFC 6464), so the SFU can see who is speaking without decoding. The SFU:
- ranks participants by recent audio level, with smoothing so a cough does not steal the floor;
- forwards only the top 3 (or so) speakers to each receiver, and drops other audio packets (most are DTX silence anyway);
- tells clients who the active speaker is, so they can enlarge that video.
In a 1,000-person meeting this reduces audio from 999 streams per receiver to 3. Clients mix the 3 streams locally.
Video: last-N and pagination. Each receiver subscribes to a limited set of videos:
- Active speaker view: 1 large video plus a strip of 4–6 thumbnails.
- Gallery view: a page of up to 25 or 49 tiles at small resolution (180p or lower, sometimes at reduced frame rate). Scrolling to the next page changes subscriptions.
- Last-N: subscribe automatically to the N most recent speakers, so the people talking are on screen without manual paging.
The SFU only forwards subscribed tracks, and senders whose video nobody watches at high quality pause those layers. In a 1,000-person meeting, perhaps 50 people's video is being watched at any time, and only a few at high resolution.
Cost of a 1,000-person meeting. Say each receiver gets 3 audio streams (120 kbps) and 25 thumbnails at 100 kbps (2.5 Mbps), plus one speaker at 720p (1.2 Mbps): about 3.8 Mbps × 1,000 = 3.8 Gbps of egress, and roughly 400,000 packets per second. That is too much for one SFU process to do comfortably alongside other meetings, so the meeting spans several SFUs in a cluster:
Each stream travels once from its sender to the root (or between SFUs that need it) and is then fanned out by each edge SFU to its own participants. Edge SFUs subscribe upstream only to streams that at least one of their participants wants, so the internal links carry far less than the full set.
Signalling also needs care. A roster of 1,000 participants is about 200 KB. Sending the whole roster on every join would mean 1,000 joins × 1,000 receivers × 200 KB, which is 200 GB of signalling for the join wave. Instead:
- send the roster once on join, then deltas with sequence numbers;
- batch roster deltas every 200–500 ms in large meetings;
- page the participant list in the client UI and fetch details lazily;
- rate-limit reactions and aggregate them ("👏 × 120") rather than broadcasting each one.
Webinars: separate speakers from the audience. A webinar has a small set of panellists (interactive, like a normal meeting) and a large audience of attendees who only receive, plus chat, Q&A and raised hands.
- Attendees do not publish media, so the SFU tree is purely fan-out: root SFU → regional SFUs → attendees. Each attendee receives perhaps 2–3 Mbps (speaker, screen share, mixed or top-speaker audio).
- 10,000 attendees × 2.5 Mbps = 25 Gbps, spread over a few dozen SFUs in several regions. Latency stays under a second.
- Promoting an attendee to a panellist (to ask a question live) just changes their role, and their client starts publishing.
Beyond tens of thousands: switch to broadcast. For 100,000+ viewers (a company all-hands or a public event), real-time forwarding to every viewer is wasteful. A composer joins as a hidden participant, renders the meeting layout into one video, and sends it to a live streaming pipeline:
- transcode into an adaptive bitrate ladder;
- package as low-latency HLS or DASH with short segments (or chunked CMAF parts), giving 2–5 seconds of delay;
- deliver through CDNs, exactly as in the case study Design a Video Streaming Platform (YouTube / Netflix).
Interactivity for viewers then moves to chat and Q&A, which is a fan-out problem like the case study Design Live Comments (Facebook Live).
Interactive meeting vs webinar vs broadcast.
| Mode | Audience | Latency | Media path | Cost per viewer |
|---|---|---|---|---|
| Meeting | Up to about 1,000, everyone may speak | 100–300 ms | SFU mesh or cascade | Highest (per-receiver adaptation) |
| Webinar | Panellists plus up to tens of thousands of view-only attendees | Under 1 s | SFU fan-out tree | Medium |
| Live stream | Unlimited | 2–30 s | Composer → packager → CDN | Lowest (cacheable segments) |
Breakout rooms. A host splits a meeting into rooms. Each room is a sub-meeting with its own roster and media routing, but on the same SFU (or cluster) as the main meeting, so moving people between rooms only changes forwarding rules, without new ICE or DTLS handshakes. The signalling owner holds the room assignments. When rooms close, everyone is returned to the main room in one state change.
8. Screen sharing#
Screen content is not camera content. A camera shows natural scenes with soft edges and constant motion. A screen shows sharp text, flat colours and long periods with no change, followed by sudden large changes (switching slides) or small areas of motion (a cursor or a video playing in one window). Encoding screens like cameras gives blurry text.
Encoding choices.
- Resolution over frame rate. Send the screen at native resolution (1080p or higher) and 5–15 fps, rather than 720p at 30 fps. Text needs pixels; slides do not need motion.
- Screen-content coding tools. AV1 and HEVC have tools for screen content (palette mode, intra block copy) that compress text and repeated patterns much better. VP9 and H.264 have encoder tuning for "text" or "detail". The WebRTC API lets the app hint the content type (
contentHint = "detail"or"text"). - Variable frame rate. When nothing changes, send almost nothing; when a slide changes, send a large frame. The bitrate is bursty: often under 100 kbps when static and several Mbps on a change.
- Motion mode. If the sharer plays a video, switch to motion mode (higher frame rate, lower resolution), either by user choice ("optimise for video clip") or by detecting motion.
Delivery.
- Screen share is a separate track with high priority in the SFU's allocator: after audio, before cameras. When someone shares, receivers typically see the screen large and cameras as small thumbnails, so the camera layers drop automatically.
- Weak receivers get a lower frame rate (SVC temporal layers, or simulcast of the screen at a lower resolution) rather than unreadable text.
- Keyframes are expensive for screens (a full 4K screenshot can be hundreds of KB), so late joiners and recovering receivers can cause bursts. The SFU can rate-limit keyframe requests to the sharer (for example at most one per second) and serve recovery from a cached recent keyframe if the codec allows.
Sharing computer audio. Capturing system audio (a video's soundtrack) adds a second audio track. Echo cancellation must know about it, otherwise the sharer's microphone picks up the same sound from the speakers.
Multiple sharers and annotation. Some products allow several people to share at once; each share is a track, and receivers choose. Annotation (drawing on a shared screen) goes through signalling or a data channel as small vector events, rendered on each client as an overlay, not burned into the video. This keeps it sharp and makes it cheap. Ordering of annotation strokes uses the meeting sequence numbers; concurrent editing of a shared whiteboard is a collaborative-editing problem (see Conflict Resolution, OT and CRDTs).
Remote control. Letting a viewer control the sharer's screen sends input events (mouse, keyboard) back to the sharer over a data channel. This needs an explicit grant from the sharer, a clear on-screen indicator, and an immediate way to take control back.
Privacy pitfalls. Sharers accidentally show notifications, other windows or passwords. Clients offer "share a window" instead of the whole screen, and some hide notifications during a share. On the server side, nothing changes: the SFU forwards encrypted packets without inspecting content.
9. In-meeting chat, reactions, captions and attachments#
Requirements for chat in a meeting. Messages to everyone or to one person, delivered in under a second, in the same order for everyone, visible to people who join late, saved with the recording if one is made, and (depending on settings) kept after the meeting in a persistent chat channel.
Which channel carries chat?
| Option | How | Pros | Cons |
|---|---|---|---|
| Signalling WebSocket | Client sends to the meeting owner, which sequences and fans out | One ordered stream with roster and host actions; easy to store | Adds load to signalling servers |
| WebRTC data channel to the SFU | SCTP over DTLS on the media connection | Low latency, no extra connection | Ordering and storage must be added; SFU becomes stateful for chat |
| Separate chat service | Like a chat system, with the meeting as a group | Reuses persistent chat infrastructure | Another connection and service on the join path |
Using the signalling channel is the common, simple choice: the meeting owner already orders events, so chat messages get sequence numbers in the same stream as "X joined" and "Y was muted". Everyone sees a consistent history. The owner appends each message to the chat store (keyed by meeting instance and seq) and fans it out.
Idempotent sends. The client attaches a client_msg_id. If the connection drops after sending, the client resends after reconnecting, and the owner ignores the duplicate. The client shows a "sending" state until the message comes back with a seq.
Private messages are sequenced in the same stream but delivered only to the sender and recipient. Host settings ("attendees may chat with the host only") are enforced by the owner, not the client.
Late joiners fetch recent history from the chat store on join, then follow the live stream from the seq the history ended at. The overlap between "history up to seq 812" and "live from seq 800" is removed by seq, so no message appears twice.
Reactions and raised hands are tiny state changes. Raised hands are part of meeting state (ordered, persistent for the meeting). Emoji reactions are ephemeral and, in large meetings, aggregated: the owner counts reactions over 500 ms windows and broadcasts totals, so 1,000 people clapping costs a few messages, not a million.
Attachments. Sending a file through the chat should never push bytes through the signalling server:
- Bad: send the file over the WebSocket and store it in the chat database. Databases are not built for large blobs, and signalling bandwidth is wasted.
- Better: the signalling server accepts the file and uploads it to object storage. It still carries every byte.
- Best: the client asks for an upload target and gets a presigned URL, uploads directly to object storage, then sends a chat message containing only the file reference. Recipients download with their own short-lived presigned URLs. Files can expire with the meeting's retention. See Pattern: Handling Large Files and Blobs.
Captions and transcripts. Live captions need speech recognition on each speaker's audio:
- A transcriber joins like the recorder and receives audio streams, ideally per speaker (separate tracks make attribution easy, unlike a mixed recording).
- It runs streaming speech recognition, producing partial results every few hundred ms and final results at pauses.
- Captions are sent to clients as small timed text events through signalling, and saved for the transcript.
- Translation adds a second step per target language.
GPU-based recognition at scale is its own capacity problem: if 10% of 25 M concurrent participants have captions on and 1 in 5 is speaking at any time, that is about 500,000 concurrent audio streams to transcribe. Only speaking streams need processing, which DTX and voice activity detection reveal for free.
Persistent chat after the meeting. Some products link the meeting to a persistent team channel. Then in-meeting chat is written to that channel and follows the delivery, storage and offline rules of the case study Design a Chat System (WhatsApp).
10. Recording#
Two kinds of recording.
- Local recording: the client records what it receives to disk. No server cost, but it depends on that client's network and CPU, captures only that person's view, and leaves the file on one laptop.
- Cloud recording: the service records on the server and makes the file available to the host. This is the version to design.
Where to capture. The recorder should get the best available quality of every stream, not one receiver's degraded view. It runs inside the data centre, close to the SFU, with a fast link. It subscribes like a client:
- all audio streams (not just the top 3 speakers), so nothing is lost;
- the screen share at full quality;
- the active speaker at high quality, other cameras at the size the chosen layout needs.
The recorder can work in two ways:
| Approach | How | Pros | Cons |
|---|---|---|---|
| Composite in real time | Recorder decodes, composes the layout, encodes one MP4 as the meeting runs | File ready minutes after the meeting ends | Needs a CPU or GPU encoder per recorded meeting for the whole meeting |
| Raw capture then compose later | Recorder writes each track's RTP payloads (already encoded) to files, plus an event log | Very cheap during the meeting (just writes); layouts can be chosen later | Processing after the meeting, so the file is ready later; must handle layer switches and packet loss in raw tracks |
Raw capture is attractive at scale: during the meeting, it costs roughly the same as forwarding to one more client. Processing can run on cheaper batch capacity, and different outputs (speaker view, gallery view, audio only, separate audio per speaker for editing) can be made from the same raw files.
Writing safely. Recordings are large (hundreds of MB per hour) and must not be lost if a recorder dies:
- Write in chunks (for example every 10 seconds) using multipart upload to object storage, so at most one chunk is at risk.
- Run the recorder with a standby: if the primary stops sending chunks, the standby joins and continues. The gap is recorded in the event log.
- Record the event log (who joined, who spoke when, layout changes, chat, screen share start and stop) with timestamps in a common clock, so the composer can rebuild the meeting.
Processing pipeline.
- Timestamp alignment is the subtle part. Each RTP stream has its own timestamp clock with a random start. RTCP sender reports map RTP timestamps to a wall clock, which the composer uses to line up audio and video from different people.
- Priority: jobs for short meetings and paying customers can jump ahead; a backlog is acceptable for hours but not days.
- Cost: composing a 40-minute meeting at 720p with a fast encoder preset might take 10–20 core-minutes. 3 M recordings a day × 15 core-minutes ≈ 45 M core-minutes ≈ 31,000 cores busy around the clock, which is a good fit for spot or pre-emptible capacity because jobs can restart.
Storage and retention. At about 900 TB a day of new recordings, keeping everything forever would cost far too much. Plans have storage quotas; recordings move to colder storage tiers after 30 or 90 days; deletions by users, admins or retention policies remove objects and their transcripts. See Object Storage and Blob Storage and Data Lifecycle, Tiering and Retention.
Consent and compliance. Everyone in the meeting must see that recording is on (the signalling owner broadcasts it and clients show a banner), and some jurisdictions require every participant's consent. Encrypted meetings complicate cloud recording: in end-to-end encrypted mode, the server cannot record because it cannot decrypt (Deep Dive 11).
11. Security and privacy#
Encryption in transit (the baseline). WebRTC requires encryption: media uses SRTP with keys negotiated by DTLS, and signalling runs over TLS (WSS). With an SFU, the DTLS session is between each client and the SFU, so encryption is hop by hop: the SFU decrypts each packet, makes its forwarding decision, and encrypts again for each receiver. That means the SFU (and anyone who controls it) can access the media.
The 2020 lesson. Zoom's marketing at first described its meetings as "end-to-end encrypted". The company later clarified that this meant from Zoom endpoint to Zoom endpoint, which in practice meant between clients and Zoom servers, and reporters called the claim misleading. The US Federal Trade Commission later alleged that Zoom held keys that could give it access to meeting content; a settlement in November 2020 required added security measures. In the same months, uninvited guests disrupting meetings ("Zoombombing") became a widespread problem. Zoom froze new features for 90 days from 1 April 2020 to focus on security and privacy, turned on meeting passwords by default, let users choose which data centres their calls go through, and acquired Keybase (a company specialising in end-to-end encryption) in May 2020. The design lessons are concrete:
- Say precisely what is encrypted and who can decrypt it.
- Make the safe settings the default (passcodes, waiting rooms).
- Treat meeting links as secrets and make them hard to guess.
Making meetings hard to find and join uninvited.
- ID space. Meeting IDs of 10–11 digits give 10¹⁰–10¹¹ possibilities. With 5 million meetings live at peak, a random guess hits a live meeting about once in 2,000–20,000 tries. That is far too easy for a bot, so IDs alone are not security.
- Passcodes embedded in the link (as a hashed or encrypted parameter) make guessing useless: a guess must match both ID and passcode. Store only a hash of the passcode.
- Rate limiting and bot detection on the join API: limit failed joins per IP address, per account and per meeting; add challenges after failures. See Rate Limiting and Throttling.
- Waiting rooms: the host admits people. Authenticated-only meetings: only users signed in with the organisation's identity provider can join. Locking: no one else can join once the meeting is locked.
- Host controls enforced on the server: remove a participant (and block rejoining), disable screen share for attendees, mute all.
See Authentication and Authorization for tokens and roles.
End-to-end encryption (E2EE) with an SFU. The goal is that only participants hold the media keys, while the SFU still forwards packets and selects layers.
- The client encrypts each encoded frame with a key that the SFU does not have, then puts the encrypted frame into RTP packets and applies the normal hop-by-hop SRTP.
- The SFU removes the outer SRTP layer, reads only the RTP headers and header extensions it needs (sequence numbers, layer IDs, audio levels, keyframe flags), and forwards. It cannot decode the frames.
- The receiver removes the outer layer and then decrypts the frame with the meeting's media key.
The IETF standardised a frame-level format for this, SFrame (RFC 9605, 2024). Browsers expose hooks for it ("encoded transforms", earlier called insertable streams), so web apps can encrypt frames before packetisation.
Key management is the hard part.
- Each participant has a long-term identity key (on the device). When they join, the meeting key is shared with them, encrypted to their key.
- When someone leaves, the key must change (rekey) so they cannot decrypt future media; when someone joins, a new key stops them decrypting earlier recorded traffic.
- In big meetings, rekeying on every join and leave is expensive. Protocols like MLS (Messaging Layer Security, RFC 9420, 2023) use a tree of keys so that a group change costs O(log N) operations rather than O(N).
- Users need a way to verify they are talking to the right people, such as security codes that participants can compare.
What E2EE disables. Anything that needs the server to see media cannot work: cloud recording, live transcription and captions on the server, phone dial-in (the phone network cannot do E2EE), server-side mixing, and some AI features. Products therefore offer E2EE as an option for meetings that need it, and clearly show what is turned off.
Other privacy controls.
- Data residency: route media and store recordings only in allowed regions (Deep Dive 6).
- Metadata minimisation: keep call quality logs and participant lists for limited periods.
- Recording consent and visible indicators (Deep Dive 10).
- Abuse reporting that does not require the server to have recorded the meeting.
See Security Fundamentals for System Design.
12. Reliability, the client media pipeline and operations#
Failure domains and what users feel.
| Failure | What users see | Design response |
|---|---|---|
| One SFU process dies | Frozen video and audio for 2–5 s | Placement moves meetings to another server; clients reconnect with ICE restart; state survives in signalling |
| Signalling server dies | Media keeps flowing; roster and chat pause | Clients reconnect to the new owner with last seq; state reloaded from replicas |
| A whole zone fails | Meetings in that zone freeze | Global placement moves meetings to the next nearest zone; clients reconnect; latency rises |
| TURN relay overloaded | Users on restrictive networks cannot connect | Separate capacity and alerts for relays; multiple relay regions |
| Meeting service or database down | New meetings cannot be created or joined | In-progress meetings continue (tokens are already issued); cache meeting settings at the edge; read replicas |
| Recording pipeline backlog | Recordings arrive late | Durable job queue; raw files already safe in object storage |
The key principle: in-progress meetings must not depend on central services. Once a client has a token, a signalling connection and a media path, a failure in the database, the meeting service or the recording pipeline should not interrupt the call.
Deploying media servers without dropping calls. SFUs hold live sessions, so "restart all servers" is not an option.
- Drain: mark a server as draining. Placement stops assigning new meetings to it. Existing meetings finish naturally (most last under an hour) or are moved gracefully during natural pauses.
- Canary: roll out new SFU versions to a small share of servers, and compare call-quality metrics (freeze rate, audio loss, CPU per packet) with the old version before going wider.
- Client releases use staged rollouts and feature flags, because a codec or estimator bug in clients is hard to recall. See CI/CD and Deployment Strategies.
Inside the SFU: performance per packet. At about 1–2 million packets per second per server, every microsecond matters.
- Per packet: parse the RTP header, decrypt SRTP (AES-GCM or AES-CTR with HMAC, accelerated by AES-NI instructions), make a forwarding decision, rewrite sequence number and timestamp per receiver, encrypt for each receiver, and send.
- Fan-out multiplies encryption. One incoming packet forwarded to 20 receivers is 20 encryptions. That is the real CPU cost of an SFU.
- Batching system calls. Use
recvmmsgandsendmmsgto handle many packets per system call, and UDP segmentation offload where available. Some deployments use kernel-bypass networking (DPDK or AF_XDP) for more throughput. - Threading: pin meetings (or receivers) to cores so each core works on its own data without locks. A meeting larger than one core's capacity spreads receivers across cores.
- Memory: keep a ring buffer of recent packets per stream for retransmissions (about 1 second), which at 1.2 Mbps is 150 KB per stream.
The client media pipeline. Quality depends heavily on the client:
- Acoustic echo cancellation (AEC): removes the far-end voice picked up by the microphone from the speakers. Without it, everyone hears themselves.
- Noise suppression: removes keyboard noise, fans and dogs. Modern apps use neural networks for this, running on the CPU or a neural accelerator in real time.
- Automatic gain control keeps voice levels consistent.
- Background blur and replacement segment the person from the background per frame, again with a small neural network.
- Adaptive capture: reduce camera resolution and frame rate when the CPU is overloaded or the battery is low, and tell the server.
Observability: measure the experience. Machine metrics do not show whether calls are good. Collect, per participant and per minute:
- round-trip time, jitter, packet loss before and after repair, and bitrate on each leg;
- freeze count and duration (video stalls), audio concealment rate (share of audio that was synthesised);
- time to join, time to first frame, ICE path type (direct UDP, TCP, relay);
- an estimated MOS (mean opinion score) for audio, computed from loss, delay and codec with a model such as the ITU-T E-model.
These go to a telemetry pipeline (client upload at call end plus samples during the call) and feed dashboards by region, ISP, client version and network type. A sudden rise in relay use or freezes for one ISP is a routing problem to fix, often before customers complain. See Observability: Logs, Metrics and Traces.
Capacity and surges. The March–April 2020 surge showed that conferencing demand can rise many times over within weeks. Defences:
- run the same media software on owned hardware and on public cloud capacity, so capacity can be rented quickly;
- keep headroom per zone for neighbour failover, and use cross-zone cascades to borrow capacity at a latency cost;
- degrade gracefully under load: lower default resolutions (for example cap gallery tiles at 180p), reduce frame rates, and prioritise audio before turning anyone away.
See Capacity Planning and Load Testing and Designing for High Availability.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| SFU process or host crash | All participants on that server freeze; audio drops for 2–5 s | Meeting state lives in signalling, not the SFU; placement picks a new SFU; clients do an ICE restart and republish; keep 20–30% headroom per zone |
| One meeting outgrows its SFU (big webinar or all-hands) | CPU or NIC saturates; everyone on that server suffers | Cascade: split receivers across several SFUs in a tree; cap forwarded videos (last-N); switch huge audiences to broadcast (LL-HLS via CDN) |
| Join storm at the top of the hour | Signalling and auth spikes 5–10× in a minute; slow joins | Pre-scale before :00 and :30; cache meeting settings at the edge; spread token checks; admission queue with a progress message |
| Users behind strict firewalls | ICE fails over UDP; no media | TURN over TCP and TLS on port 443; relays in every region; monitor relay share per network and ISP |
| TURN relay overload | Relayed users lose quality or cannot join | Separate relay capacity and alerts; route relay traffic straight to the SFU (the SFU itself listens on TCP/443) so most "relay" users need no extra hop |
| Bandwidth drop on one receiver's network | That user sees frozen or blurry video | Congestion control per receiver; SFU switches that receiver to a lower simulcast or SVC layer; audio is protected first |
| Packet loss bursts on a long path | Choppy audio, freezes | NACK for short RTTs, FEC and RED for audio, jitter buffer, Opus packet loss concealment; place SFUs near users and cascade over the private backbone |
| Keyframe storm (many receivers ask for a keyframe at once) | Sender's uplink spikes, more loss, more requests | SFU merges PLI requests and rate-limits them per sender; uses the cached latest keyframe for SVC; prefers layer switches at natural keyframes |
| Signalling owner failure | Roster, chat and host controls pause; media continues | Replicated meeting state, new owner by lease or epoch, clients reconnect and resync from their last seq |
| Recording pipeline backlog | Recordings arrive hours late | Raw capture chunks written durably first; queue-based processing with autoscaling; priority by meeting length and customer tier |
| Meeting ID guessing and Zoombombing | Uninvited people disrupt meetings | Passcodes in links, waiting rooms, authenticated-only meetings, rate limits on failed joins, host removal and lock |
| Regional outage or demand surge (like March 2020) | Joins fail or quality drops in one region | Multi-zone placement with spill-over, rented cloud capacity running the same software, default quality caps under pressure |
What Interviewers Expect#
Mid-level. Explain why video calls use UDP and not TCP. Draw the split between a control plane (meeting service, signalling over WebSockets) and a media plane (media servers). Explain why a central server (SFU) is needed beyond about four people, using the mesh bandwidth argument. Mention STUN and TURN for NAT traversal at a basic level. Produce a reasonable capacity estimate (bitrate × participants) and simple APIs for create and join. Handle chat and the participant list as messages on the signalling channel.
Senior. Explain simulcast and how the SFU picks a layer for each receiver based on bandwidth estimates and the size of the tile. Know the latency budget (about 150 ms one-way for natural conversation) and where it is spent. Design signalling with one owner per meeting, sequence numbers for ordering, and reconnection. Handle SFU failure without losing the meeting. Discuss placement: pick an SFU zone near the participants, and cascade SFUs when people are on different continents. Cover cloud recording with a bot participant that writes chunks to object storage, and handle the large meeting case (active speaker, last-N, pagination).
Staff and above. Go deep on one or two of: ICE candidate gathering and prioritisation, congestion control (delay-based estimation like GCC, transport-wide feedback), SVC versus simulcast trade-offs, the SFU packet path and its CPU cost (encryption per receiver), end-to-end encryption with frame-level encryption and group key management (and what it disables), and the economics of bandwidth (TURN share, backbone versus public internet, owned hardware versus cloud during surges). Define call quality metrics (freezes, audio concealment, join time, MOS) as the true SLOs, and explain how to roll out SFU and client changes safely with canaries judged on those metrics.
Deep Dive: sizing every tierShow
The numbers below follow from the capacity estimate: 25 M concurrent participants at peak, 5 M meetings, an average of 5 people per meeting, 60% of people sending video.
Media servers (SFUs).
- Per participant, the SFU receives about 1.5 Mbps (simulcast layers plus audio) when video is on, and sends about 1.8 Mbps on average (several tiles at low layers, one speaker at a high layer, plus audio).
- A modern server with a 25 Gbps NIC can be run to about 60% of its NIC (about 15 Gbps), which leaves headroom for bursts and failover.
- The CPU limit usually comes first: about 1–2 million packets per second with SRTP decrypt and re-encrypt. At an average packet size of about 1,000 bytes, that is 8–16 Gbps.
- So one server carries about 15 Gbps / 3.3 Mbps ≈ 4,500 participants if bandwidth bound, or about 3,000–4,000 when CPU bound. Plan with 3,500.
- 25 M / 3,500 ≈ 7,100 servers at peak, matching the earlier estimate. Add 25% headroom for zone failover and surges: about 9,000 SFU servers, spread over 15–25 zones.
TURN relays.
- About 15% of participants need a relay: about 3.75 M people. Many connect over TCP/TLS on port 443 straight to the SFU, which removes the extra hop; assume a third still need a separate relay.
- About 1.25 M relayed participants × 3.3 Mbps ≈ 4 Tbps through relays. At 15 Gbps per relay server, about 300 relay servers plus headroom, about 400.
Signalling.
- 25 M persistent WebSocket connections. A well-tuned server handles 100,000–200,000 idle connections; use 50,000 per server to leave CPU for message fan-out.
- 25 M / 50,000 = 500 edge servers, plus meeting owners that hold state for 5 M meetings. Each meeting state is a few KB (roster, settings, seq); 5 M × 10 KB = 50 GB in memory across the owner fleet, easily held on 100–200 servers.
- Messages: about 2.5 M per second at peak (roster updates, chat, reactions, layer requests, heartbeats are mostly handled at the edge).
Meeting service and database.
- Joins: 40,000 per second at the top of the hour. Each join reads meeting settings (cached) and writes a participant session row.
- A sharded relational store (for example MySQL with Vitess, or a distributed SQL database) with 50–100 shards handles 40,000 writes per second comfortably at 400–800 writes per second per shard.
- Participant session rows: 300 M per day × about 500 bytes = 150 GB per day, kept hot for 30–90 days and then moved to the analytics store.
Chat.
- Assume 2 messages per participant per meeting, so 600 M messages per day, about 7,000 per second on average and 30,000 per second at peak.
- At 500 bytes each, 300 GB per day. Persisted only when the meeting has saved chat enabled or persistent chat is on.
Recording.
- 5% of meetings recorded: about 900 TB of new recordings per day (from the capacity section), about 330 PB per year before retention policies.
- Processing: about 31,000 cores for compositing and transcoding (Deep Dive 10), mostly in batch after the meeting ends, so it can use cheaper interruptible capacity.
Telemetry.
- Each participant sends a quality sample every 10 seconds of about 1 KB: 25 M × 0.1 = 2.5 M samples per second, about 2.5 GB/s, which is about 200 TB per day.
- Store per-minute aggregates for long periods and raw samples for a week. Use a streaming system such as Kafka plus a column store like ClickHouse or Druid for slicing by region, ISP and client version.
Backbone.
- Cascaded traffic between zones: if 10% of meetings span regions and each cross-region link carries about 5 Mbps per meeting, that is 500,000 × 5 Mbps = 2.5 Tbps across the private backbone at peak.
| Tier | Peak load | Fleet (with headroom) |
|---|---|---|
| SFU media servers | 25 M participants, ~70 Tbps | ~9,000 servers in 15–25 zones |
| TURN relays | ~1.25 M relayed participants, ~4 Tbps | ~400 servers |
| Signalling edges | 25 M WebSockets, 2.5 M msg/s | ~500 servers |
| Meeting owners | 5 M live meetings, ~50 GB state | ~150 servers |
| Meeting DB | 40,000 joins/s | 50–100 shards |
| Recording processing | 900 TB/day | ~31,000 cores, batch |
| Telemetry | 2.5 M samples/s | Kafka plus ClickHouse cluster |
Deep Dive: real-world systems comparedShow
The public facts below are deliberately general. Product internals change often, so treat anything not stated by the vendor as an informed guess.
- Zoom. Public descriptions of Zoom's design stress three choices: scalable video coding (one layered stream per sender, so a server can drop upper layers for weak receivers), servers it calls multimedia routers that choose paths and forward video, and clients that connect to the closest data centre. Zoom runs colocated data centres (it has announced expansions with Equinix) alongside public cloud. During the 2020 surge it was widely reported to have added large amounts of cloud capacity, including from Oracle. Its native apps are widely described as using Zoom's own protocol stack rather than standard browser WebRTC.
- Google Meet. Runs in the browser using WebRTC, on Google's global network. Being browser first means it depends on standard WebRTC features (simulcast, and VP9 or AV1 SVC where supported) and benefits from Google's private backbone between data centres.
- Microsoft Teams. Combines meetings with chat, files and calendars in one product. Media flows through Microsoft's media servers and relays, and the meetings product is tightly linked with the organisation's identity system, which makes "authenticated-only" meetings the natural default for companies.
- Discord. Built for always-on voice channels rather than scheduled meetings. A 2018 Discord engineering post by Jozsef Vass, "How Discord Handles Two and Half Million Concurrent Voice Users using WebRTC", describes a design worth knowing in detail:
- Everything goes through servers. Every call is treated as multiparty and routed through Discord's media servers. Besides scaling, this hides users' IP addresses from each other, which matters because players attack each other with DDoS floods.
- Custom native stack. The browser app uses standard WebRTC. The desktop and mobile apps use one C++ media engine built on the WebRTC native library. Because every client talks only to a Discord server, the native apps skip SDP (which can be close to 10 KB per round trip) and exchange under 1,200 bytes on join, skip ICE entirely, and use Salsa20 encryption instead of DTLS-SRTP. They also stop sending audio during silence, which saves a lot in big channels where few people talk at once.
- Placement. Signalling services are written in Elixir. All voice channels of one guild (community) are assigned to one voice server; the guild service picks the least loaded voice server in the region using health and load reports stored in etcd.
- SFU and failover. Each voice server pairs a signalling component with a C++ SFU. If the SFU crashes, signalling restarts it and rebuilds its state without involving clients; the same mechanism gives zero-downtime SFU updates. If a whole voice server dies or is hit by a DDoS attack, it is removed from service discovery and the guild is moved to a new server, and clients reconnect.
- Scale. At the time: about 2.5 million concurrent voice users, more than 850 voice servers in 13 regions hosted in more than 30 data centres, on physical servers from several providers, while the gateway and guild services ran on Google Cloud.
- Open-source SFUs. Jitsi Videobridge, mediasoup, Janus and LiveKit (built on the Pion WebRTC library in Go) are widely used to build conferencing products. They show that the core SFU is a well-understood component; the hard parts of a Zoom-scale product are global placement, operations, client quality and cost.
| Aspect | Zoom-style native client | Browser-first (Meet-style) | Voice-channel apps (Discord-style) |
|---|---|---|---|
| Media stack | Custom codecs and transport tuned per platform | Standard WebRTC | WebRTC native library with custom signalling and encryption, custom SFU |
| Main strength | Quality on poor networks, very large meetings | Zero install, works anywhere | Low cost per user, always-on rooms |
| Main constraint | Must ship and update native apps | Limited to what browsers support | Less focus on video features and recording |
| Large meetings | Webinars and broadcast modes | Live streaming for big audiences | "Stage" style rooms with few speakers |
What to say in an interview. Do not claim exact internals. Say that all of these systems use a forwarding server design, place servers close to users, use layered video (simulcast or SVC) to serve mixed networks, and differ mainly in client strategy (native versus browser) and in how they handle the largest meetings.
Deep Dive: a 45-minute interview planShow
| Minutes | What to do | What to put on the board |
|---|---|---|
| 0–5 | Clarify scope: meeting size (2–100 normal, up to 1,000 interactive, larger as webinars), video and screen share, chat, recording, browsers or apps, E2EE or not | A short list of in-scope and out-of-scope features |
| 5–10 | Non-functional goals and numbers: under 150 ms one-way latency, join in under 3 s, 25 M concurrent participants, bitrate per stream | Capacity lines: participants × Mbps = Tbps; SFU count |
| 10–15 | APIs and entities: create and join meeting (REST), signalling messages (WebSocket), media over UDP | Meeting, instance, participant session, recording |
| 15–25 | High-level design: control plane versus media plane; why SFU (mesh and MCU compared); STUN, TURN and ICE; placement service | The HLD with clients, meeting service, signalling, SFU zones, relays, recording |
| 25–40 | Deep dives the interviewer picks. Prepare at least: simulcast or SVC with per-receiver layer choice; congestion control; SFU failure and reconnection; large meetings with cascades and last-N; recording pipeline | One sequence diagram (join or SFU failure) and one layer-selection sketch |
| 40–45 | Bottlenecks, failure modes and what you would measure (freezes, join time, MOS) | Failure table and two or three SLOs |
Common traps.
- Sending media through the WebSocket or over TCP. Explain why late packets are useless and why UDP with repair wins.
- Drawing a single "video server" with no story for placement, cascades or failure.
- Forgetting that one sender serves receivers with very different networks; this is the whole reason for simulcast and SVC.
- Treating recording as "save the stream". It is a separate participant, a durable chunk pipeline and a heavy batch job.
- Promising end-to-end encryption while also offering cloud recording and live captions without explaining the conflict.
Deep Dive: follow-up questions and strong answersShow
"Why not use peer-to-peer for everything? It is free for you." For two people, many products do use a direct path when ICE finds one, because it gives the lowest latency. Beyond three or four people, each sender must upload one copy per receiver, which home uplinks cannot carry, and each device must encode or send many streams. A server design also hides IP addresses and lets the server enforce host controls.
"How does the SFU know which layer to send to me?" From two inputs. The receiver's bandwidth estimate (from transport-wide feedback and the delay-based estimator) sets a budget. The receiver's layout (tile sizes, who is pinned, who is speaking) sets the useful resolution per sender. The allocator gives audio first, then the active speaker, then other tiles, choosing the highest layer of each that fits, and re-runs whenever either input changes.
"A user's video freezes. Walk me through the debugging." Check their quality telemetry: bandwidth estimate, loss, RTT and the ICE path type. If loss is high only on their downlink, the SFU should have dropped them to a lower layer; check whether it did and how quickly. If the sender's uplink was the problem, every receiver froze at once. If only users of one ISP froze, look at routing to that zone. Freezes right after a layer switch point to slow keyframes.
"How do you move a meeting from one SFU to another without a visible glitch?" Make-before-break. The new SFU is set up first, clients get the new endpoint through signalling and connect to it while the old path still works, then senders publish to the new SFU and receivers switch once the first keyframes arrive. Only then is the old path torn down. The glitch shrinks to about one keyframe interval.
"How do you support 10,000 people in one meeting?" Separate speakers from audience. Up to a few hundred interactive participants stay on cascaded SFUs, with only the top few audio streams and a small set of videos forwarded. The rest watch a composited or single-speaker stream through a broadcast path such as low-latency HLS on a CDN, at 2–5 seconds of delay. An attendee who is promoted to speak moves from the broadcast path to the interactive path.
"How would you add end-to-end encryption?" Encrypt each frame on the sender with a key the server does not know (SFrame), leave the RTP headers and layer information readable so the SFU still forwards, and manage group keys with rekeying on join and leave (MLS for big groups). Then state clearly that cloud recording, server captions and phone dial-in stop working in E2EE meetings.
"How do you keep costs down?" Bandwidth is the largest cost. Run SFUs in owned or colocated data centres with cheap transit; keep cross-region traffic on a private backbone; send fewer and smaller layers when tiles are small; stop sending video that nobody views (receivers report what they show); use audio-only defaults for very large meetings; and run recording processing in batch on cheaper capacity.
"What would you measure to know calls are good?" Per call and per minute: join success rate and time to join, time to first frame, freeze rate and duration, audio concealment share, one-way latency estimates, and an estimated audio MOS. Set SLOs on these and slice them by region, ISP, client version and network type.
Deep Dive: the SFU packet path in detailShow
An SFU is a packet router that understands just enough of RTP to make smart decisions. Here is what happens to one video packet from the moment it arrives.
Demultiplexing on one port. To get through firewalls and to save ports, SFUs usually listen on a single UDP port (and TCP/443) for all sessions. The first byte of each datagram tells STUN (0–3), DTLS (20–63) and RTP or RTCP (128–191) apart, as described in RFC 7983. ICE checks carry a username fragment that maps the new address to a session; after that, the source address and port identify the session.
Header extensions the SFU relies on.
- Transport-wide sequence number: one counter across all streams from a sender, so the server can report arrival times for every packet and the sender can estimate bandwidth (Deep Dive 4).
- Audio level (RFC 6464): the loudness of each audio packet in the clear, so the SFU picks active speakers without decoding.
- Layer information: the VP8 or VP9 payload descriptor, or the AV1 dependency descriptor, which says which spatial and temporal layer a packet belongs to and whether it can be decoded by itself. With E2EE these headers stay readable while the payload is encrypted.
- Absolute send time or capture time: used for delay estimates and for lining up audio and video.
Rewriting sequence numbers. When the SFU switches a receiver from the 360p stream to the 720p stream, the receiver must see one continuous stream, or its jitter buffer would think thousands of packets were lost. The SFU keeps an offset per receiver and stream:
// per receiver, per forwarded video track
function forward(pkt: Rtp, out: OutTrack) {
if (out.switchPending && pkt.ssrc === out.targetSsrc && pkt.isKeyframeStart) {
out.currentSsrc = pkt.ssrc;
out.seqOffset = out.lastSentSeq + 1 - pkt.seq; // continue numbering
out.tsOffset = out.lastSentTs + 3000 - pkt.timestamp; // ~1 frame at 90 kHz
out.switchPending = false;
}
if (pkt.ssrc !== out.currentSsrc) return; // not the chosen layer
if (pkt.temporalId > out.maxTemporalId) { // dropped frame rate layer
out.seqOffset -= 1; // hide the gap
return;
}
const seq = (pkt.seq + out.seqOffset) & 0xffff;
const ts = (pkt.timestamp + out.tsOffset) >>> 0;
out.lastSentSeq = seq; out.lastSentTs = ts;
send(out.receiver, rewrite(pkt, out.outSsrc, seq, ts));
}The switch only happens at a keyframe of the new stream, because the receiver cannot decode a delta frame without its reference. That is why the SFU asks the sender for a keyframe (PLI) when it decides to switch up, and why keyframe requests must be merged and rate-limited. (The simple seq offset above assumes dropped packets are never retransmitted; real SFUs keep a map from incoming to outgoing numbers so NACKs can be translated.)
Pacing. The SFU does not dump a keyframe (often 30–100 packets) onto a receiver's link in one burst. It queues packets per receiver and sends them at the receiver's estimated bandwidth, a few milliseconds apart, so router queues on the way do not overflow.
CPU cost, worked through. Suppose a server forwards 12 Gbps outbound at about 1,100 bytes per packet: about 1.4 M packets per second out, and perhaps 0.4 M packets per second in.
- AES-128-GCM with AES-NI runs at a few GB per second per core, so encrypting 1.5 GB/s of output takes roughly one or two cores of pure crypto. The bigger cost is everything around it: per-packet lookups, copies, timers and feedback.
- A typical system-call-per-packet design manages a few hundred thousand packets per second per core. With
recvmmsgandsendmmsg(32–64 packets per call) and UDP segmentation offload, this rises to around a million per core for the send path. - So a 32-core server spends perhaps 4–8 cores on network I/O, 2–4 on crypto, and the rest on forwarding logic, feedback, bandwidth allocation and control. Kernel-bypass designs (DPDK, AF_XDP) can double throughput but cost operational complexity.
Spreading work over cores. NICs hash incoming packets to receive queues by address and port (RSS), so each core can own a set of sessions. A meeting is placed on one core when small. When large, its receivers are split across cores, and each incoming packet is handed to those cores through lock-free queues, so fan-out work runs in parallel.
Memory. Per stream, a 1-second retransmission buffer at 1.5 Mbps is about 190 KB. A server with 3,500 participants receiving and sending around 10 streams each needs a few GB for buffers, which is modest. The real memory risk is unbounded queues to slow receivers, so per-receiver queues have strict limits and drop the least important packets (high temporal layers) first.
Deep Dive: the audio pipeline from microphone to speakerShow
People forgive frozen video, but not broken audio. Most of the work that makes audio sound good happens on the client.
Echo cancellation. Without it, the far-end voice comes out of your speaker, into your microphone, and back to the speaker as an echo about half a second later. The echo canceller is an adaptive filter: it learns how the speaker signal reaches the microphone (the room's echo path) and subtracts the predicted echo. It must handle changing rooms, volume changes and both people talking at once ("double talk"). It works best when the speaker reference and the microphone are tightly synchronised, which is why it runs on the device, not on the server.
Noise suppression. Classic methods estimate the noise spectrum during pauses and subtract it. They handle steady fan noise but not keyboard clicks or barking dogs. Neural network suppressors, trained on speech mixed with many kinds of noise, now run in real time on ordinary CPUs and remove these much better. The trade-off is CPU and battery use, and occasional damage to non-speech sounds the user wanted (music lessons), so products offer a "music mode" or "original sound" switch.
Automatic gain control raises quiet speakers and limits loud ones, so the receiver does not need to keep changing volume.
Voice activity detection decides whether the user is speaking. It drives three things: the "you are muted" warning when someone talks while muted, the audio-level header used by the SFU to pick active speakers, and DTX.
The Opus codec. Opus (RFC 6716, 2012) is the standard codec for WebRTC audio.
- It runs from about 6 kbps (narrow-band speech) to 510 kbps (high-quality stereo music). Conference speech typically uses 24–40 kbps.
- Frames are usually 20 ms. Shorter frames lower delay but add header overhead; with RTP, UDP and IP headers of about 40 bytes per packet, 50 packets per second add about 16 kbps of headers alone.
- DTX (discontinuous transmission) sends almost nothing during silence, apart from an occasional comfort-noise update. In a 10-person meeting where one person talks, this cuts audio packets by around 90%.
- In-band FEC carries a low-bitrate copy of the previous frame inside the current packet, so one lost packet can be rebuilt from the next one. The sender turns it on when receivers report loss. RED (redundant encoding) goes further by repeating whole earlier frames, at the cost of more bandwidth.
The jitter buffer. Packets arrive with uneven gaps (jitter). The receiver holds them briefly so playback is smooth. A fixed 100 ms buffer would add needless delay on good networks and still be too small on bad ones, so it adapts: it tracks recent arrival variation and keeps the delay just above it, typically 20–80 ms. To shrink or grow the buffer without clicks, it speeds up or slows down playback slightly during speech, or stretches and compresses silences. The WebRTC audio engine's version of this is called NetEQ.
Packet loss concealment. When a packet is still missing at playout time, the decoder synthesises a plausible continuation from the previous audio. Short gaps of 20–60 ms are almost unnoticeable; longer gaps fade to silence. The share of concealed audio is one of the best call-quality metrics.
Mixing at the receiver. An SFU forwards the top 3 or so audio streams (Deep Dive 7). The client decodes each and mixes them. Because only a few streams are decoded, a 500-person meeting costs the client about the same as a 5-person one for audio.
Audio and video sync. Audio and video travel as separate streams with separate clocks (48 kHz for audio, 90 kHz for video). RTCP sender reports map each stream's timestamps to a shared wall clock, so the receiver can delay one stream to line them up. People notice when audio and video are out of sync by more than roughly 45 ms (audio early) to 125 ms (audio late), so the player aims well inside that.
A worked latency budget for audio. Capture and processing 10 ms, encoding 20 ms (one frame), sender network to SFU 20 ms, SFU forwarding 1 ms, SFU to receiver 30 ms, jitter buffer 40 ms, decode and playout 10 ms. Total about 130 ms one-way, inside the 150 ms target. Every extra network hop or larger jitter buffer pushes it over, which is why placing the SFU close to the participants matters so much.
Key Takeaways#
- Two planes. A control plane (meeting service, signalling over WebSockets) decides who is in the meeting and what they may do. A media plane (SFUs and relays) moves packets over UDP. Keep live calls independent of central services.
- The SFU is the default. Mesh breaks after three or four people because of uplink limits; an MCU costs too much CPU and adds delay. An SFU forwards without decoding and lets each receiver get the right quality.
- Connectivity is a protocol, not a hope. ICE gathers host, reflexive (STUN) and relay (TURN) candidates and tests them in priority order. Offer TURN over TLS on port 443 for strict networks, and measure how many users need it.
- One sender, many networks. Simulcast or SVC gives the SFU several layers to choose from per receiver. The allocator gives audio first, then the active speaker, then other tiles.
- Latency is a budget. About 150 ms one-way for natural talk. Place SFUs near users, cascade between regions over a private backbone, keep jitter buffers small, and prefer concealment over waiting.
- Congestion control keeps calls alive. Delay-based estimation (like GCC) with transport-wide feedback reacts before loss happens; NACK, FEC and RED repair what is lost.
- Signalling needs one owner per meeting, with sequence numbers, heartbeats, epoch-based failover and replayable state, so a server failure does not lose the roster or chat.
- Big meetings change shape. Forward only the top few speakers and the visible videos, cascade SFUs into trees, and move very large audiences to a broadcast path on a CDN.
- Recording is its own system. A bot participant writes durable chunks to object storage; compositing and transcoding run as batch jobs later.
- Security must be precise. Encrypt hop by hop by default, add frame-level E2EE (SFrame with group keys) as an option, explain what it disables, and make passcodes, waiting rooms and join rate limits the defaults.
- Measure the experience. Freezes, audio concealment, join time and MOS are the real SLOs. Roll out SFU and client changes with canaries judged on those metrics.