Chapter 22 · APIs

WebRTC


WebRTC is a standards-based collection of browser APIs and network protocols for real-time media and arbitrary peer data. It is often described as "peer-to-peer video," but production systems frequently route each browser to a media server such as a Selective Forwarding Unit (SFU). The browser API handles media capture, codec negotiation, encryption, congestion control, NAT traversal, and transport. Your application must still provide signaling, identity, authorization, room state, moderation, recording, analytics, and recovery behavior.

Level: foundation → senior/staff Primary skill: designing low-latency audio, video, and data systems across hostile networks while controlling quality, cost, security, and operational risk Companions: UDP · TCP · HTTP · WebSockets · Load Balancing · CDNs · Queues · Object Storage

A senior interview answer does not stop at getUserMedia() and RTCPeerConnection. It separates the control and media planes, explains when traffic uses STUN or TURN, chooses a topology from workload constraints, quantifies fan-out and relay cost, and gives a concrete plan for poor networks, reconnects, deployments, and regional failure.

How to use this chapter

  1. Explain the end-to-end call setup without looking at the diagram.
  2. Work the bandwidth examples on paper and replace the assumptions with your own.
  3. Compare mesh, SFU, MCU, and CDN delivery for three different products.
  4. Answer each question aloud before revealing the strong-answer signals.
  5. Complete one design drill in 45 minutes and score it with the readiness checklist.

Learning objectives

By the end of this chapter, you should be able to:

  • Distinguish signaling, session negotiation, connectivity establishment, media transport, and application state.
  • Explain ICE candidate gathering, STUN discovery, TURN relaying, trickle ICE, nomination, and ICE restart.
  • Trace audio or video from capture through encoding, RTP, encryption, transport, jitter buffering, decoding, and rendering.
  • Handle offer/answer glare, transceivers, renegotiation, screen sharing, device changes, and network handoffs.
  • Compare direct peer-to-peer, mesh, SFU, MCU, and broadcast/CDN topologies.
  • Design quality adaptation using bitrate control, simulcast or scalable video coding, retransmission, keyframes, and receiver selection.
  • Operate a media system using join-funnel metrics, getStats(), TURN/SFU telemetry, synthetic calls, and failure drills.
  • Quantify bandwidth, egress, recording storage, TURN usage, and reconnect-storm capacity.
  • Address authentication, signaling integrity, media encryption, abuse, privacy, and optional end-to-end media encryption.

Mental model

A useful architecture separates five responsibilities:

  1. Application plane: users, rooms, permissions, billing, moderation, chat history, invitations, and product state.
  2. Signaling plane: exchange of session descriptions, ICE candidates, call-control messages, and reconnect intent. WebRTC deliberately does not prescribe the signaling protocol.
  3. Connectivity plane: ICE tests candidate pairs. STUN helps discover reachable addresses; TURN relays traffic when a direct path cannot be established or when policy requires relay.
  4. Media/data plane: RTP/RTCP carry real-time media protected with SRTP; data channels use SCTP over DTLS. Media may flow directly or through an SFU/MCU.
  5. Operations plane: admission control, placement, autoscaling, quality telemetry, recording pipelines, deploy draining, incident response, and cost controls.

A simplified one-to-one setup looks like this:

Browser A                         Application services                         Browser B
---------                         --------------------                         ---------
getUserMedia()                                                                    getUserMedia()
     |                                                                                  |
RTCPeerConnection <-- SDP / ICE --> signaling API / WebSocket <-- SDP / ICE --> RTCPeerConnection
     |                                                                                  |
     +------------ ICE connectivity checks: host / srflx / relay -----------------------+
     |                                                                                  |
     +================ encrypted SRTP media / SCTP data ================================+
                     direct path or relayed through TURN

A group-call setup usually changes only the media path:

                    room/auth/signaling services
                  /          |          |          \
             Browser A   Browser B   Browser C   Browser D
                  \          |          |          /
                   \========= regional SFU =======/
                              |
                   recorder / transcription / analytics

The signaling service is normally latency-sensitive but not on the packet-by-packet media path. The SFU is on the media path and therefore has different capacity, networking, placement, and failure requirements.

Core mechanics

1. Media capture, tracks, senders, receivers, and transceivers

