# WebRTC Explained: Understanding the Core Concepts

## What is WebRTC?

WebRTC (Web Real-Time Communication) is a set of browser APIs and protocols that lets two browsers send audio, video and data straight to each other, with no plugin. I walk you through the two core browser APIs, the signaling handshake, NAT traversal with STUN, TURN and ICE, and the topologies you pick from once more than two people are in a call.

## The Core Browser APIs

Two browser APIs do most of the work in any WebRTC app: one captures the media, the other moves it.

### 1\. navigator.mediaDevices.getUserMedia(): The Hardware "Ingestion" Engine

This API is the gateway to the user's physical devices. Behind this single Promise, the browser handles device access and permissions: it asks the user before any camera or microphone is switched on. If the user says no, the Promise is rejected. It also only works on secure origins (HTTPS or localhost).

```js
// run this inside an async function (or a module that allows top-level await)
const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });

// <video id="local" autoplay playsinline muted></video>
document.querySelector('#local').srcObject = stream;   // show your own camera
```

#### Anatomy of a MediaStream (object)

When getUserMedia() resolves, it returns a MediaStream object. Analogy: think of a MediaStream as a synchronized container holding independent, parallel data streams called MediaStreamTrack objects.

- When you ask for both audio and video, a resolved stream typically contains two tracks: one audio track and one video track. Ask for only one kind and you get just that track.
- Tracks operate independently. You can mute (disable) a video track while keeping an audio track enabled.
- Each track has an underlying identifier.

```js
const [audioTrack] = stream.getAudioTracks();
const [videoTrack] = stream.getVideoTracks();

videoTrack.enabled = false;                  // the other side now sees black frames
console.log(audioTrack.id, videoTrack.id);   // a unique id for each track
```

### 2\. RTCPeerConnection: The Real-Time Network Engine

If getUserMedia handles the media, RTCPeerConnection is what moves the media across the world. It wraps an incredibly complex stack of network routing, video encoding, compression and encryption into a single object. One RTCPeerConnection represents a single, exclusive pipeline between exactly two endpoints. The same connection can also carry arbitrary data through an RTCDataChannel.

When an instance is created with `new RTCPeerConnection(config)`, the browser sets up its built-in WebRTC engine, which works in the background and is responsible for:

**i. Codec Negotiation & Compression**

It takes the raw camera frames and compresses them in real time using highly efficient codecs (VP8/VP9 for video & Opus for audio). Which codec gets used is agreed during the SDP exchange, covered below. Every WebRTC browser must support VP8 and H.264 for video, and Opus and G.711 for audio, so two browsers always have something in common. VP9 and others are optional and depend on the browser.

**ii. Adaptive Bitrate Management (Congestion Control)**

It continuously tracks network conditions between the two devices. If peer's Wi-Fi drops from 50Mbps to 2Mbps, RTCPeerConnection automatically scales down the resolution, frame rate and bitrate on the fly to keep the call from freezing or dropping. You do not write any of this logic yourself.

**iii. Mandatory Encryption**

WebRTC forces encryption at the browser level. You cannot disable it. It uses DTLS (Datagram Transport Layer Security) for a secure cryptographic handshake and SRTP (Secure Real-Time Transport Protocol) to ensure that your video & audio frames cannot be read, even if they are intercepted by a malicious intermediary. Data channels are protected by DTLS too.

## Signaling (The Handshake)

WebRTC connects peers directly, but one must build a "Signaling server" to pass introduction messages back & forth before the WebRTC connection can start. WebRTC does not say how that server should work. WebSocket, `Socket.io` or plain HTTP requests all do the job. It only carries small text messages and never touches the media.

### SDP (Session Description Protocol)

Before sending video, browsers must agree on formats and media codecs. They do this by exchanging SDP text documents. An SDP document also carries the connection details the other side needs: ICE credentials, the candidate addresses gathered so far and a certificate fingerprint that is used later in the DTLS handshake. Resolution is not usually fixed here, because the browser keeps adapting it during the call.

Caller (generates offer) → sends it through the signaling server → Receiver (replies with answer)

Both peers start from the same setup. Create the connection and attach the handlers first, before any offer or answer, so that no early candidate or track is missed:

