HomeCurriculumWebRTC FundamentalsICE Candidate Harvesting & STUN/TURN Servers
ICE Candidate Harvesting & STUN/TURN Servers

ICE Candidate Harvesting & STUN/TURN Servers

STUN server binding requests, TURN relay server fallback, and ICE candidate gathering states.

DT
Authored by DevThesis Systems Editorial Team
Reviewed for Technical Accuracy & Code Determinism

Establishing a direct peer-to-peer media stream across heterogeneous enterprise and consumer networks requires overcoming unpredictable firewall topologies, dynamic NAT port assignments, multi-homed devices (e.g., laptops connected concurrently to Wi-Fi, Ethernet, and cellular hotspots), and asymmetric routing rules. No single networking address can be guaranteed to work across all network conditions.

To systematically discover, validate, and select the optimal communication path between two browsers, WebRTC relies on the Interactive Connectivity Establishment (ICE) framework (standardized in RFC 8445). ICE orchestrates two companion protocol utilities: STUN (Session Traversal Utilities for NAT) to discover external public reflexive addresses, and TURN (Traversal Using Relays around NAT) to provide guaranteed cloud relay fallback when direct hole punching is mathematically or administratively impossible.

This guide provides an exhaustive, university-grade examination of ICE architecture. We analyze candidate taxonomy, derive binary STUN XOR-mapped address encoding, dissect the mechanics of Trickle ICE, examine TURN allocation protocols, and formulate candidate pair prioritization algorithms.


The Interactive Connectivity Establishment (ICE) Architecture#

ICE operates as a systematic search algorithm: it gathers all possible network addresses (candidates) where an endpoint might receive packets, coordinates an asynchronous out-of-band candidate exchange with the remote peer, forms cross-product candidate pairs, and executes active STUN connectivity checks to select the lowest-latency, highest-priority valid connection path.

text
+---------------------------------------------------------------------------------------+
|                               The ICE Connection Pipeline                             |
+---------------------------------------------------------------------------------------+
|                                                                                       |
|   1. Candidate Harvesting:                                                            |
|      - Query local OS network interfaces ===> [ Host Candidates ]                     |
|      - Send Binding Request to STUN   ===> [ Server Reflexive Candidates (srflx) ]   |
|      - Send Allocate Request to TURN   ===> [ Relayed Candidates (relay) ]            |
|                                                                                       |
|   2. Trickle ICE Signaling:                                                           |
|      - Stream candidate strings asynchronously to remote peer over WebSocket          |
|                                                                                       |
|   3. Candidate Pairing & Prioritization:                                             |
|      - Compute Cartesian Product: Pairs = Candidates_local × Candidates_remote        |
|      - Sort pairs by Priority Score descending                                        |
|                                                                                       |
|   4. Connectivity Checks:                                                             |
|      - Transmit 4-way STUN Binding Requests across each candidate pair                |
|      - Validate symmetric reachability & measure Round-Trip Time (RTT)                |
|                                                                                       |
|   5. Nomination & Binding:                                                            |
|      - Controlling agent sends USE-CANDIDATE flag on best active pair                 |
|      - State transitions to 'connected' ===> SRTP Media & SCTP Data Channel Flow      |
|                                                                                       |
+---------------------------------------------------------------------------------------+

The Four Types of ICE Candidates#

During the harvesting phase, the browser inspects its local network adapters and queries configured STUN/TURN servers, generating four distinct classes of ICE candidates:

text
+----------------------------------------------------------------------------------------------------+
|                                    ICE Candidate Taxonomy Matrix                                   |
+-------------------+---------------+------------------------+---------------------------------------+
| Candidate Type    | Protocol Tag  | Network Location       | Path Characteristics                  |
+-------------------+---------------+------------------------+---------------------------------------+
| Host Candidate    | typ host      | Local physical adapter | Direct LAN / Same subnet (Zero NAT)   |
| Server Reflexive  | typ srflx     | Public NAT Gateway     | Traverses single or multi-NAT via STUN|
| Peer Reflexive    | typ prflx     | Inbound STUN source    | Discovered dynamically during checks  |
| Relayed Candidate | typ relay     | Public Cloud TURN Node | Traverses symmetric/enterprise relays |
+-------------------+---------------+------------------------+---------------------------------------+