navigator.mediaDevices.getUserMedia() requests camera and microphone tracks. A MediaStreamTrack represents one source, while a MediaStream is primarily a grouping abstraction. Tracks are attached to a RTCPeerConnection through senders or transceivers and arrive as remote tracks through receivers.

The modern mental model is transceiver-oriented:

  • An RTCRtpSender encodes and sends one track.
  • An RTCRtpReceiver receives and decodes media.
  • An RTCRtpTransceiver pairs sender and receiver state for one negotiated media section and has a direction such as sendrecv, sendonly, recvonly, or inactive.
  • A media identifier, or MID, associates negotiated media sections with transceivers.

Adding a track or transceiver can require renegotiation. Replacing a camera track with a screen-share track of compatible negotiated parameters can often use sender.replaceTrack() without a fresh offer/answer exchange. Do not assume it always succeeds: a material codec, channel-count, or resolution-envelope change may still require negotiation or may be rejected by the implementation.

Capture is also a product and privacy concern. Permission denial, missing devices, devices becoming unavailable, operating-system privacy controls, and browser autoplay restrictions belong in the join-state machine. A robust client distinguishes “user denied permission” from “camera busy,” “no device,” and “media server unreachable.”

2. Signaling and session negotiation

WebRTC does not define how two endpoints find each other or exchange control messages. Applications commonly use HTTPS plus WebSocket, but any channel that can carry the required messages can work.

Signaling usually carries:

  • room join and participant identity;
  • session descriptions containing negotiated media and transport parameters;
  • incremental ICE candidates;
  • call actions such as ring, accept, reject, mute state, screen-share intent, or hand raise;
  • reconnect, resume, and server-migration instructions.

JSEP and the browser APIs expose the SDP offer/answer model. A caller creates an offer, applies it locally, sends it to the remote endpoint, and receives an answer. SDP is a negotiation format, not an application database. Avoid editing it casually with string manipulation; prefer browser APIs such as transceiver direction, codec preferences where supported, and sender parameters.

Two peers can create offers at the same time. This glare case is why production clients use a “perfect negotiation” pattern with polite and impolite roles, collision detection, and rollback. A senior design names this explicitly rather than assuming only one side can initiate changes.

A minimal shape is:

let makingOffer = false;
const polite = true; // assign deterministically per session

pc.onnegotiationneeded = async () => {
  try {
    makingOffer = true;
    await pc.setLocalDescription();
    signal({ description: pc.localDescription });
  } finally {
    makingOffer = false;
  }
};

async function onSignal({ description, candidate }) {
  if (description) {
    const collision =
      description.type === "offer" &&
      (makingOffer || pc.signalingState !== "stable");

    const ignoreOffer = !polite && collision;
    if (ignoreOffer) return;

    await pc.setRemoteDescription(description);
    if (description.type === "offer") {
      await pc.setLocalDescription();
      signal({ description: pc.localDescription });
    }
  } else if (candidate) {
    await pc.addIceCandidate(candidate);
  }
}

Real implementations need message sequencing, session IDs, stale-generation rejection, authorization, reconnect behavior, and careful error handling around candidate arrival before a compatible remote description.

3. ICE, STUN, TURN, and NAT traversal

Endpoints frequently sit behind NATs, firewalls, VPNs, and enterprise proxies. ICE gathers possible addresses, exchanges them through signaling, checks candidate pairs, and selects a working pair.

The main candidate types are:

  • Host: an address on a local interface.
  • Server-reflexive (srflx): a public mapping discovered through STUN or TURN.
  • Peer-reflexive (prflx): discovered during connectivity checks.
  • Relayed (relay): an address allocated on a TURN server.

STUN is not a media relay. It helps an endpoint learn a public-facing mapped address and participates in connectivity checks. TURN allocates relay capacity and forwards packets. TURN is therefore both a reliability tool and a significant bandwidth/cost component.

Trickle ICE sends candidates as they are found, allowing connectivity checks to overlap candidate gathering and shortening time to first media. Without trickle, the caller may wait until gathering completes before sending a complete offer.

