Lesson 5 of 9 · 26m
PeerConnection Lifecycle and Failure States
Instrument signaling, ICE connection, DTLS, and media flow as separate state machines so failures are diagnosable instead of mystical.
A WebRTC call does not fail as one object. It fails in layers: signaling never connected, offer/answer stalled, ICE found no pair, DTLS handshake failed, media flowed in one direction, or decoding stalled after connect. If your telemetry only says "call failed," you do not have observability. You have a shrug.
The browser exposes several state machines
These are related but not interchangeable:
signalingState stable / have-local-offer / have-remote-offer / closed
iceGatheringState new / gathering / complete
iceConnectionState new / checking / connected / completed / failed / disconnected / closed
connectionState new / connecting / connected / disconnected / failed / closediceConnectionState tells you about candidate connectivity. connectionState includes broader transport health. Neither proves media is decoding. A call can be connected while video is black because a sender track is muted, a codec negotiation is wrong, or the decoder is starved.
Instrument events at the edge of each transition
function attachDiagnostics(pc, sessionId) {
const emit = (name, extra = {}) => sendDiag({sessionId, name, ...extra});
pc.onsignalingstatechange = () => emit("signaling", {state: pc.signalingState});
pc.onicegatheringstatechange = () => emit("ice-gathering", {state: pc.iceGatheringState});
pc.oniceconnectionstatechange = () => emit("ice-connection", {state: pc.iceConnectionState});
pc.onconnectionstatechange = () => emit("connection", {state: pc.connectionState});
pc.onicecandidateerror = e => emit("candidate-error", {code: e.errorCode, text: e.errorText, url: e.url});
}The event stream is the difference between a reproducible incident and a user saying "it was spinning." Include client build, browser version, network type if available, and a session correlation ID.
Connected does not mean media
Measure actual flow with stats:
for (const report of (await pc.getStats()).values()) {
if (report.type === "inbound-rtp" && report.kind === "video") {
console.log({bytes: report.bytesReceived, framesDecoded: report.framesDecoded,
packetsLost: report.packetsLost, jitter: report.jitter, frameWidth: report.frameWidth});
}
}Bytes increasing means packets arrive. framesDecoded increasing means video is actually rendering. Audio needs additional care because comfort noise and silence suppression can make packet counters misleading.
Disconnected is a warning; failed is a verdict
Wi-Fi handoffs often produce disconnected first. Do not instantly destroy the call. ICE may recover or select another pair. A practical policy is:
disconnected for < 5 seconds keep UI connected, show recovering
disconnected for 5-15 seconds attempt ICE restart if media absent
failed perform controlled reconnect or rejoin
closed terminal; user or application ended itICE restart is not magic. It asks the browser to gather fresh candidates and re-test connectivity:
pc.restartIce();
// If needed, trigger renegotiation with iceRestart:
const offer = await pc.createOffer({iceRestart: true});Use it deliberately. Repeated restarts amplify signaling load and can interrupt otherwise recoverable paths.
DTLS failures are their own category
WebRTC media uses DTLS-SRTP. The fingerprint in SDP authenticates the peer's certificate for this session. If fingerprints mismatch, something is wrong in signaling or a middlebox is interfering. Browser APIs intentionally limit key access; do not try to export media keys in application JavaScript. Your normal diagnostic is the fact of failure plus fingerprints in controlled server logs, not packet decryption.
Timeouts need product meaning
A call setup timeout should answer what the user can do next: retry, rejoin, switch network, or contact support. Preserve the old peer connection until the replacement is ready when possible. Destroying state too early turns a network blip into a user-visible dropped call.
Field notes
iceConnectionState === "connected"can occur before the best pair is selected;completedmeans ICE finished its initial checks.- Safari, Chrome, Firefox, and embedded WebViews expose slightly different stats fields. Treat stats as best-effort telemetry, not schema-stable API.
ontrackfiring proves a receiver object exists, not that pixels are rendering. Attach stats-based flow checks before declaring victory.- Close peer connections explicitly on leave. Zombie audio capture indicators destroy user trust faster than almost any bug.
Was this lesson helpful?