跪拜 Guibai
← Back to the summary

WebRTC Latency Is Not One Number: Six Observation Points From ICE to Jitter Buffer

WebRTC Latency Debugging: Six Observation Points from ICE to Jitter Buffer

In a live session with 500 people, everything on the presenter side was normal, but on the audience side the video lagged behind the audio by about 1.4 seconds, and the comment area was flooded. The post-mortem found that encoding parameters, network bandwidth, and servers were all within normal ranges; the problem was on the receiving side's jitter buffer: the packet loss rate was 0.3%, but the inter-arrival jitter was 68 ms, and the buffer was pushed to over 240 ms. Combined with two-hop relay, the lag became stable. This case shows one thing: WebRTC latency is not a single metric, and watching only one number will never locate the root cause.

1. Split Latency into Four Segments First

End-to-end latency = capture + encoding + network transmission + jitter buffering + decoding and rendering. Each segment has a different magnitude and different observation methods; mixing them together only produces useless conclusions like 'network is bad'.

Segment Typical value Observation method Out-of-range signal
Capture + encoding 30-80 ms framesEncoded, totalEncodeTime Encoder queue keeps growing
Network transmission 20-150 ms currentRoundTripTime, packetsLost RTT variation > 50 ms
Jitter buffering 20-200 ms jitterBufferDelay, jitterBufferEmittedCount Single value > 200 ms
Decoding and rendering 10-50 ms framesDecoded, freezeCount Freeze count keeps increasing

2. Spot Check with getStats

Don't judge lag with your eyes. The standard statistics interface for WebRTC is RTCPeerConnection.getStats(). The W3C WebRTC 1.0 specification (w3c.github.io/webrtc-pc) defines the field meanings, and both Chromium and Firefox implement it. Sample once per second for 30 consecutive rounds to see trends instead of transient noise:

const pc = new RTCPeerConnection(config);
setInterval(async () => {
  const stats = await pc.getStats();
  stats.forEach((r) => {
    if (r.type === 'candidate-pair' && r.state === 'succeeded') {
      console.log('rtt', Math.round(r.currentRoundTripTime * 1000), 'ms');
    }
    if (r.type === 'inbound-rtp' && r.kind === 'video') {
      console.log('jitter', Math.round(r.jitter * 1000), 'ms');
      console.log('lost', r.packetsLost, 'recv', r.packetsReceived);
      console.log('jbDelay', Math.round((r.jitterBufferDelay / r.jitterBufferEmittedCount) * 1000), 'ms');
    }
  });
}, 1000);

Three Fields That Are Easy to Read Wrong

3. Six Thresholds for Judging WebRTC Latency

Once the data is available, run it through the following empirical thresholds; if a threshold is exceeded, keep digging down:

  1. currentRoundTripTime > 150 ms: first check whether ICE went through a TURN relay, then check physical distance.
  2. Packet loss > 2%: distinguish Wi-Fi air loss from uplink congestion by comparing the bytesSent growth rate in transport stats against the bitrate.
  3. jitter > 30 ms sustained for more than 5 seconds: check whether traffic crosses ISPs or goes through multi-hop forwarding.
  4. jitterBufferDelay average > 200 ms: the receiver is trading latency for smoothness; lower the buffer cap or improve packet loss.
  5. freezeCount or pauseCount increasing: decode-side resources are insufficient; check CPU usage and resolution.
  6. totalEncodeTime constantly above the frame interval: the sender is overloaded; lower bitrate or resolution instead of adding bandwidth.

4. Network-Side Reproduction and Verification

Browser stats only tell you what happened; locating why requires reproducing on the link. Under Linux, injecting jitter with tc is the most direct approach:

sudo tc qdisc add dev lo root netem delay 20ms 20ms distribution normal loss 1%
sudo tc qdisc del dev lo root

Wireshark's RTP analysis (Statistics -> RTP -> Show all streams) shows sequence number gaps and arrival times, which gets closer to the truth than reading stat fields. Chrome's chrome://webrtc-internals records each getStats round as charts, convenient for before/after comparison. Among third-party tools, Twilio Network Test gives an end-to-end network quality baseline, WebRTC Samples' peer connection demo is good for verifying candidate pairs, and Open Relay's TURN service can be used to compare RTT differences before and after relay.

5. Frequently Asked Questions

Q: Why is running getStats only once not enough? A single sample only shows an instantaneous value. Packet loss and jitter are statistical quantities; 1 second per round for 30 consecutive rounds is needed to distinguish sporadic from sustained degradation.

Q: RTT is normal but video still freezes. Where do I check first? Check the receiver's jitter buffer and decode time. RTT only covers the network round trip, not buffering and rendering, and those two segments together often exceed 300 ms.

Q: Does a TURN relay always increase latency? It adds one hop of RTT and the bandwidth cap of the relayed link, but if direct connection quality is poor, the relay can be more stable. Judge by the candidate-pair type and measured RTT, not by guessing.

6. Make Observation a Comparable Series

Locating an online issue depends on comparing the same metrics at two points in time, so the collection standard must be unified first:

Scenario Sampling frequency Recommended retention Purpose
Daily inspection 1s x 30 rounds Last 24 hours Discover sustained degradation
User report reproduction 250 ms x 120 rounds Single event package Capture transient jitter
Version comparison 10 minutes before and after release Two complete sequences Determine regression

The collection side only records six fields: currentRoundTripTime, packetsLost/packetsReceived, jitter, jitterBufferDelay/jitterBufferEmittedCount, growth of framesDecoded, and totalEncodeTime. Fewer fields makes cross-version comparison more reliable; storing the entire getStats dump as-is makes historical data incomparable because fields are added or removed. When retaining, also tag with region, network type, and version number so you can group problems among similar users. Otherwise what you have is just isolated sessions and you can't tell whether it's a single case or a general regression. When drawing conclusions, only cite comparison data with the same tags and collection standard.

7. Resolution Order

Follow the order of first confirming which segment is out of range, then adjusting the corresponding switch: RTT exceeding the threshold, check candidate pairs and relay; packet loss exceeding the threshold, check wireless and congestion control; jitter buffer exceeding the threshold, check the jitter source, then consider allowing more aggressive adaptation; decode freezing, lower resolution. Turn the six observation points into a dashboard checked before every release, which is far more efficient than digging through logs afterward. When you need a browser-side connectivity initial check, you can use ez4code.com's WebRTC detection page to first confirm whether candidate pairs can be established, then enter the per-segment inspection above.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

组合搭配函数

The picture lags the sound by 1.4 seconds. After checking everything, it turned out the jitter buffer was blown up. That root-cause hunt is ruthless enough. With the six thresholds laid out, sampling 30 rounds is enough to locate the issue. The approach is practical.