Production TURN design should include:

  • UDP relaying for the normal low-latency path;
  • TCP and TLS options, commonly through a firewall-friendly port, for restrictive networks;
  • short-lived credentials rather than public static secrets;
  • regional placement near users and SFUs;
  • autoscaling based on allocations, sessions, packets, and bandwidth, not CPU alone;
  • abuse prevention, quotas, and denial-of-service controls;
  • telemetry for allocation failure, candidate type, relay ratio, and relay round-trip time.

An ICE failure can be caused by signaling loss, bad credentials, blocked UDP, TURN exhaustion, DNS failure, clock skew affecting temporary credentials, candidate-policy mistakes, or a remote endpoint that disappeared. “ICE failed” is an outcome, not a root cause.

4. Transport security

WebRTC media is encrypted in transit. DTLS establishes keying material and SRTP protects media; data channels use SCTP over DTLS. Signaling itself is outside the WebRTC protocol suite, so the application must protect it with authenticated secure transport and authorization.

This distinction matters:

  • Transport encryption protects each WebRTC hop. In an SFU architecture, each participant typically has a secure connection to the SFU, and the SFU can usually access packet payloads as part of forwarding and media processing.
  • End-to-end media encryption adds an application-controlled encryption layer so the SFU forwards ciphertext it cannot interpret. This complicates recording, transcription, moderation, server-side compositing, key distribution, membership changes, and abuse handling.

A signaling attacker who can alter session descriptions, fingerprints, candidate information, or room membership may redirect or interfere with the call. Authenticate both the user and the session, bind messages to room and participant IDs, reject stale messages, and avoid logging sensitive tokens or full session descriptions unnecessarily.

Use short-lived join tokens and TURN credentials. Recheck authorization when a participant reconnects, joins a privileged stage, begins recording, or changes publication state. A long-lived socket is not permanent authorization.

5. RTP, RTCP, adaptation, and recovery

Real-time media usually prefers timeliness over perfect delivery. RTP carries timestamped media packets; RTCP provides control and feedback used for quality and synchronization. The browser media engine handles much of the difficult work, including pacing, bandwidth estimation, jitter buffering, codec adaptation, and packet-loss response.

Important mechanisms include:

  • Congestion control: adjusts sending rate to available network capacity.
  • Jitter buffer: absorbs variable packet delay at the cost of latency.
  • NACK/retransmission: requests selected lost packets when they may still arrive in time.
  • RTX: carries retransmitted video packets separately when negotiated.
  • PLI/FIR and keyframes: request or cause a decoder-refresh frame after loss or when switching streams.
  • Forward error correction: adds redundant information in some media modes to recover from loss without a round trip.
  • Audio concealment: synthesizes or repeats audio to mask missing samples.

A senior answer describes the product trade-off: raising the jitter buffer can improve smoothness while increasing conversational latency; aggressive retransmission helps on moderate RTT but may be useless on a high-RTT path; frequent keyframes speed recovery and layer switching but spike bitrate and encoder load.

Do not optimize only average bitrate. Real calls experience burst loss, queue buildup, handoffs between Wi-Fi and cellular, CPU throttling, camera stalls, and asymmetric links. Quality logic needs hysteresis to avoid rapidly switching resolution or topology.

6. Codecs, simulcast, and scalable video coding

Endpoints negotiate codecs and parameters. Interoperability requirements provide a baseline, while product support for additional codecs varies by browser, hardware, licensing policy, and deployment. Hardware acceleration can matter more than theoretical compression efficiency because software encoding drains batteries and constrains multiparty layouts.

For group calls, an SFU needs multiple quality choices without decoding and re-encoding every stream. Two common techniques are:

  • Simulcast: the sender encodes multiple independent spatial versions, for example low, medium, and high. The SFU selects an encoding for each receiver. It is operationally mature but increases publisher uplink and encoder work.
  • Scalable Video Coding (SVC): one encoded stream contains temporal or spatial dependency layers. The SFU forwards an appropriate subset. It can be more bandwidth-efficient, but browser/codec interoperability and layer-switch behavior must be validated for the target clients.

Receiver-driven selection uses viewport size, active-speaker state, available bandwidth, device capability, and subscription policy. The SFU should avoid sending ten high-resolution streams to a phone that displays one large tile and several thumbnails.