1. Host Candidates (`typ host`)#

Host candidates represent the physical or virtual IP addresses bound directly to the operating system's local network interface cards (NICs):

  • Local Wi-Fi interface (e.g., 192.168.1.15:54200)
  • Local Ethernet adapter (10.0.0.42:54200)
  • Local IPv6 global unicast address (2001:db8::1:54200)
  • VPN virtual tunnel interface (10.8.0.5:54200)

If two peers reside on the same enterprise corporate intranet or domestic Wi-Fi network, their host candidates can connect directly with microsecond latency, completely bypassing external NAT routers.

2. Server Reflexive Candidates (`typ srflx`)#

When a peer resides behind a NAT gateway, its local host address (192.168.1.15) is unroutable across the public Internet.

  • The peer transmits a UDP packet to an external public STUN server.
  • The NAT translates the packet's source address to the NAT's public IP and an allocated port (e.g., 198.51.100.25:61001).
  • The STUN server inspects the UDP packet header, reads this allocated address, and returns it in the STUN payload.
  • This public endpoint is the Server Reflexive Candidate.

3. Peer Reflexive Candidates (`typ prflx`)#

Peer reflexive candidates are not harvested during initial initialization; they are discovered dynamically during the connectivity check phase.

  • If Peer A is behind a Symmetric NAT, the public port allocated when sending packets to Peer B's IP differs from the port allocated when sending packets to the STUN server.
  • When Peer B receives Peer A's incoming STUN connectivity check, Peer B inspects the source address on the raw IP packet header. If this address does not match any candidate previously signaled by Peer A, Peer B registers it as a Peer Reflexive Candidate and initiates response checks against it.

4. Relayed Candidates (`typ relay`)#

When strict Symmetric NATs or enterprise firewalls prohibit direct peer-to-peer UDP hole punching, the peer contacts a Traversal Using Relays around NAT (TURN) server.

  • The TURN server allocates a permanent public IP and UDP port on its own infrastructure (e.g., 203.0.113.50:34780).
  • All media packets sent by the peer to the TURN server are relayed across the public Internet to the destination peer.
  • Relayed candidates guarantee 100% connection reliability at the expense of server bandwidth and transit latency.

SDP Candidate String Grammar#

When an ICE candidate is discovered, WebRTC serializes it into a standardized single-line string attribute (a=candidate:...):

text
a=candidate:420194 1 udp 2122260223 192.168.1.15 54200 typ host generation 0
a=candidate:840281 1 udp 1686052607 198.51.100.25 61001 typ srflx raddr 192.168.1.15 rport 54200 generation 0
a=candidate:910294 1 udp 41885439 203.0.113.50 34780 typ relay raddr 198.51.100.25 rport 61001 generation 0

Parameter Breakdown#

  • `foundation` (`420194`): An arbitrary alphanumeric token shared by all candidates of the same type, protocol, and base address. ICE uses foundations to optimize check scheduling.
  • `component-id` (`1`): Specifies the component: 1 for RTP (media), 2 for RTCP (control telemetry). Under rtcp-mux, only Component 1 is generated.
  • `transport` (`udp`): Transport protocol (typically udp, but can be tcp for enterprise firewalls).
  • `priority` (`2122260223`): A 32-bit unsigned integer assigned by the browser indicating relative path preference.
  • `connection-address` (`198.51.100.25`): The public or private IP address.
  • `port` (`61001`): The transport port.
  • `typ <candidate-type>` (`typ srflx`): Indicates whether the candidate is host, srflx, prflx, or relay.
  • `raddr` & `rport`: The related base address and port from which this candidate was derived (e.g., a server reflexive candidate links back to its local host address).

STUN Protocol Mechanics & Binary Message Encoding#

