Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Concepts and Signalling

Perfect Negotiation

Learn the perfect negotiation pattern: polite and impolite peers, offer collisions (glare), rollback, ignoring offers, and a complete symmetrical implementation.

So far we gave Alice the job of calling and Bob the job of answering. Real apps are not so tidy. A user turns on their camera, so their side needs a new offer. At the same moment the other user shares their screen, so their side needs a new offer. Both offers cross on the wire. Each peer is in have-local-offer and receives an offer, which is illegal. This is called glare (an offer collision).

Perfect negotiation is a pattern, recommended by the WebRTC specification authors, that makes glare a non-event. Both sides run identical code. Either side may start a negotiation at any time, and collisions resolve themselves. It also removes the "who is the caller" question from your application.

The idea in three rules

  1. One peer is polite, the other impolite. This role is fixed per pair (decide by comparing ids, or let the server pick).
  2. If an offer arrives while we are making one (a collision), the impolite peer ignores the incoming offer: it insists on its own.
  3. The polite peer backs off: it accepts the incoming offer. Setting a remote offer in have-local-offer performs an implicit rollback of its own pending offer, and it then answers.

The polite peer's own change is not lost, because negotiationneeded fires again after the dust settles and starts a fresh round.

sequenceDiagram
  participant P as Polite peer
  participant I as Impolite peer
  P->>I: offer P (collision)
  I->>P: offer I (collision)
  Note over I: ignores offer P (impolite)
  Note over P: rolls back, accepts offer I
  P->>I: answer to offer I
  Note over P,I: negotiationneeded fires again on P
  P->>I: new offer P
  I->>P: answer

Both sides ended up with one agreed description, and nobody had to decide in advance who calls.

The code

This is the canonical implementation. Read it slowly: every line is there for a reason.

JavaScript
let makingOffer = false;
let ignoreOffer = false;

pc.onnegotiationneeded = async () => {
  try {
    makingOffer = true;
    await pc.setLocalDescription();                       // creates an offer
    signal.send({ description: pc.localDescription });
  } catch (err) {
    console.error(err);
  } finally {
    makingOffer = false;
  }
};

pc.onicecandidate = ({ candidate }) => signal.send({ candidate });

signal.onmessage = async ({ description, candidate }) => {
  try {
    if (description) {
      const offerCollision =
        description.type === 'offer' &&
        (makingOffer || pc.signalingState !== 'stable');

      ignoreOffer = !polite && offerCollision;
      if (ignoreOffer) return;

      await pc.setRemoteDescription(description);        // implicit rollback if needed
      if (description.type === 'offer') {
        await pc.setLocalDescription();                  // creates the answer
        signal.send({ description: pc.localDescription });
      }
    } else if (candidate) {
      try {
        await pc.addIceCandidate(candidate);
      } catch (err) {
        if (!ignoreOffer) throw err;                     // ignored offers' candidates may fail
      }
    }
  } catch (err) {
    console.error(err);
  }
};

Notes:

  • makingOffer covers the short gap while setLocalDescription() is still running, when signalingState is still stable but we are already creating an offer.
  • Candidates that belong to an offer we ignored will fail to apply; that failure is harmless, which is why the ignoreOffer check swallows it.
  • setLocalDescription() without an argument picks offer or answer depending on the current state. This is why modern code no longer calls createOffer() or createAnswer() by hand.

A complete, runnable collision

The example below connects two peers with a stand-in signalling object (messages are delayed by 30 ms), and makes both peers create a data channel at the same moment so that both fire negotiationneeded. Without perfect negotiation this would throw InvalidStateError; with it, both channels end up open.

Glare resolved by perfect negotiation

You should see both peers send an offer, a collision detected by each, the impolite side ignore the polite side's offer, and the polite side answer. Both channels open, and both states end stable. (With a data channel the polite side's channel is carried by the impolite offer, so no second round is needed; a new media track would fire negotiationneeded again.) Exact line order can vary slightly between runs.

Choosing who is polite

The roles only need to be different and stable for the pair:

  • Compare user ids: the peer with the smaller id is polite.
  • Let the server assign: the first to join a room is polite.
  • In a client-server design (a media server), make the server impolite and every client polite.

If both peers think they are polite, a collision makes both back off and nobody wins; if both are impolite, both ignore each other. Either way the connection stalls, so check the roles when you debug.

Why this beats the older approach

The older approach was "caller creates offers, callee only answers". It breaks as soon as the callee wants to add a track. You then need extra messages such as "please send me an offer", and your code has two different flows for the same job. Perfect negotiation has one flow, runs the same code on both sides, and also handles ICE restarts (covered later) with one more line: pc.restartIce() simply fires negotiationneeded.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is glare in WebRTC?

    Glare (an offer collision) happens when a peer receives an offer while it already has its own offer pending.
  2. 2. What does the impolite peer do when it detects a collision?

    The impolite peer insists on its own offer; the polite peer yields.
  3. 3. Why is makingOffer needed in addition to checking signalingState?

    There is a short window where an offer is being created but signalingState has not yet changed. makingOffer covers it.
  4. 4. What triggers the polite peer's own change to be negotiated again after it yielded?

    Because the connection still needs a negotiation for the change, negotiationneeded fires again once the signalling state is stable.

Summary

  • Perfect negotiation lets both peers run identical code and start negotiations at any time.
  • One peer is polite (yields and rolls back) and one is impolite (ignores colliding offers).
  • Use makingOffer plus signalingState to detect collisions, and setLocalDescription() with no argument to create the right description.
  • Ignore candidate errors that belong to an ignored offer; queue or catch other errors.

Next: Capturing Media with getUserMedia