Screen sharing differs from camera video. Text and slides benefit from higher spatial detail and lower frame rate; motion-heavy sharing needs more temporal quality. Treat screen-share bitrate, content hints, and active-speaker policies separately.

7. Data channels

RTCDataChannel carries arbitrary messages. The protocol stack supports multiple channels, ordered or unordered delivery, and full or partial reliability. Typical uses include cursor position, game state, in-call control, whiteboard operations, peer file transfer, and low-latency metadata.

Choose semantics explicitly:

// Reliable and ordered: chat or critical control.
const control = pc.createDataChannel("control", { ordered: true });

// Unordered and partially reliable: position updates where freshness wins.
const state = pc.createDataChannel("state", {
  ordered: false,
  maxRetransmits: 0
});

Data channels are not an excuse to ignore backpressure. send() can enqueue faster than the network drains. Track bufferedAmount, set bufferedAmountLowThreshold, pause producers, coalesce stale state, and chunk large transfers. Multiple SCTP streams reduce some cross-stream head-of-line effects, but channels in one association still share transport resources and congestion behavior.

For durable chat, compliance records, or multi-device delivery, use a server-backed messaging system rather than treating the data channel as the source of truth. The channel can carry the low-latency copy while the durable service assigns IDs, stores messages, and supports replay.

8. Topology choices

Direct one-to-one

Each endpoint sends media directly to the other, with TURN when needed. This minimizes server media handling and can be cost-effective, but it complicates recording, moderation, network policy, quality troubleshooting, and seamless migration. A TURN-relayed “peer-to-peer” call still consumes server bandwidth.

Mesh

Every participant sends a separate stream to every other participant. For N people, the room has N(N-1) directed media flows. Client uplink grows with N-1, so mesh becomes unattractive quickly for video, especially on mobile devices.

SFU

Each publisher sends one set of streams or layers to an SFU. The SFU forwards selected packets to receivers without fully composing the video. This keeps client uplink roughly constant while shifting bandwidth, routing, and state into the server fleet. It is the default architecture for many interactive group products.

MCU

An MCU decodes, mixes or composites, and re-encodes media. Participants receive one composed output. This can simplify thin clients, interoperate with legacy systems, or create a fixed broadcast layout, but it is compute-intensive, adds latency, and reduces per-participant layout flexibility.

Broadcast/CDN hybrid

A host or small stage publishes with WebRTC to an ingest service or SFU. A large passive audience receives a CDN-friendly stream. This trades some latency for massive fan-out and lower unit cost. A live auction, town hall, or sports stream may use WebRTC only for hosts and interactive bidders, while most viewers use low-latency segmented streaming.

Decision table

DecisionPrefer the first option when…Prefer the second option when…Senior caveat
Direct P2P vs SFUOne-to-one calls, minimal server media handling, and no server-side processing dominate.Group calls, recording, moderation, quality control, or predictable routing dominate.TURN usage can erase much of the P2P bandwidth advantage; measure relay ratio.
Mesh vs SFURooms are tiny, clients are powerful, and simplicity is worth duplicate uplink.Rooms can grow, mobile clients matter, or adaptive subscriptions are needed.Define the hard room-size cutoff and migration behavior rather than saying “small.”
SFU vs MCULow latency, per-user layouts, and scalable packet forwarding dominate.One composed stream, legacy endpoints, or centralized processing dominates.Hybrid systems may use SFU forwarding plus selective server-side composition/recording.
Simulcast vs SVCBroad browser interoperability and independent encodings are preferred.Supported clients/codecs make layered coding efficient.Validate layer switching, hardware acceleration, and fallback on real devices.
STUN/direct vs TURN relayLowest path latency and relay cost dominate.Restrictive networks, privacy policy, or deterministic routing requires relay.Always provide TURN fallback; “STUN-only” is a reliability defect.
Renegotiate vs replaceTrack()Media sections, directions, or capabilities change materially.The source changes within already negotiated bounds.Implement collision-safe negotiation because either side may trigger it.
Data channel vs WebSocketPeer-local low-latency state and partial reliability are valuable.Server authority, durable history, fan-out, or offline delivery dominates.It is common to use both, with the server as source of truth.
WebRTC vs CDN streamingSub-second interaction and two-way media dominate.Audience scale and delivery efficiency dominate over conversational latency.Split participants into stage and audience tiers instead of forcing one transport onto all.
Transport encryption vs E2EEServer processing, moderation, recording, and transcription are required.The server must not access media content.E2EE moves complexity into key management, membership, recovery, and feature trade-offs.