STUN (Session Traversal Utilities for NAT, RFC 5389) is a lightweight, binary request-response protocol running over UDP or TCP on port 3478 (unencrypted) or port 5349 (TLS).

Binary Packet Header Format#

Every STUN packet begins with a fixed 20-byte header:

text
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0 0|     STUN Message Type     |         Message Length        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                         Magic Cookie                          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
|                     Transaction ID (96 bits)                  |
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  • STUN Message Type (16 bits): The two most significant bits are always 00. A Binding Request has type 0x0001; a Binding Success Response has type 0x0101.
  • Message Length (16 bits): Length of the payload attributes in bytes (excluding the 20-byte header).
  • Magic Cookie (32 bits): Fixed constant value 0x2112A442. Allows servers to distinguish STUN packets from multiplexed SRTP packets on the same UDP socket.
  • Transaction ID (96 bits / 12 bytes): Cryptographically random identifier matching responses to requests and preventing replay attacks.

Why `XOR-MAPPED-ADDRESS` Exists (Overcoming Application Layer Gateways)#

In early STUN versions (RFC 3489), the server returned the client's public IP address inside a plaintext attribute called MAPPED-ADDRESS.

  • The Failure: Many commercial NAT home routers feature buggy Application Layer Gateways (ALGs) designed to intercept and rewrite SIP/VoIP traffic. When the NAT ALG inspected the incoming STUN response packet, it saw a public IP address in the payload, assumed it was a private address needing translation, and corrupted the payload by rewriting it back to the local private IP!
  • The Solution: RFC 5389 introduced XOR-MAPPED-ADDRESS (Attribute Type: 0x0020). The STUN server applies a bitwise XOR between the client's public IP/Port and the fixed Magic Cookie and Transaction ID. Because the address bytes are obfuscated by the XOR cipher, dumb NAT ALGs cannot recognize the IP address, allowing the packet to traverse the router untouched. The browser simply repeats the bitwise XOR locally to recover the exact public IP.

TURN Server Protocol: Relayed Media Allocation#

When both peers sit behind restrictive Symmetric NATs or enterprise firewalls that block all non-HTTP outbound UDP traffic, direct hole punching fails. In these scenarios, WebRTC utilizes TURN (Traversal Using Relays around NAT, RFC 5766 / RFC 8656).

text
+---------------------------------------------------------------------------------------+
|                                 TURN Relay Architecture                               |
+---------------------------------------------------------------------------------------+
|  Peer A (Symmetric Corporate NAT)                     Peer B (Symmetric Mobile CGNAT) |
|         |                                                           |                 |
|         | 1. Allocate Request (Authentication)                      |                 |
|         v                                                           |                 |
|  +---------------------------------------------------------------+  |                 |
|  |                  TURN Server (Public Cloud IP:Port)           |  |                 |
|  |                  Allocated Relay: 203.0.113.50:48200          |  |                 |
|  +---------------------------------------------------------------+  |                 |
|         |                                                           |                 |
|         | 2. CreatePermission(Peer B Public IP)                     |                 |
|         v                                                           |                 |
|  +---------------------------------------------------------------+  |                 |
|  | Active Relay Bound: Forwards all packets between A & B        |  |                 |
|  +---------------------------------------------------------------+  |                 |
|         ^                                                           ^                 |
|         | 3. Encrypted SRTP Media Packets                           |                 |
|         +===========================================================+                 |
+---------------------------------------------------------------------------------------+

TURN Allocation Lifecycle#

  1. `Allocate Request`: The client transmits an Allocate Request over UDP, TCP, or TLS (port 443).
  2. Digest Authentication: The TURN server responds with 401 Unauthorized containing a NONCE and REALM. The client calculates an HMAC-SHA1 hash using ephemeral credentials generated via the TURN REST API time-limited secret mechanism (username = timestamp:userid, password = HMAC(secret, username)).
  3. Relayed Transport Address Assignment: Once authenticated, the TURN server allocates a public IP and ephemeral UDP port (the relayed candidate) and returns it in an XOR-RELAYED-ADDRESS attribute.
  4. ChannelBind Optimization: In raw TURN mode, every packet is wrapped in a 36-byte SendIndication header. To eliminate this bandwidth waste, the client issues a ChannelBind request, binding Peer B's address to a compact 16-bit channel number (0x4000 to 0x7FFE). Subsequent media packets require only a tiny 4-byte ChannelData header, slashing bandwidth overhead by 88%.

