When using Javascript Client SDK, when we e.g. dis...
# ask-ai
c
When using Javascript Client SDK, when we e.g. disconnect wifi, the connecitonQuality and connectionState indicators are very slow to show any changes/issues. How can we implement a more responsive indicator to the user of network issues?
t
Thanks for reaching out, Benjamin. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to make your network issue indicator in the LiveKit JavaScript Client SDK more responsive, a great way is to use the
connectionQuality
property of a
Participant
and listen for
connectionQualityChanged
events. This way, you can update your UI on the fly based on how the user's network is doing. Here’s a simple way to get started: 1. Check out the
connectionQuality
property—it tells you the current network state (like Excellent, Good, Poor, or Lost). 2. Listen to the
connectionQualityChanged
event so you catch any changes right away:
Copy code
participant.on('connectionQualityChanged', (quality) => {
  updateConnectionIndicator(quality);
});
Then, you can update your UI however you like—maybe with icons, colors, or text—to show the connection status clearly. If you’re working with React, the
@livekit/components-react
library has a handy
useConnectionQualityIndicator
hook that makes this even easier. It helps you build a custom indicator without much hassle. Feel free to ask if you want more details or examples—I’m here to help! Sources: Room & Participant Management | livekit/livekit_composite | DeepWiki | examples/demo/demo.ts | examples/nextjs/pages/customize.tsx | Managing Video Quality During Network Congestion | Client SDKs | livekit/livekit_composite | DeepWiki
c
both of these are very slow to react, for quality at least 5 seconds delay and connection state sometimes more than 20 seconds
t
Hey there! Just to make sure I understand you correctly—are you hoping to speed up the updates for
connectionQuality
and
connectionState
that you already have, or would you be open to trying out some extra tools (like custom network monitoring) to get quicker responses? Let me know what works best for you!
c
either or both would be fine
t
Hey there! Just a quick note on why updates for
connectionQuality
and
connectionState
might be a bit delayed—it’s mainly because of server-side scoring intervals and some internal timers. But don’t worry, I’ve got some tips to help you optimize responsiveness or even set up your own custom monitoring: Optimizing Built-in Updates: • Try to keep clients geographically close to the LiveKit server or use region-aware URL providers to cut down on latency. • If you have access to server settings, you can tweak server-side scorer parameters to speed up update frequency. • Keep an eye on
trackStreamStateChanged
events for real-time feedback on congestion. Custom Monitoring for Faster Responsiveness: 1. Use WebRTC Statistics: You can grab metrics like packet loss, RTT, and jitter using
RTCPeerConnection.getStats()
. Here’s a quick example:
Copy code
async function collectConnectionStats(engine) {
  const pc = engine.pcManager?.publisher?.pc;
  if (!pc) return;

  const stats = await pc.getStats();
  stats.forEach(report => {
    if (report.type === 'outbound-rtp' || report.type === 'inbound-rtp') {
      console.log('Packet Loss:', report.packetsLost);
      console.log('RTT:', report.roundTripTime);
    }
  });
}
setInterval(() => collectConnectionStats(room.engine), 1000);
1. Monitor Data Channel Buffer: Listen for
DCBufferStatusChanged
events to spot congestion early. 2. Track Stream State: Use
trackStreamStateChanged
events to keep tabs on video stream pauses caused by congestion. If you want me to dive deeper into any of these options or have questions, just let me know—I’m here to help! Sources: Infrastructure & Deployment | livekit/livekit_composite | DeepWiki | pkg/rtc/room.go | src/room/Room.ts | Sources/LiveKit/Core/Room+SignalClientDelegate.swift | Voice Assistants | livekit/livekit_composite | DeepWiki
c
show me a complete javascript code client example using getStats()
t
Here's a complete JavaScript example that shows you how to use
getStats()
to keep an eye on network metrics like packet loss and RTT:
Copy code
// Function to collect WebRTC connection stats
async function collectConnectionStats(engine) {
  // Access the WebRTC PeerConnection (publisher in this case)
  const pc = engine.pcManager?.publisher?.pc; // Replace with subscriber if needed
  if (!pc) {
    console.error('PeerConnection not available');
    return;
  }

  // Get stats from the PeerConnection
  const stats = await pc.getStats();
  stats.forEach(report => {
    if (report.type === 'outbound-rtp' || report.type === 'inbound-rtp') {
      console.log('Packet Loss:', report.packetsLost);
      console.log('RTT:', report.roundTripTime);
      console.log('Jitter:', report.jitter);
      console.log('Bitrate:', (report.bytesSent * 8) / report.intervalMs, 'kbps');
    }
  });
}

// Example: Poll stats every second
setInterval(() => {
  collectConnectionStats(room.engine); // Replace 'room.engine' with your LiveKit Room instance's engine
}, 1000);
This code checks the WebRTC stats every second and logs important info like packet loss, RTT, jitter, and bitrate. Feel free to tweak it to update your UI or even set up alerts based on what you find. If you have any questions or need a hand with anything else, just let me know!