Quantitative reasoning

The point of interview arithmetic is not to predict an exact invoice. It is to expose the dominant terms and test whether the architecture can plausibly meet the workload.

Common failure modes and operational signals

FailureWhat users seeLikely causesSignals and response
Permission or device failureJoin blocked, black video, no microphoneUser denial, OS privacy setting, device busy, removed hardwareTrack permission/error codes separately; provide device test and actionable recovery.
Signaling connected but no mediaUI says joined; remote remains blankSDP generation mismatch, missing candidates, stale session, SFU publish failureTrace join stages with session/correlation ID; compare signaling state, transceivers, ICE, and first RTP.
ICE stuck or failed“Connecting” followed by timeoutUDP blocked, TURN credentials/DNS failure, exhausted relay, wrong candidate policyBreak down selected candidate type, gathering time, checks, allocation errors, and region.
One-way audio/videoOne participant hears or sees only one directionSender muted/disabled, transceiver direction, routing bug, firewall asymmetry, decoder issueCompare sender outbound RTP with receiver inbound RTP; inspect bytes, packets, SSRC/MID mapping.
Frozen video with live audioLast frame remains while speech continuesVideo loss, missing keyframe, decoder overload, layer-switch bugMonitor frames decoded, freezes, PLI/FIR, NACK, packet loss, keyframe rate, CPU.
Robotic or clipped audioSpeech is distorted or missingLoss, jitter, queueing, CPU starvation, bad audio processingTrack RTT, jitter, concealed samples, audio level, jitter-buffer delay, device CPU.
Quality oscillationResolution repeatedly rises and fallsNo hysteresis, bandwidth estimate instability, competing flowsRecord layer/bitrate changes, available bitrate, queue delay; use dwell time and conservative upgrades.
Data-channel memory growthUI lag or tab crashProducer ignores bufferedAmount; large reliable sendsAdd queue limits, bufferedamountlow, chunking, coalescing, and disconnect policy.
TURN region overloadCalls fail mainly on enterprise/mobile networksRelay autoscaling or bandwidth limit, credential service outageAlert on allocation failure, throughput, active allocations, packet loss, and regional saturation.
SFU hot roomA few rooms dominate one nodeCelebrity room, poor placement, recording/subscription amplificationTrack per-room ingress/egress and CPU; isolate or shard exceptional rooms.
Deployment disconnect waveCalls drop during rolloutNo draining, abrupt process stop, incompatible signaling versionsStop new room placement, drain sessions, preserve resume compatibility, and jitter reconnects.
Network handoffCall freezes after Wi-Fi/cellular changeCandidate path invalid; no ICE restart or slow recoveryDetect disconnected/failed, attempt bounded ICE restart, preserve room identity and publications.
Regional failureLarge correlated call lossSFU/control-plane outage, network partition, dependency failureMulti-region SLOs, evacuation drills, failover tokens, spare capacity, and reconnect throttling.

Production observability

Join funnel

Measure each stage separately:

  1. page/app ready;
  2. permission requested and granted;
  3. signaling authenticated;
  4. room allocated;
  5. offer/answer completed;
  6. first ICE candidate gathered;
  7. ICE connected;
  8. DTLS connected;
  9. first RTP packet sent/received;
  10. first audio sample or video frame decoded/rendered.

A single “join failed” counter cannot tell whether the problem is browser permissions, TURN, signaling, SFU placement, or media decoding. Track time-to-first-media percentiles and failure reason by browser, version, OS, network, geography, candidate type, and server build while respecting privacy constraints.

Media quality

Useful metrics from browser statistics and server telemetry include:

  • bytes and packets sent/received;
  • packet loss, RTT, jitter, and jitter-buffer delay;
  • target, encoded, and available bitrate;
  • frames encoded/decoded, frame rate, resolution, dropped frames, and freezes;
  • NACK, PLI, FIR, retransmission, and keyframe counts;
  • audio concealment and interruption signals;
  • selected local/remote candidate type and relay usage;
  • data-channel state and buffered amount;
  • CPU, memory, event-loop lag, encoder utilization, and thermal/battery indicators where available;
  • per-SFU room, publisher, subscriber, ingress, egress, packet-loss, and queue metrics.

