How WebRTC Selects the Best ICE Candidate Path

WebRTC establishes direct peer-to-peer connections using the Interactive Connectivity Establishment (ICE) protocol to bypass firewalls and Network Address Translators (NATs). This article explains how WebRTC gathers network pathways (ICE candidates), prioritizes them, tests their viability through real-time connectivity checks, and nominates the absolute best communication path for seamless data and media transfer.

1. Gathering and Classifying Candidates

When a WebRTC session begins, each peer gathers potential connection endpoints called ICE candidates. These candidates represent different ways a peer can be reached on the network and are classified into three primary types:

2. Prioritizing Candidate Pairs

Once both peers exchange their gathered candidates via a signaling server, WebRTC pairs each local candidate with each remote candidate to form “candidate pairs.”

WebRTC prioritizes these pairs using a standardized mathematical formula defined in RFC 5245. The priority calculation heavily favors paths with the lowest latency and overhead: * Host-to-Host pairs receive the highest priority. * Host-to-Reflexive and Reflexive-to-Reflexive pairs receive medium priority. * Relay-to-Relay or Relay-to-Host pairs receive the lowest priority, as routing traffic through an external server introduces latency and bandwidth costs.

3. Executing Connectivity Checks

With the candidate pairs sorted from highest to lowest priority, the ICE agent initiates connectivity checks. It does this by sending STUN binding request packets along each candidate pair sequence.

These checks serve two purposes: * Validation: They confirm whether a network path is actually open and capable of routing bi-directional traffic. * Consent: They ensure that the receiving peer is willing to accept incoming traffic from the sender, preventing malicious traffic redirection.

If a STUN request successfully receives a corresponding STUN response, that candidate pair is moved into a “Valid List.”

4. Nominated Selection

To prevent both peers from trying to select different paths, WebRTC assigns role dynamics: one peer acts as the Controlling Agent (typically the peer that sent the initial SDP Offer) and the other acts as the Controlled Agent.

The Controlling Agent is responsible for making the final decision on which valid path to use through a process called “nomination.” This is achieved using one of two methods:

Through this combination of systematic prioritization, active verification, and controlled nomination, WebRTC guarantees that peers always connect via the shortest, fastest, and most reliable network route available.