Candidate Pairing, Prioritization, and Connectivity Checks#

Candidate Priority Formula#

The ICE specification (RFC 8445) assigns each candidate a 32-bit unsigned integer priority determining the preference order for connectivity checks:

text
Priority = (2^24) · Type_Preference + (2^8) · Local_Preference + (2^0) · (256 - Component_ID)

where:

  • `Type_Preference` (0 to 126):

* Host candidates: 126 (Highest preference; zero infrastructure cost, minimal latency).

* Peer Reflexive candidates: 110.

* Server Reflexive candidates: 100.

* Relayed (TURN) candidates: 0 (Lowest preference; incurs cloud server bandwidth costs).

  • `Local_Preference` (0 to 65,535): Differentiates multiple interfaces of the same type (e.g., assigning higher preference to Wi-Fi over metered cellular 5G).
  • `Component_ID` (1 to 256): 1 for RTP media, 2 for RTCP telemetry.

Candidate Pair Priority#

When local and remote candidate lists are combined, each candidate pair (Local_Candidate, Remote_Candidate) is assigned a combined pair priority score:

text
Pair_Priority = (2^32) · min(G, D) + 2 · max(G, D) + (1 if G > D else 0)

where G is the controlling peer's candidate priority, and D is the controlled peer's candidate priority. This mathematical formulation guarantees that both peers compute the exact same sorted priority order independently, preventing distributed deadlock.

Vanilla ICE vs. Trickle ICE (RFC 8838)#

  • Vanilla ICE (Legacy): The browser gathers all host, STUN, and TURN candidates upfront before generating the SDP offer. Gathering takes 2 to 4 seconds while waiting for remote TURN allocation timeouts. The call setup experiences a frustrating multi-second delay before the phone even begins ringing.
  • Trickle ICE (Modern Standard): The initial SDP offer is generated immediately containing only local host candidates. As STUN and TURN candidates are harvested asynchronously in the background, the browser fires the pc.onicecandidate event, streaming candidate fragments over the signaling WebSocket in real-time. Call setup latency drops from ~3,000 ms down to under 300 ms.


Network Mobility: ICE Restarts & Zero-Downtime Mobile Handoffs#

Modern users frequently initiate video calls on home Wi-Fi and subsequently walk out the front door, transitioning onto 4G or 5G cellular networks.

The Socket Rupture Problem#

When a mobile device disconnects from Wi-Fi and connects to a cellular carrier:

  • The local IP address changes from 192.168.1.15 to a carrier-assigned CGNAT address 10.142.8.91.
  • The external NAT public IP changes completely.
  • The established UDP 5-tuple becomes instantly invalid; all existing packets routed to the old IP:port are dropped by the cellular tower.
  • The browser's iceConnectionState transitions to disconnected and subsequently to failed.

The ICE Restart Protocol#

Rather than terminating the call, WebRTC implements ICE Restart (RFC 8445 Section 9):

  1. The client detects network interface failure via operating system network state listeners or iceConnectionState === "disconnected".
  2. The client calls pc.createOffer({ iceRestart: true }).
  3. The browser generates a new SDP offer containing fresh ICE credentials:

* A completely new a=ice-ufrag (username fragment).

* A completely new a=ice-pwd (password).

  1. The fresh offer is signaled to the remote peer.
  2. Both peers harvest a fresh set of candidates on the new cellular interface, execute rapid STUN connectivity checks, nominate a new candidate pair, and seamlessly migrate the active SRTP media session to the cellular socket—all within ~300 milliseconds without dropping the active call.

Enterprise TURN Infrastructure: Coturn & Global Anycast#