getStats() fields and browser behavior evolve, so production collectors need schema/version tolerance and server-side validation. Do not equate “packets delivered” with good user experience; correlate transport metrics with freezes, audio interruptions, and user feedback.

Synthetic and active testing

Run controlled probe calls across regions, browser versions, network impairment profiles, and TURN transports. Include:

  • direct and relay-only paths;
  • UDP blocked, high RTT, burst loss, and constrained uplink;
  • screen share and device switch;
  • reconnect and ICE restart;
  • SFU drain and region failover;
  • long calls that cross token expiry and deployments.

Synthetic calls complement, rather than replace, privacy-conscious production telemetry.

Senior architecture lenses

Control plane versus media plane

The room service owns membership and policy. Signaling coordinates endpoints. SFUs forward packets. Recorders and transcription workers consume media. Analytics pipelines process events asynchronously. Keeping these responsibilities separate allows the control plane to use transactional storage while the media plane uses locality, packet throughput, and ephemeral state.

Do not put every packet-level event into a general-purpose database. Persist durable room facts and audit events; stream aggregate quality data; keep high-cardinality packet counters in telemetry systems with sampling and retention controls.

Room placement and affinity

Place a room on an SFU region or cluster based on participant geography, available capacity, compliance, and expected growth. Once a call is active, changing the media server is disruptive. Treat placement as a lease with explicit ownership and versioning.

For globally distributed participants, options include:

  • one “home” SFU near the majority or host;
  • cascaded SFUs connected over a managed backbone;
  • regional ingress SFUs with inter-SFU forwarding;
  • separate stage and audience paths.

Cascading reduces long-haul duplicate streams but adds topology, failure, ordering, and quality complexity. Define what happens if an inter-SFU link fails: local participants may still hear each other, the room may degrade, or clients may migrate.

Scaling and overload

Media servers are constrained by network packets/second and egress as well as CPU. Autoscaling on average CPU can react too late. Use admission control before saturation, reserve headroom for layer switches and keyframe bursts, and avoid placing a large room on a nearly full node.

Overload responses should preserve audio first. Possible degradation order:

  1. stop sending off-screen video;
  2. lower thumbnail layers and frame rates;
  3. pause non-speaker video;
  4. reduce screen-share quality carefully;
  5. preserve audio and essential control;
  6. reject new participants or move new rooms elsewhere.

State the policy before an incident rather than letting random packet loss decide which users suffer.

Recording and transcription

Choices include:

  • client-side recording;
  • SFU packet forwarding to isolated recorders;
  • server-side per-participant recordings;
  • real-time composition into one layout;
  • post-call composition from isolated tracks.

The design must define consent, visible indicators, access control, encryption, retention, deletion, legal holds, failed-segment recovery, A/V synchronization, and what happens during recorder failover. Recording should not overload the primary SFU or block the live call.

End-to-end encryption

With application-level E2EE, use a group key protocol or carefully designed key distribution, rotate keys on membership changes, authenticate participant devices, and prevent removed users from receiving future content. Decide whether metadata such as participant IDs, speaking activity, codec layers, and packet timing remains visible to the SFU.

Features that need media access—cloud recording, transcription, content moderation, noise suppression, and server-side composition—must be redesigned, moved to trusted endpoints, or explicitly unavailable. “E2EE enabled” is not a complete design until recovery and multi-device membership are specified.

Migration and deploys

For control-plane changes, version signaling messages and support mixed client/server versions. For SFU changes, drain nodes by stopping new room placement, let calls finish within a maximum window, and only force migration when required. For a forced migration, issue a new allocation, reconnect with jitter, preserve participant identity, deduplicate join events, and prevent double publication.

Codec or topology migrations should be capability-based and gradual. Shadow quality metrics, canary by room, retain rollback, and avoid requiring every client version to update simultaneously.

Interview question ladder

Q22.1 foundation

What does WebRTC provide, and what must the application still build?

Show strong-answer signals

