Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Peer Connections and ICE

The RTCPeerConnection Life Cycle

Learn the four RTCPeerConnection state machines (signaling, ICE gathering, ICE connection, connection), their events, the configuration object and how to close cleanly.

The RTCPeerConnection is the object every call revolves around. It is not a single connection but a small machine made of several parts that each have their own state: the offer/answer conversation, ICE candidate gathering, the network path check, and the overall transport. When someone says "my WebRTC call is stuck", the first debugging step is to read these four states. This lesson explains each one, shows them changing in a real connection and teaches you to configure and close a peer connection properly.

The four states

Property Event Question it answers Values
signalingState signalingstatechange Where are we in the offer/answer exchange? stable, have-local-offer, have-remote-offer, have-local-pranswer, have-remote-pranswer, closed
iceGatheringState icegatheringstatechange Are we still collecting candidates? new, gathering, complete
iceConnectionState iceconnectionstatechange Did the network path work? new, checking, connected, completed, disconnected, failed, closed
connectionState connectionstatechange Is the whole connection (ICE and DTLS) usable? new, connecting, connected, disconnected, failed, closed

connectionState is the one to show in your UI: it combines the ICE and DTLS transports, so connected really means "media can flow, encrypted". iceConnectionState is more detailed and the better source for debugging network problems.

stateDiagram-v2
  [*] --> new
  new --> connecting: ICE checks and DTLS start
  connecting --> connected: a working path and DTLS done
  connected --> disconnected: packets stop (maybe temporary)
  disconnected --> connected: path recovers
  disconnected --> failed: recovery gave up
  connecting --> failed: no path found
  connected --> closed: close()
  failed --> closed: close()

The connectionState machine. disconnected can heal itself; failed will not without an ICE restart.

Watching them all

Log every state change

Read the log from top to bottom. A typical run shows have-local-offer and gathering at the start, stable when the answer is applied, checking and then connected for ICE, connecting then connected for the whole connection, gathering finishing with complete, and finally all closed after close(). The exact interleaving can vary, but the order within each state machine never does.

Two details worth knowing:

  • iceConnectionState === 'completed' is rare in modern browsers; treat connected and completed the same.
  • Calling close() does not fire the state change events on the object you closed. Update your UI right after calling it.

Reacting to trouble

JavaScript
pc.onconnectionstatechange = () => {
  switch (pc.connectionState) {
    case 'connected':
      hideSpinner();
      break;
    case 'disconnected':
      showBanner('Connection unstable...');      // often heals by itself within seconds
      break;
    case 'failed':
      pc.restartIce();                            // try a new path (see the next lessons)
      break;
    case 'closed':
      cleanup();
      break;
  }
};

disconnected is a warning (a few seconds of silence or a network change); failed is final for that ICE session. The next lesson, ICE candidates and NAT, explains why paths fail, and trickle ICE and restarts shows recovery.

Configuring a connection

The constructor takes a configuration object. You can read it back with getConfiguration() and change some fields later with setConfiguration().

JavaScript
const pc = new RTCPeerConnection({
  iceServers: [
    { urls: 'stun:stun.example.com:3478' },
    { urls: ['turn:turn.example.com:3478?transport=udp', 'turns:turn.example.com:443?transport=tcp'],
      username: 'user', credential: 'secret' },
  ],
  iceTransportPolicy: 'all',       // 'relay' forces TURN only
  bundlePolicy: 'max-bundle',      // all media over one transport
  rtcpMuxPolicy: 'require',
  iceCandidatePoolSize: 0,
});
Option Purpose
iceServers STUN and TURN servers used to find and relay paths (chapter 6)
iceTransportPolicy all (default) or relay (only TURN: hides your IP, costs bandwidth)
bundlePolicy balanced (default), max-bundle, max-compat; prefer max-bundle when you control both ends
iceCandidatePoolSize Pre-gather candidates before an offer, shaving connect time
certificates Supply a long-lived DTLS certificate
Read the default configuration

You can change iceServers, iceTransportPolicy and the pool size after creation (useful when TURN credentials expire), but not bundlePolicy once a description has been applied.

Closing cleanly

A peer connection holds a UDP socket, a DTLS session and possibly media devices. When a call ends:

JavaScript
function hangUp(pc, localStream) {
  pc.getSenders().forEach((s) => s.track && s.track.stop());   // stop local tracks you own
  localStream?.getTracks().forEach((t) => t.stop());
  pc.ontrack = pc.onicecandidate = pc.onconnectionstatechange = null;
  pc.close();
}

After close() the object is dead: signalingState is closed, and methods such as createOffer() throw InvalidStateError. Create a new RTCPeerConnection for the next call; never reuse a closed one. In single-page apps, make sure unmounting a call view triggers this function, or the camera light and sockets leak.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which state is best for showing 'connected' in your UI?

    connectionState combines ICE and DTLS, so 'connected' means media can flow securely.
  2. 2. What does iceConnectionState 'disconnected' usually mean?

    disconnected is a warning state caused by lost connectivity. Only failed means that path will not recover on its own.
  3. 3. Which iceTransportPolicy value forces all traffic through a TURN relay?

    relay uses only relay candidates, hiding your IP from the peer at the cost of server bandwidth.
  4. 4. What should you do to start a second call after closing a peer connection?

    A closed connection cannot be reused.

Summary

  • A peer connection has four state machines: signaling, ICE gathering, ICE connection and overall connection.
  • Show connectionState to users; use iceConnectionState and the others to debug.
  • disconnected can heal, failed needs an ICE restart or a new connection.
  • Configure ICE servers, transport policy and bundling in the constructor; read back with getConfiguration().
  • Close by stopping tracks, clearing handlers and calling close(); create a fresh connection for the next call.

Next: ICE Candidates and NAT