Because relayed traffic accounts for 10% to 15% of all calls globally (and up to 35% in enterprise banking environments), production WebRTC platforms operate robust, globally distributed TURN server clusters.

Coturn Architecture#

The open-source coturn daemon is the industry standard for enterprise STUN/TURN deployments:

  • Multi-Threaded Asynchronous I/O: Leverages Linux epoll or FreeBSD kqueue to handle up to 50,000 concurrent UDP allocations per server instance.
  • Port 443 Fallback: Enterprise corporate proxies strictly block all outbound UDP traffic except on ports 80 and 443. Coturn listens on TCP port 443 and TLS port 443 (disguising TURN traffic as standard HTTPS), bypassing deep packet inspection firewalls.
  • Ephemeral Secret Authentication: Integrates with the TURN REST API:

```

Turn_Password = Base64( HMAC-SHA1( Secret_Key, Timestamp + ":" + Username ) )

```

This eliminates hard-coded credentials in client JavaScript; credentials expire automatically after 24 hours.

text
+---------------------------------------------------------------------------------------+
|                               Global Anycast TURN Routing                             |
+---------------------------------------------------------------------------------------+
|                                                                                       |
|   Client (Frankfurt) ---> [ Anycast IP: 198.51.100.1 ] ---> BGP Routes to Frankfurt   |
|   Client (Singapore) ---> [ Anycast IP: 198.51.100.1 ] ---> BGP Routes to Singapore   |
|   Client (São Paulo) ---> [ Anycast IP: 198.51.100.1 ] ---> BGP Routes to São Paulo   |
|                                                                                       |
+---------------------------------------------------------------------------------------+

By binding all global TURN nodes to a single BGP Anycast IP address, the client's DNS query automatically resolves to the geographically closest TURN relay, minimizing path-stretch latency and preventing international packet routing.


ICE Connection State Diagnostics & `getStats()` Telemetry#

The RTCPeerConnection API exposes a granular state machine tracking ICE health:

  • `iceConnectionState`:

* new: Gathering has not begun.

* checking: STUN connectivity checks are actively probing candidate pairs.

* connected: A valid candidate pair has been selected and media is flowing.

* completed: All candidate checks have finished.

* disconnected: Periodic STUN keep-alive pings failed for > 5 seconds (temporary packet loss).

* failed: All candidate pairs exhausted; direct connection failed (triggers ICE restart or TURN fallback).

  • `getStats()` Telemetry API:

Production monitoring engines poll pc.getStats() every second to extract critical operational telemetry:

* candidate-pair.currentRoundTripTime: Milliseconds RTT on the active socket.

* candidate-pair.bytesSent & bytesReceived: Egress/ingress volume.

* inbound-rtp.packetsLost & jitter: Audio/video degradation metrics.

Checkpoint Practice Problems#

Problem 1 (ICE Candidate Priority Calculation): A WebRTC endpoint configures an RTP media component (Component_ID = 1).

  • Candidate 1 is a local Wi-Fi Host Candidate (Type_Preference = 126, Local_Preference = 65,535).
  • Candidate 2 is a Server Reflexive Candidate (Type_Preference = 100, Local_Preference = 65,535).
  • Candidate 3 is a Cloud TURN Relayed Candidate (Type_Preference = 0, Local_Preference = 65,535).

Using the standard RFC 8445 priority formula:

text
Priority = (2^24) · Type_Pref + (2^8) · Local_Pref + (256 - Component_ID)
  1. Compute the exact 32-bit integer priority for Candidate 1 (Host).
  2. Compute the exact 32-bit integer priority for Candidate 2 (Srflx).
  3. Compute the exact 32-bit integer priority for Candidate 3 (Relay).
  4. Verify mathematically that Priority(Host) > Priority(Srflx) > Priority(Relay).

Solution:

Note constants:

  • 2^24 = 16,777,216
  • 2^8 = 256
  • 256 - Component_ID = 256 - 1 = 255
  • (2^8) · Local_Pref = 256 · 65,535 = 16,776,960
  • Constant tail = 16,776,960 + 255 = 16,777,215
  1. Candidate 1 (Host: Type_Pref = 126):