Browser media capture; RTCPeerConnection; negotiation and adaptive encrypted transport; ICE/STUN/TURN; data channels; signaling is intentionally unspecified; application still owns identity, room discovery, permissions, moderation, durable state, UI, recording, and operations.

Q22.2 foundation

Explain the difference between ICE, STUN, and TURN.

Show strong-answer signals

ICE is the connectivity-establishment procedure; STUN helps discover mapped addresses and supports checks; TURN allocates a relay when direct connectivity fails or policy requires it; candidates are exchanged through signaling; relay improves reachability but costs bandwidth and may add latency.

Q22.3 foundation

Walk through a one-to-one call setup.

Show strong-answer signals

Permission/capture; authenticated signaling; create peer connection and add tracks; offer/answer; trickled candidates; candidate-pair checks and nomination; DTLS and SRTP establishment; first RTP and remote track; liveness/quality monitoring; teardown and resource cleanup.

Q22.4 intermediate

A call works on home Wi-Fi but fails on a corporate network. How do you debug it?

Show strong-answer signals

Compare ICE gathering/check states and candidate types; verify TURN UDP/TCP/TLS reachability and credentials; inspect DNS, certificates, proxy/firewall policy, allocation failures, and port exposure; reproduce with relay-only; distinguish signaling, ICE, DTLS, and first-RTP failures; do not “open random ports” without evidence.

Q22.5 intermediate

When is renegotiation needed, and how do you avoid offer collisions?

Show strong-answer signals

Adding/removing media sections, direction or capabilities can trigger negotiation; replaceTrack() can handle compatible source changes; use transceivers and negotiationneeded; implement perfect negotiation with polite/impolite roles, collision detection, rollback, and stale-message/session generation handling.

Q22.6 intermediate

How would you use a data channel for a multiplayer game or collaborative cursor?

Show strong-answer signals

Unordered/partially reliable updates for rapidly superseded position data; reliable ordered channel for critical commands; sequence numbers and application reconciliation; bufferedAmount backpressure; message-size/chunking limits; server remains authoritative where cheating or durability matters.

Q22.7 senior

Design a 12-person video meeting.

Show strong-answer signals

Clarify resolution, mobile mix, screen share, recording, regions, SLO; choose SFU over mesh; simulcast/SVC and subscription policy; active speaker and thumbnail layers; signaling/control plane separate from media plane; TURN fallback; room placement; join funnel and media metrics; drain/reconnect behavior; bandwidth calculation and audio-first overload policy.

Q22.8 senior

How would you operate one million concurrent WebRTC participants globally?

Show strong-answer signals

Quantify rooms, participant distribution, bitrate, relay ratio, PPS, egress, and headroom; regional control/media planes; anycast/geo routing only for initial placement, not transparent session migration; TURN and SFU capacity metrics; admission control; cascaded SFUs where justified; fleet draining; synthetic probes; reconnect-storm protection; cost attribution by tenant/region/candidate type.

Q22.9 senior

The product requires E2EE, recording, and transcription. What trade-offs do you surface?

Show strong-answer signals

Transport encryption is not E2EE; an SFU normally can access media; E2EE prevents ordinary server-side recording/transcription; possible trusted client recorder, user-authorized bot endpoint, enclave-like trust model, or mutually exclusive modes; key rotation and membership; consent and indicators; explain security boundaries honestly rather than claiming all features coexist automatically.

Q22.10 staff / stretch

Design regional failure recovery for ongoing calls.

Show strong-answer signals

Active media connections cannot be moved invisibly; preserve room/control state in another region; pre-provision spare capacity; client reconnect tokens and bounded ICE restart/full reconnect; full jitter and admission control; staged recovery by audio/host/room priority; deduplicate participant state; reason about cascaded-SFU partitions; exercise the plan regularly.

Q22.11 staff / stretch

How would you migrate from one SFU implementation or codec strategy to another?

Show strong-answer signals

Define stable signaling and room abstractions; capability negotiation; dual-stack or room-level canaries; shadow metrics; avoid mid-call migration unless necessary; drain old rooms; compare join success, first-media time, packet loss, freezes, CPU, egress, and client compatibility; rollback criteria; recording/transcription compatibility; long-tail browser versions.

Q22.12 staff / stretch

