Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Peer Connections and ICE

Trickle ICE and ICE Restarts

Learn trickle ICE for fast call setup, how end-of-candidates works, when to use restartIce, and how to recover from disconnected and failed connections.

Gathering all candidates can take a while. A STUN request may need hundreds of milliseconds, a TURN allocation more, and a slow server can add seconds. If you waited for every candidate before sending the offer, every call would start with an awkward pause. Trickle ICE solves this: send the offer immediately and trickle candidates to the other side one by one as they are found, while connectivity checks start as soon as the first pair is possible.

The second half of this lesson covers the opposite problem: a call that was fine but then lost its network path (the user walked from Wi-Fi to cellular). ICE restart gets a working path back without hanging up.

Trickle ICE in practice

You already used it: onicecandidate fires per candidate and you forward each to the peer, who calls addIceCandidate. The shape of the code:

JavaScript
pc.onicecandidate = ({ candidate }) => {
  if (candidate) signal.send({ type: 'candidate', candidate });
  // candidate === null means gathering has finished
};

signal.on('candidate', async ({ candidate }) => {
  await pc.addIceCandidate(candidate);
});

Compare this with the "wait for gathering" approach from your first loopback call:

Trickle ICE Wait for gathering
Time to first connectivity check As soon as one candidate exists After slowest candidate
Messages One per candidate One offer, one answer
Complexity Must queue early candidates Simple
Good for Production Demos, copy-and-paste signalling

The timing difference is easy to see. This example measures when the first candidate and the last candidate appear:

First candidate versus gathering complete

Without STUN or TURN servers all candidates arrive almost at once, so the gap is tiny here. With real servers, candidates arrive over hundreds of milliseconds, and the offer (shown as "offer ready") can leave long before the last one.

End of candidates

The final onicecandidate event has candidate === null. If you want to tell the other side explicitly that no more candidates will come, call pc.addIceCandidate(null) (or an empty candidate string) on the remote side; most apps skip this because the end is implied by timeouts and state.

Also be aware that candidates can keep coming after gathering is "complete" if the network changes (a new interface appears), and iceGatheringState can return to gathering.

When the path breaks

Network paths die for ordinary reasons: Wi-Fi to cellular, a VPN toggled, the laptop wakes from sleep, a NAT mapping expires. The browser keeps sending connectivity checks ("consent freshness") every few seconds. When they go unanswered:

  1. iceConnectionState becomes disconnected after about 5 seconds. Media freezes. This state can heal if packets resume.
  2. After roughly 30 seconds without recovery it becomes failed.

Your options in failed (or sooner, in disconnected):

  • Restart ICE: gather new candidates and run new checks on the same peer connection. Media tracks, data channels and DTLS session keep their identity.
  • Rebuild the connection from scratch (a heavier option, appropriate when the remote side has vanished).

Restarting ICE

pc.restartIce() marks the connection as needing a new ICE session; the next offer carries fresh ice-ufrag and ice-pwd values, which tell the other side to start over. You then negotiate as usual:

JavaScript
pc.restartIce();               // triggers negotiationneeded
// with perfect negotiation, your handler creates and sends the offer

If you are not using restartIce(), the older API is createOffer({ iceRestart: true }). Both produce an offer with new credentials; restartIce() plays well with negotiationneeded and is the preferred way.

Restart is most effective when both ends use perfect negotiation, because either side may start it and a restart on one side can collide with a normal renegotiation on the other.

Restart ICE on a live connection

The username fragment changes (that is the restart), yet the connection stays connected and the data channel keeps working: nothing the application owns was torn down.

A recovery policy

A sensible policy combines both signals:

JavaScript
let restartTimer;
pc.oniceconnectionstatechange = () => {
  clearTimeout(restartTimer);
  if (pc.iceConnectionState === 'disconnected') {
    // give it a few seconds to heal, then try a restart
    restartTimer = setTimeout(() => pc.restartIce(), 4000);
  } else if (pc.iceConnectionState === 'failed') {
    pc.restartIce();
  }
};
window.addEventListener('online', () => pc.restartIce());   // network came back

Add a limit (for example three restarts in a row) and a final fallback that tells the user and ends the call. Also remember that a restart needs a working signalling channel to carry the new offer, so reconnect that first.

Common mistakes

  • Treating disconnected as final and hanging up. Wait a few seconds.
  • Restarting in a tight loop. Back off between attempts.
  • Forgetting to apply candidates that belong to the new ICE session: after a restart, old candidates are invalid; the ufrag inside each candidate identifies its session.
  • Calling restartIce() on only one side without a way to negotiate. Use negotiationneeded.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of trickle ICE?

    Candidates are sent as they appear, so the connection can start without waiting for slow STUN or TURN lookups.
  2. 2. What does an onicecandidate event with candidate === null mean?

    A null candidate signals the end of gathering for that session.
  3. 3. How does an ICE restart show up in the SDP?

    New ICE credentials tell the other side to run a new ICE session on the same connection.
  4. 4. Which approach is best when iceConnectionState turns failed?

    restartIce keeps the application objects and often recovers the call; set a retry limit and a final fallback.

Summary

  • Trickle ICE sends the offer at once and candidates as they are found; queue candidates that arrive early.
  • disconnected can heal; after about 30 seconds the state becomes failed.
  • restartIce() issues an offer with new ICE credentials on the same connection, preserving tracks and channels.
  • Combine timers, the online event and retry limits into a recovery policy; both sides should use perfect negotiation.

Next: Transceivers and Senders