Library / Documentation

MDN: WebRTC connectivity

ICE, STUN, TURN and how peers find a path through NATs.

IntermediateWebSockets

By MDN contributors · MDN Web Docs · Added 2026-10-12

Open the docs

All content belongs to MDN contributors / MDN Web Docs. We only link to it and give credit. Report a problem

Learn this doc

About 30 min left. Your work is saved as you go.

What you want from these docs

MDN Web Docs documents a tool you may use. Decide what you want to do with it, then read only what answers that.

Ideas you will meet

WebSockets
Persistent bidirectional connections for real-time features.

What we already know about this

Our own lessons on these ideas. Read them here before you start, so it makes sense.

  • Core Concepts: How Things Actually Work · 7 minPolling, long polling, SSE and WebSocketsFour ways to get live updates to a browser, and how to choose between them.Read here

    The problem

    HTTP is request and response: the client asks. How does the server tell a browser something now?

    The four options

    TechniqueHowGoodWeak
    Short pollingClient asks every N secondsTrivial, works everywhereWasteful, delayed by N
    Long pollingClient asks; the server holds the request until there is news (or a timeout), then the client asks againNear real time, plain HTTPA held request per client, awkward at scale
    Server-sent events (SSE)One long HTTP response streams eventsSimple, auto-reconnect, text over HTTPOne-way only
    WebSocketsHTTP upgrades to a two-way connectionLow latency both waysStateful connections, more infrastructure

    Figure SDA-CORE-08-1 · The four options · © forcsguy.com

    Before: polling: keep asking

    After: WebSocket: server pushes

    What changed

    • No wasted requests when nothing has changed
    • Updates arrive the moment they happen
    • The server must hold many open connections

    Choosing

    • Updates are rare or delays are fine: polling.
    • The server pushes, the client mostly listens (feeds, scores, notifications, progress): SSE.
    • Both sides send often (chat, games, collaborative editing): WebSockets.

    Running persistent connections

    Connections are long-lived, so capacity is about how many connections a server can hold, not requests per second.

    • Put connection handling in servers that are separate from your stateless API.
    • Use heartbeats to detect dead connections, and reconnect with backoff and jitter.
    • Track which server holds which user so messages can be routed (a presence or session store), and use a pub/sub system between servers.
    • When a client reconnects, let it ask for what it missed (events after id X), because connections drop.
    • Authenticate on connect and again when tokens expire.

    More on this site

    Open this lesson with its quiz and exercise

  • Storage, Queues and Real-time · 12 minWebRTC: peer-to-peer media, signalling, NATs and media serversHow browsers exchange audio, video and data directly, how signalling, STUN, TURN and ICE get through firewalls, and when to add an SFU for group calls.Read here

    What WebRTC is

    WebRTC is a set of browser APIs and protocols for sending audio, video and arbitrary data directly between peers with low delay, for example for calls, screen sharing, games and file transfer. Media travels over UDP-based protocols and is encrypted (DTLS and SRTP) by default.

    The problem it must solve

    Two browsers behind home routers (NATs) usually have no public addresses and cannot just connect to each other. They first need to learn about each other, exchange what they can send and receive, and discover a network path that works.

    Figure SDA-SQR-06-1 · Setting up a call · © forcsguy.com

    The pieces

    • Signalling is not part of WebRTC; you build it (a WebSocket service works well). It carries the session descriptions (SDP offer and answer) and ICE candidates. It also handles rooms, who is online and permissions.
    • ICE (Interactive Connectivity Establishment) gathers candidate addresses and tests pairs to find a working path.
    • STUN servers tell a peer its public address as seen from the internet. They are cheap and light.
    • TURN servers relay the media when no direct path works, for example behind symmetric NATs or strict firewalls. Relaying costs real bandwidth, so use it as a fallback and monitor how often it is needed.
    • Codecs and adaptation: the connection adapts bitrate to the available bandwidth, and can drop quality instead of stalling.

    Figure SDA-SQR-06-2 · Direct path versus relay · © forcsguy.com

    Beyond one-to-one: mesh, SFU and MCU

    TopologyHow it worksGood forCost
    MeshEvery peer sends to every other peer2 to 4 peopleUpload grows with participants; weak devices struggle
    SFU (selective forwarding unit)Each client sends one stream to a server, which forwards it to others without decodingMost group calls and webinarsServer bandwidth; no transcoding, so low delay
    MCUServer decodes and mixes all streams into oneLegacy rooms, recording a mixed viewHeavy CPU, higher delay

    SFUs often use simulcast (the sender uploads a few quality layers) or scalable coding, so the server can send each receiver a layer that fits its bandwidth.

    Figure SDA-SQR-06-3 · Mesh versus SFU for a group call · © forcsguy.com

    Before: mesh: everyone sends to everyone

    After: SFU: send once to a server

    What changed

    • Each person uploads one stream instead of many
    • The server forwards streams without decoding them
    • You now run and scale media servers

    Design checklist

    • Own signalling with authentication and room permissions; it is the control plane and a security boundary.
    • Deploy STUN and TURN in several regions near users; measure the relay share and its bandwidth cost.
    • Choose SFU for group calls; scale it by placing each room on one server and spreading rooms across servers, with regional placement for latency.
    • Handle reconnection, device changes and poor networks (lower resolution, audio first).
    • Plan for recording (SFU-side or a bot participant) and moderation separately; they are not free with peer-to-peer.
    • For one-way live streaming to huge audiences, WebRTC is costly; HLS or DASH with a CDN scales better at higher latency (see the video streaming lessons).

    Real-world reading

    Open this lesson with its quiz and exercise

Go deeper on this

A path through videos, articles, other case studies and code on the same ideas as MDN: WebRTC connectivity.

  1. Warm upGet the vocabulary first.

  2. WatchHow others solve the same problem, on video.

    Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)

  3. ReadEngineers explain it in their own words.

  4. See it in another companyThe same ideas, a different system.

Keep learning

Loading community…