Choose among WebRTC, WebSocket, WebTransport, and low-latency CDN streaming for a live auction.

Show strong-answer signals

Segment roles: auctioneer and selected bidders need interactive WebRTC; bids require server-authoritative durable APIs, not only peer data; large passive audience can use CDN delivery; WebSocket/SSE can carry price/state updates; WebTransport is client-server transport, not a drop-in browser conferencing stack; discuss latency fairness, clocking, moderation, replay, and failure fallback.

Design drills

Drill A Telehealth call with recording

Design a two-party call between patient and clinician with optional interpreter, regulated recording, waiting room, and a 99.95% successful-join target.

What to cover — open after attempting

Cover:

  • P2P versus SFU despite the small room;
  • TURN and enterprise/hospital networks;
  • identity, consent, waiting-room authorization, and session timeout;
  • recording isolation, encryption, retention, and audit trail;
  • degraded audio-only mode;
  • device test and support diagnostics;
  • region/compliance placement and outage recovery.

A strong design may choose an SFU for deterministic routing, recording, supportability, and interpreter insertion even though direct P2P would reduce normal media-server cost.

Drill B Hybrid company meeting

Design a meeting with 20 interactive participants, 300 view-only employees, screen sharing, captions, and recording.

What to cover — open after attempting

Cover:

  • interactive participants on an SFU;
  • whether viewers subscribe through the SFU or a separate broadcast path;
  • simulcast/SVC layers and screen-share policy;
  • active-speaker and stage membership;
  • caption pipeline and synchronization;
  • moderator controls and durable room state;
  • per-room bandwidth calculation;
  • viewer promotion to the stage without a full page reload.
Drill C Global live auction

Design one auctioneer, up to 100 approved real-time bidders, and 50,000 viewers across three continents.

What to cover — open after attempting

Cover:

  • fairness and acceptable video/state latency;
  • authoritative bid submission and ordering separate from media;
  • WebRTC stage and regional SFUs for bidders;
  • CDN path for passive viewers;
  • TURN/privacy policy;
  • synchronized auction state with sequence numbers;
  • failover without duplicate bids;
  • regional partitions and whether the auction pauses;
  • observability for media quality and bid-processing latency.

Common weak answers and stronger corrections

“WebRTC is peer-to-peer, so no servers are needed.”

Show the stronger answer

Why it is weak: Signaling is required; TURN may relay; group calls commonly use SFUs.

Stronger: Separate signaling, connectivity, and media topology. Quantify direct versus relay/SFU traffic.

“STUN punches through the NAT.”

Show the stronger answer

Why it is weak: It oversimplifies the ICE procedure and ignores networks where direct checks fail.

Stronger: Explain candidate gathering/checks and TURN fallback.

“Use mesh for small rooms and SFU for large rooms.”

Show the stronger answer

Why it is weak: No cutoff or client/network assumptions are given.

Stronger: Compute per-client uplink/downlink and define a hard supported room size by device class.

“WebRTC guarantees low latency.”

Show the stronger answer

Why it is weak: Queueing, relay distance, jitter buffers, overload, and poor networks still dominate.

Stronger: State a latency budget and adaptation/placement strategy.

“All WebRTC calls are end-to-end encrypted.”

Show the stronger answer

Why it is weak: Standard transport encryption may terminate at an SFU.

Stronger: Define the encryption boundary and whether the media server can access content.

“We will reconnect when the connection fails.”

Show the stronger answer

Why it is weak: It ignores state, storms, duplicate identity, and capacity.

Stronger: Define ICE restart versus full reconnect, jitter, tokens, admission control, and room reconciliation.

“Use getStats() to monitor quality.”

Show the stronger answer

Why it is weak: No metrics, aggregation, privacy, or action is specified.

Stronger: Name join and media SLIs, dimensions, sampling, alerts, and automated degradation policies.

“Record on the SFU.”

Show the stronger answer

Why it is weak: Recording can create CPU, storage, consent, and failure coupling.

Stronger: Use isolated recorders or packet forks, define sync/retention, and keep live media independent.

“Send chat over the data channel.”

Show the stronger answer

Why it is weak: It loses durable/offline/multi-device behavior.

Stronger: Use the data channel for immediate delivery only when a durable server remains authoritative.

Primary standards and references