```

Priority_Host = (16,777,216 · 126) + 16,777,215

= 2,113,929,216 + 16,777,215 = 2,130,706,431

```

  1. Candidate 2 (Srflx: Type_Pref = 100):

```

Priority_Srflx = (16,777,216 · 100) + 16,777,215

= 1,677,721,600 + 16,777,215 = 1,694,498,815

```

  1. Candidate 3 (Relay: Type_Pref = 0):

```

Priority_Relay = (16,777,216 · 0) + 16,777,215

= 0 + 16,777,215 = 16,777,215

```

  1. Verification:

```

2,130,706,431 > 1,694,498,815 > 16,777,215

Priority(Host) > Priority(Srflx) > Priority(Relay)

```

The host candidate has the highest priority, ensuring direct LAN connections take precedence over STUN, and STUN takes precedence over costly TURN relays.


Problem 2 (STUN XOR-MAPPED-ADDRESS Bitwise Encoding): A STUN server detects a client's public IPv4 address as 198.51.100.25 and public port as 52,000.

  • The STUN Magic Cookie constant is 0x2112A442.
  • The port is encoded by XORing the 16-bit port with the most significant 16 bits of the Magic Cookie (0x2112).
  • The IPv4 address is encoded by XORing the 32-bit IP address with the 32-bit Magic Cookie (0x2112A442).

Compute:

  1. The hexadecimal representation of the raw port 52,000 and the resulting X-Port.
  2. The hexadecimal representation of the raw IP 198.51.100.25 and the resulting X-Address.

Solution:

  1. Port Encoding:

* Port 52,000 in hexadecimal:

52,000 = 12 · 4096 + 11 · 256 + 2 · 16 + 0 = 0xCB20.

* Most significant 16 bits of Magic Cookie: 0x2112.

* Apply bitwise XOR:

```

0xCB20 = 1100 1011 0010 0000

^ 0x2112 = 0010 0001 0001 0010

-------------------------------

0xEA32 = 1110 1010 0011 0010

```

X-Port = 0xEA32 (decimal 59,954).

  1. IP Address Encoding:

* Convert 198.51.100.25 to hexadecimal:

* 198 = 0xC6

* 51 = 0x33

* 100 = 0x64

* 25 = 0x19

* Raw 32-bit IP: 0xC6336419.

* Magic Cookie: 0x2112A442.

* Apply bitwise XOR:

```

0xC6336419 = 1100 0110 0011 0011 0110 0100 0001 1001

^ 0x2112A442 = 0010 0001 0001 0010 1010 0100 0100 0010

-------------------------------------------------------

0xE721C05B = 1110 0111 0010 0001 1100 0000 0101 1011

```

* Convert 0xE721C05B back to dotted decimal:

* 0xE7 = 231

* 0x21 = 33

* 0xC0 = 192

* 0x5B = 91

X-Address = 231.33.192.91.

The STUN server writes X-Port = 0xEA32 and X-Address = 231.33.192.91 into the packet payload, successfully cloaking the true coordinates from NAT ALGs.


Problem 3 (Trickle ICE vs. Vanilla ICE Setup Latency Timeline): An empirical network benchmark evaluates call setup duration:

  • Host candidate gathering: T_host = 15 ms.
  • STUN candidate gathering: T_stun = 180 ms.
  • TURN candidate allocation: T_turn = 1,200 ms.
  • Signaling transmission one-way latency: T_sig = 80 ms.
  • Direct P2P STUN connectivity check (Host/Srflx RTT): T_check = 40 ms.

Calculate:

  1. The total elapsed time to establish a connected media session under Vanilla ICE (where the caller waits for all candidates—including TURN—to finish harvesting before transmitting the SDP offer).
  2. The total elapsed time under Trickle ICE (where the initial offer is transmitted immediately upon host candidate harvesting, and host connectivity checks succeed directly).
  3. The absolute latency improvement achieved by Trickle ICE.

Solution:

  1. Vanilla ICE Timeline:

