0Pricing
Real-Time Streaming Systems (WebRTC + Live Data) · Lesson

Renegotiation and Connection State

Learn how WebRTC peer connections change over time: monitoring connection state, handling ICE restarts, and renegotiating SDP when media or network conditions change.

Renegotiation and Connection State is a free Real-Time Streaming Systems (WebRTC + Live Data) lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Real-Time Streaming Systems (WebRTC + Live Data) learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Connections Are Not Static

You have set up signaling, SDP, and ICE to create a connection. But a real session evolves: a user adds screen share, switches networks, or recovers from a drop. Handling these changes is called renegotiation and state management.

The Connection State Machine

An RTCPeerConnection reports its health through connectionState, moving through values like new, connecting, connected, disconnected, failed, and closed.

pc.onconnectionstatechange = () => {
  console.log('state:', pc.connectionState);
};

Reacting to State

Use the state to drive UI and recovery logic, such as showing a reconnecting spinner or tearing down a dead connection.

pc.onconnectionstatechange = () => {
  switch (pc.connectionState) {
    case 'connected': showCall(); break;
    case 'disconnected': showReconnecting(); break;
    case 'failed': restartConnection(); break;
    case 'closed': cleanup(); break;
  }
};

ICE Connection State

Separately, iceConnectionState tracks the connectivity checks. A transition to disconnected may be temporary, while failed usually means connectivity must be re-established.

pc.oniceconnectionstatechange = () => {
  if (pc.iceConnectionState === 'failed') {
    pc.restartIce();
  }
};

What Is an ICE Restart?

When a network path dies (for example, switching from Wi-Fi to cellular), the existing candidates no longer work. An ICE restart gathers fresh candidates and finds a new path without recreating the whole connection.

When Renegotiation Is Needed

Any change to the set of media tracks or transceivers requires a new offer/answer exchange. The browser tells you via the negotiationneeded event.

pc.onnegotiationneeded = async () => {
  const offer = await pc.createOffer();
  await pc.setLocalDescription(offer);
  signaling.send({ type: 'offer', sdp: offer });
};

Adding a Track Mid-Call

Adding a screen-share track during a call triggers negotiationneeded, prompting a fresh SDP exchange that updates the remote peer.

async function startScreenShare() {
  const screen = await navigator.mediaDevices.getDisplayMedia();
  const track = screen.getVideoTracks()[0];
  pc.addTrack(track, screen); // fires negotiationneeded
}

The Glare Problem

If both peers create offers at the same time, they collide. This is called glare. The fix is the perfect negotiation pattern, where one peer is polite and rolls back its offer when a collision occurs.

Perfect Negotiation Sketch

A polite peer rolls back on collision; the impolite peer ignores the incoming offer. This guarantees exactly one negotiation succeeds.

const offerCollision = (msg.type === 'offer') &&
  (makingOffer || pc.signalingState !== 'stable');
ignoreOffer = !polite && offerCollision;
if (ignoreOffer) return;
if (offerCollision) await pc.setLocalDescription({ type: 'rollback' });

Closing Cleanly

When a call ends, stop tracks and close the connection to free resources and release the camera and microphone.

function hangUp() {
  pc.getSenders().forEach(s => s.track && s.track.stop());
  pc.close();
}

Putting It Together

Robust WebRTC apps monitor connection state, restart ICE on path loss, renegotiate when tracks change, and handle glare with perfect negotiation. These behaviors turn a fragile demo into a reliable product.

Quick Check

Test your understanding of renegotiation.

Recap

You learned about connection state and renegotiation:

  • connectionState and iceConnectionState report health
  • ICE restart recovers from network path changes
  • negotiationneeded triggers a fresh SDP exchange
  • Perfect negotiation resolves glare; clean shutdown frees devices

These skills keep peer connections resilient over time.

Frequently asked questions

Is the “Renegotiation and Connection State” lesson free?

Yes — the full text of “Renegotiation and Connection State” is free to read here on the web, and the Real-Time Streaming Systems (WebRTC + Live Data) course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Real-Time Streaming Systems (WebRTC + Live Data) course, upgrade to CoddyKit PRO.

What will I learn in “Renegotiation and Connection State”?

Learn how WebRTC peer connections change over time: monitoring connection state, handling ICE restarts, and renegotiating SDP when media or network conditions change. You practise Real-Time Streaming Systems (WebRTC + Live Data) with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Real-Time Streaming Systems (WebRTC + Live Data)?

No prior experience is required. Real-Time Streaming Systems (WebRTC + Live Data) on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Renegotiation and Connection State” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Real-Time Streaming Systems (WebRTC + Live Data) lesson?

Yes. Every Real-Time Streaming Systems (WebRTC + Live Data) lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Role of Signaling Servers
  2. SDP: Session Description Protocol
  3. ICE Candidates and Connectivity
  4. Renegotiation and Connection State
← Back to Real-Time Streaming Systems (WebRTC + Live Data)