```js
const socket = io();   // a Socket.IO client connected to your signaling server
// <video id="remote" autoplay playsinline></video>
const remoteVideo = document.querySelector('#remote'); 

// the STUN and TURN servers are explained in the next section
const config = {
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' },
    { urls: 'turn:turn.example.com:3478', username: 'user', credential: 'secret' }
  ]
};
const pc = new RTCPeerConnection(config);

// send every candidate we discover to the other peer
pc.onicecandidate = ({ candidate }) => {
  if (candidate) socket.emit('ice-candidate', candidate);
};

// add the candidates the other peer sends us
// (in production, queue them until the remote description has been set)
socket.on('ice-candidate', (candidate) => {
  pc.addIceCandidate(candidate).catch(console.error);
});

// show the remote video once media arrives
pc.ontrack = (event) => { remoteVideo.srcObject = event.streams[0]; };
```

The caller creates the offer:

```js
async function startCall() {
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
  stream.getTracks().forEach(track => pc.addTrack(track, stream));

  const offer = await pc.createOffer();
  await pc.setLocalDescription(offer);
  socket.emit('offer', pc.localDescription);     // travels through the signaling server
}

// when the answer comes back
socket.on('answer', (answer) => pc.setRemoteDescription(answer).catch(console.error));
```

The receiver replies with an answer:

```js
socket.on('offer', async (offer) => {
  await pc.setRemoteDescription(offer);

  const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
  stream.getTracks().forEach(track => pc.addTrack(track, stream));

  const answer = await pc.createAnswer();
  await pc.setLocalDescription(answer);
  socket.emit('answer', pc.localDescription);    // goes back the same way
});
```

## NAT Traversal (Punching through Firewalls)

A browser typically only knows its local IP address, which is unreachable from outside its own network and useless for a device trying to connect from halfway across the world. Most homes and offices sit behind a NAT router that hands out private addresses like 192.168.1.5, and those mean nothing outside the network. STUN, TURN and ICE exist to get around this.

### i. Session Traversal Utilities for NAT (STUN)

A lightweight server that the browser pings to ask what its public IP looks like to the rest of the internet. Think of a STUN server as an internet mirror. Its only job is to look at your browser's incoming request and say, "Here is your public IP address & port". The same STUN message format is also reused later by ICE for the connectivity checks between the two peers.

### ii. Traversal Using Relays around NAT (TURN)

Sometimes, corporate firewalls completely block P2P connections. If STUN is a mirror, TURN is a middleman. A TURN server acts as a fallback relay. Instead of sending video directly to the peer, you stream it to the TURN server, which forwards it to the peer. Firewalls are not the only reason: some NAT types and networks that block UDP also force a relay. Since relaying video costs real bandwidth, TURN servers ask for a username and a credential. Because those are visible in your client-side code, production setups hand out short-lived ones. The relayed media stays encrypted, so the TURN server cannot read it.

You tell the browser which STUN and TURN servers to use through the `iceServers` list in the config, as shown in the setup code above.

### iii. ICE (Interactive Connectivity Establishment)

This is the negotiation algorithm inside RTCPeerConnection that gathers all possible network addresses (Local IP, STUN public IP, TURN relay). Each address is called a candidate. ICE then systematically tests pairs of them, one candidate from each peer, with connectivity checks and picks the best working route, preferring a direct path and using the relay only as a last resort.

| Candidate type | Where it comes from | Example |
| --- | --- | --- |
| host | The device's own local IP and port | 192.168.1.5:54321 |
| srflx (server reflexive) | The public IP and port a STUN server sees | 203.0.113.5:8000 |
| relay | An address allocated on the TURN server | Assigned by the TURN server |

There is also a rare fourth type, prflx (peer reflexive), which is discovered during the connectivity checks themselves. The preference order is host > prflx > srflx > relay. One practical detail: current browsers usually hide the real local IP in host candidates behind a random name ending in `.local`, to protect the user's privacy.

## STUN vs TURN

| Feature | STUN | TURN |
| --- | --- | --- |
| Primary Role | IP Discovery ("What is my public IP?") | Media Relay ("Forward my video for me") |
| Data Handled | Tiny binary packets for the address lookup, never media | Heavy media streams (Audio / Video) |
| Server Load | Extremely low | High (requires high bandwidth) |
| Success Rate | Enough for most calls to connect directly | Needed for the calls that can't connect directly |