* Harvesting phase (waits for slowest candidate, TURN): 1,200 ms.

* Offer transmission over signaling: 80 ms.

* Answer generation & transmission back: 80 ms.

* Connectivity checks: 40 ms.

* Total Vanilla Setup Time:

```

T_vanilla = 1,200 + 80 + 80 + 40 = 1,400 milliseconds (1.40 seconds)

```

  1. Trickle ICE Timeline:

* Host candidate harvesting: 15 ms.

* Initial Offer transmitted immediately: 80 ms.

* Answer received back: 80 ms.

* Host candidate connectivity checks succeed: 40 ms.

* (STUN and TURN continue harvesting asynchronously in the background, but the connection is already active!).

* Total Trickle Setup Time:

```

T_trickle = 15 + 80 + 80 + 40 = 215 milliseconds (0.215 seconds)

```

  1. Latency Improvement:

```

Time Saved = 1,400 ms - 215 ms = 1,185 ms (1.185 seconds faster)

```

Trickle ICE accelerates connection establishment by 84.6%, delivering near-instantaneous call connection.


Problem 4 (TURN Server Bandwidth & Infrastructure Cost Sizing): A telecommunications platform handles C = 10,000 concurrent active video calls during peak hours.

  • Empirical network telemetry shows that 12% of all calls fail direct P2P hole punching (due to symmetric NATs/firewalls) and must route 100% of their media through a cloud TURN relay cluster.
  • Each video call consists of two peers, each streaming an average bidirectional bitrate of B = 1.5 Mbps (1.5 Mbps upload + 1.5 Mbps download per peer).
  • Cloud provider network egress bandwidth costs 0.05 per Gigabyte (GB).

Calculate:

  1. The number of calls that require TURN relaying.
  2. The total aggregate throughput bandwidth (in Megabits per second and Gigabits per second) handled by the TURN server cluster.
  3. The total monthly cloud bandwidth egress cost for the TURN cluster assuming peak traffic runs for 4 hours per day over a 30-day billing cycle (1 GB = 8,000 Megabits).

Solution:

  1. Relayed calls:

```

Relayed Calls = 10,000 · 0.12 = 1,200 concurrent calls

```

  1. Server Throughput Bandwidth:

For each relayed call, the server receives streams from Peer A and Peer B, and re-transmits them to Peer B and Peer A.

* Server Egress per call = 1.5 Mbps (to Peer B) + 1.5 Mbps (to Peer A) = 3.0 Mbps.

* Total server egress bandwidth:

```

Throughput = 1,200 calls · 3.0 Mbps = 3,600 Mbps = 3.60 Gbps

```

  1. Monthly Egress Cost:

* Total active hours per month:

4 hours/day · 30 days = 120 hours = 120 · 3,600 seconds = 432,000 seconds.

* Total megabits transferred:

3,600 Mbps · 432,000 seconds = 1,555,200,000 Megabits.

* Convert to Gigabytes:

1,555,200,000 Megabits / 8,000 Mbits/GB = 194,400 GB.

* Total cost:

194,400 GB · 0.05/GB = 9,720.00 per month.

The engineering team must budget 9,720 per month for TURN relay egress bandwidth to service the 12% symmetric NAT cohort.

Key Architectural Takeaways

  • Mastering ICE Candidate Harvesting & STUN/TURN Servers is critical for WebRTC Fundamentals production systems.
  • Strict invariant verification guarantees runtime stability and predictability.
  • Always follow industry-standard telemetry, logging, and security practices.

Hands-on Code Playground Available

Execute, edit, and experiment with code for this topic in the live sandbox.

Practice Check • Quick Quiz

Test Your Understanding

In WebRTC Fundamentals, what is the main purpose of ICE Candidate Harvesting & STUN/TURN Servers?

A
To guarantee deterministic performance and correctness for ice candidate harvesting & stun/turn servers.
B
To bypass all system security checks during execution.
C
To increase memory allocation overhead unnecessarily.
D
To force non-blocking single-threaded execution globally.