Treat the 80/20 split as a rule of thumb, not a law. A well-known WebRTC consultant calls it [common lore](https://bloggeek.me/webrtc-turn/) and says in the comments that he has seen TURN usage anywhere from 0% to 50% depending on the users. Metrics from `callstats.io` covering 2015 to 2016 found that [22% of conferences](https://webrtchacks.com/usage-stats/) needed a TURN relay. Mobile and corporate networks lean on TURN the most, which is why you should always keep a TURN server in your setup.

## Connection Topologies

Once more than two people join, you have to decide how the media travels between them.

### i. Mesh Topology (P2P)

Every participant opens a direct "RTCPeerConnection" to every other participant. If there are 5 people in a room, the browser must maintain 4 distinct RTCPeerConnection instances simultaneously. If there are 4 people, each person is uploading their video 3 times. This method works well and keeps media-server cost at zero, but only up to 4-5 participants. You still need a signaling server and STUN/TURN, but no media passes through your own servers.

The numbers grow fast. With N people, each one holds N-1 connections, and the room as a whole has N x (N-1) / 2 links. Five people already means 10 links, and every phone or laptop has to encode and upload its video several times.

### ii. Selective Forwarding Unit (SFU)

Once a room grows past about 4-5 people, an SFU becomes the usual choice. Once a room grows past about 4-5 people, an SFU becomes the usual choice. Instead of sending video to everyone, clients send one single video stream to a central media server, which then acts as a router to distribute it to the rest of the room.

A few things worth knowing about SFUs:

- Each client uploads once (often as several quality layers of the same video, called simulcast), but still downloads one stream per other participant, so very large rooms need extra tricks such as showing only the active speakers.
- The server forwards packets without mixing them, which keeps its CPU cost far lower than an MCU (Multipoint Control Unit), the older design that decodes everything and mixes it into one video.
- Open-source SFUs such as mediasoup, Janus, LiveKit and Jitsi Videobridge are common starting points.
- Encryption now stops at the server, because each browser has an encrypted link to the SFU and not to the other users. True end-to-end encryption needs extra work on top.

## Putting It All Together

Here is the whole journey of a one-to-one call, in order:

1. Peer A calls getUserMedia() and gets a MediaStream with an audio track and a video track.
2. Peer A creates an RTCPeerConnection with the STUN and TURN servers in its config, adds the tracks and creates an SDP offer.
3. The offer travels through the signaling server to Peer B, who sends back an SDP answer the same way.
4. Both peers gather their ICE candidates and trade them through the signaling server.
5. ICE tests the candidate pairs and picks the best one that works.
6. A DTLS handshake sets up the encryption keys, and encrypted media flows straight between the peers, or through the TURN server if no direct path worked.

The diagram below shows the same flow with the servers and the NAT boxes. Its public addresses (203.0.113.5 and 198.51.100.7) come from the ranges reserved for documentation, so they are safe to reuse in examples, and the 192.168.x.x ones are ordinary private addresses. For simplicity it leaves out the rare prflx candidate type.

![webrtc-in-brief](https://cdn.hashnode.com/uploads/covers/6b051685d81ea9aa9caaeb47/898ef709-ac19-445f-ba13-137fc7c861c5.png align="center")

## Key Takeaways

- getUserMedia() captures the camera and microphone as a MediaStream made of independent tracks.
- RTCPeerConnection moves that media between two endpoints and handles codecs, adaptive bitrate and mandatory encryption for you.
- Signaling is not part of WebRTC, so you build it. It only has to carry the SDP offer and answer and the ICE candidates.
- STUN tells a browser its public address, TURN relays the media when no direct path works, and ICE picks the best path. Plan for TURN even if most calls will not need it.
- Mesh is fine for rooms of 4-5 people. Beyond that, move to an SFU.

## Further Reading

Main sources used for this article:

- [MDN: MediaDevices.getUserMedia()](https://developer.mozilla.org/docs/Web/API/MediaDevices/getUserMedia): permissions, secure contexts and tracks.
- [MDN: WebRTC connectivity](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Connectivity): how ICE, offers and answers fit together.
- [MDN: RTCIceCandidate type](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/type): host, srflx, prflx and relay candidates.
- [MDN: Codecs used by WebRTC](https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Formats/WebRTC_codecs): the codecs every browser must support.
- [RFC 7742: WebRTC Video Processing and Codec Requirements](https://datatracker.ietf.org/doc/html/rfc7742)
- [RFC 8827: WebRTC Security Architecture](https://www.rfc-editor.org/rfc/rfc8827.html): DTLS-SRTP and mandatory encryption.
- [WebRTC TURN: why you need it and when you don't](https://bloggeek.me/webrtc-turn/): the 80% rule of thumb.
- [WebRTC usage stats from callstats.io](https://webrtchacks.com/usage-stats/): the 22% TURN figure.
- [WebRTC architectures: advantages and limitations](https://medium.com/agora-io/webrtc-architectures-advantages-limitations-7016b666e1ae): mesh, SFU and MCU compared.
