I have hosted livekit server and agent on my local...
# ask-ai
a
I have hosted livekit server and agent on my local machine. The customer connects to my server and the server connects to my agent. The customer is disconnected after around 5 seconds but returns no error. What could be the issue?
t
Thanks for reaching out, Talha. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I understand how frustrating it can be when a customer disconnects from your LiveKit server after just 5 seconds without any error message. Let’s explore some common reasons this might happen, so you can get to the bottom of it: • Silence Detection Timeout: Sometimes, if the system notices silence for 5 seconds, it might automatically disconnect the user. It’s a good idea to check your application logs for any silence detection messages. • Agent Connection Timeout: If your server expects an agent to connect within a certain timeframe (like 5 seconds) and that doesn’t happen, the connection could be closed. • Network Issues: Things like network blackouts, unclean client disconnects, or client crashes can also cause early disconnections. • Firewall or VPN Blocking: If the user’s network blocks WebSocket, WebRTC, or TURN connectivity, this might lead to a quick disconnect. • Server-Initiated Disconnection: Actions such as room deletion, participant removal, or identity conflicts might also trigger this behavior. To help you troubleshoot, here are some steps you can try: 1. Check your application logs for any silence detection or timeout messages. 2. Review your agent or application logic to see if there are any 5-second timeout settings. 3. Run connection tests to make sure network connectivity isn’t the issue. 4. Keep an eye on server-side logs for any automatic disconnection triggers. If you’d like, I’m here to help you dig into any specific area or walk you through these steps. Just let me know! Sources: Agent Testing & CI/CD | livekit/livekit_composite | DeepWiki | lib/controllers/app_ctrl.dart | Understanding the STATE_MISMATCH Disconnect Reason | Diagnosing Connection Errors with Connection Test Utility | Connecting to LiveKit | LiveKit Docs
a
Failed to connect to LiveKit: ConnectionError: could not establish pc connection at at timer ( ) at _ZoneDelegate.invokeTask ( ) at Object.onInvokeTask ( ) at _ZoneDelegate.invokeTask ( ) at ZoneImpl.runTask ( ) at invokeTask ( ) at ZoneTask.invoke ( ) at data.args.<computed> ( ) (anonymous)@ rejected@ this is present on the console of my web page, what does this mean?
t
I'm sorry to hear you're encountering the error
ConnectionError: could not establish pc connection
. This means that the WebRTC peer connection (PC) between your client and the LiveKit server couldn't be set up, often because the transport manager timed out while trying to connect. To help you get to the bottom of this, here are some steps you can try: 1. Use LiveKit's Connection Test tool to check your WebSocket, WebRTC, and TURN server connectivity. You can find it here: https://livekit.io/connection-test. 2. Look into possible network-related issues such as: ◦ Firewall settings that might be blocking necessary connections ◦ VPNs that could interfere with WebRTC traffic ◦ Restrictions on your corporate network 1. Take a look at your application logs for any extra error details that might give us more clues. If the connection tests don’t go through, it’s a good sign that something at the network level is blocking the connection. In that case, you might want to check your firewall settings, try temporarily disabling any VPNs, or reach out to your IT team to ensure LiveKit connections are allowed. Please feel free to reach out if you’d like help running these tests or understanding the results—I’m here to support you every step of the way! Sources: src/api/SignalClient.ts | Diagnosing Connection Errors with Connection Test Utility
a
port: 7880 log_level: info rtc: tcp_port: 7881 port_range_start: 50000 port_range_end: 60000 redis: address: localhost:6379 keys: APIbLLHJzVJJEei: ZSLMLLihE5l8sauRKnmNRIFm9nvC73Yf3k96QOWzbgE turn: enabled: true tls_port: 8365 domain: ws://localhost:7880 cert_file: /etc/pki/tls/certs/star.enteract.cloud.crt key_file: /etc/pki/tls/private/star.enteract.cloud.key what ports should I open in firewall to allow? tell me what single or range of ports and whether tcp/udp?
t
To help your LiveKit server connect smoothly, you'll want to make sure the following ports are open in your firewall: • TCP Ports: ◦ 7880 - This is the main API port (if you’re not using a load balancer) ◦ 7881 - Used for WebRTC TCP fallback ◦ 443 - HTTPS endpoint (if you have a load balancer set up) ◦ 80 - Needed for TLS certificate issuance via Let's Encrypt • UDP Ports: ◦ 50000-60000 - For WebRTC media traffic (each participant will use two ports) ◦ Optional: 7882 - A single UDP mux port if you prefer it over the range above • TURN Server Ports (if you have it enabled): ◦ 5349/TCP - TURN over TLS ◦ 3478/UDP - TURN over UDP (also acts as STUN) Make sure these ports are open for both inbound and outbound traffic. If anything feels unclear or you’d like a hand with your setup, just let me know—I’m here to help! Sources: Ports and firewall | LiveKit Docs | Deploy to a VM | LiveKit Docs | config-sample.yaml
a
WorkerOptions has num_idle_processes, what does it do and increasing it affects what?
t
WorkerOptions.num_idle_processes
is a setting that controls how many idle processes the LiveKit worker keeps ready and waiting to handle incoming jobs. This is a great way to reduce job startup latency because it pre-warms processes, so you don’t have to wait for new ones to spawn and initialize when jobs come in. Here’s what happens when you increase this value: • Positive: You’ll see reduced job startup latency, better responsiveness, and smoother handling of multiple jobs at once. • Trade-offs: It does use more memory and CPU, and if job demand is low, some resources might go unused. The best value really depends on your specific needs. Higher numbers mean quicker responses but more resource use, while lower numbers save resources but might cause some delay. If you’d like, I’m here to help you figure out the ideal setup for your situation—just let me know! Sources: livekit-agents/livekit/agents/worker.py | Worker options | LiveKit Docs
a
What number would you recommend if i have around 20 calls simultaneously?
t
To comfortably handle 20 simultaneous calls, I’d suggest setting
num_idle_processes
to around 12-15 on a single worker, assuming your hardware supports it (think 4+ cores and 8GB+ RAM). This way, you’ll have enough pre-warmed processes ready to go, helping to avoid any delays when new calls come in. If you’re working with multiple workers, a good approach is to spread the load by setting
num_idle_processes
to about 6-8 per worker across 2-3 workers. Starting with these settings is a great first step! Keep an eye on things like process spawn times, memory use, and CPU load to see how it’s performing, and adjust as needed. Feel free to reach out if you want help tweaking your setup or if you’d like to share more about your hardware so I can offer more personalized advice. Sources: tests/test_ipc.py | Deploying to custom environments | LiveKit Docs
a
How would a single worker compare with multiple workers on a single machine?
t
When deciding between using a single worker or multiple workers on a single machine in LiveKit, there are some important points to consider, and I’m here to help you navigate them: Benefits of a Single Worker: • It’s easier to deploy and manage, which can save you time and effort. • It uses less memory since there are fewer worker processes running. • Resources are managed in one centralized place, making things straightforward. Benefits of Multiple Workers: • They offer better fault isolation, so if one job type has an issue, it won’t affect others as much. • You can handle different workload patterns more effectively with specialized workers. • Load distribution becomes more precise and balanced. • It’s a smoother path if you’re thinking about scaling out horizontally in the future. For handling around 20 simultaneous calls, a single worker with enough resources (like 4+ cores and 8GB+ RAM) usually does the job well. But if you’re looking for specialized job handling, improved fault isolation, or planning to scale horizontally soon, going with multiple workers (say 2-3 workers each having 6-8 idle processes) might be the way to go. Please feel free to reach out if you want me to help you tailor this advice to your specific workload or hardware setup—I’m happy to assist! Sources: Worker lifecycle | LiveKit Docs | examples/avatar_agents/audio_wave/dispatcher.py | Deploying to custom environments | LiveKit Docs | pkg/sfu/receiver_test.go
a
rtc: tcp_port: 7881 port_range_start: 50000 port_range_end: 60000 the server team has told me to limit the port number, can I pass them through a single port or what alternatives do I have?
t
I'd be happy to help you configure LiveKit to use a single port for WebRTC traffic by enabling the UDP mux feature. Here’s a simple example:
Copy code
rtc:
  udp_port: 7882
This setup will route all UDP traffic through port 7882, which can make your firewall configuration much easier. If you’re looking for a bit more performance, you might consider using a small range of ports, like 7882-7892:
Copy code
rtc:
  udp_port: 7882-7892
Using a single port is great if your environment has strict firewall rules, but keep in mind it might become a bottleneck if there’s heavy traffic. A small range of ports offers a nice balance between simplicity and performance. If you’d like, I’m here to guide you through the implementation or answer any other questions you might have about your setup. Just let me know! Sources: Ports and firewall | LiveKit Docs | config-sample.yaml | pkg/rtcconfig/webrtc_config.go | Firewall Tips
a
port: 7880 log_level: info rtc: tcp_port: 7881 port_range_start: 50000 port_range_end: 60000 redis: address: localhost:6379 keys: APIbLLHJzVJJEei: ZSLMLLihE5l8sauRKnmNRIFm9nvC73Yf3k96QOWzbgE turn: enabled: true tls_port: 8365 domain: ws://localhost:7880 cert_file: /etc/pki/tls/certs/star.enteract.cloud.crt key_file: /etc/pki/tls/private/star.enteract.cloud.key What changes would you suggest, i don't mind any thing else just the 50000 and 60000 range is too much so maybe change that
t
I understand you're looking to reduce the port range while keeping good performance—let’s explore a couple of friendly options together! Option 1: Use a Smaller Port Range
Copy code
rtc:
  port_range_start: 50000
  port_range_end: 50010
This way, you narrow it down to 11 ports, which usually works well for moderate traffic and helps keep the number of open ports manageable. Option 2: Use a Single UDP Port
Copy code
rtc:
  udp_port: 7882
Here, all UDP traffic goes through port 7882, making firewall setup a bit simpler. Just a heads-up—it might get a little busy if the load gets heavy. If you'd like, I’m here to help you step through these changes or chat about what they might mean for your setup. Just let me know!
a
Connecting to signal connection via WebSocket Connected to server, version 1.9.1. Establishing WebRTC connection udp 172.17.0.1:7882 host (private) udp 172.19.0.1:7882 host (private) udp 10.30.11.98:7882 host (private) udp 172.18.0.1:7882 host (private) tcp 10.30.11.98:7881 host (private) tcp 172.18.0.1:7881 host (private) tcp 172.17.0.1:7881 host (private) tcp 172.19.0.1:7881 host (private) udp 3.141.128.111:46152 srflx udp 3.141.128.111:49910 srflx udp 3.141.128.111:34916 srflx udp 172.17.0.1:7882 host (private) udp 172.19.0.1:7882 host (private) udp 10.30.11.98:7882 host (private) udp 172.18.0.1:7882 host (private) tcp 10.30.11.98:7881 host (private) tcp 172.18.0.1:7881 host (private) tcp 172.17.0.1:7881 host (private) tcp 172.19.0.1:7881 host (private) udp 3.141.128.111:60871 srflx udp 3.141.128.111:59512 srflx udp 3.141.128.111:46912 srflx Warning: error with ICE candidate: 701 STUN host lookup received error. stun:stun.l.google.com:19302 Warning: error with ICE candidate: 701 STUN host lookup received error. stun:stun1.l.google.com:19302 Warning: error with ICE candidate: 701 STUN host lookup received error. stun:global.stun.twilio.com:3478 Warning: error with ICE candidate: 701 Failed to establish connection turnslivekit server dev.enteract.cloud443?transport=tcp Warning: error with ICE candidate: 701 Failed to establish connection turnslivekit server dev.enteract.cloud443?transport=tcp Warning: ports need to be open on firewall in order to connect. Error: could not establish pc connection Can connect via TURN Error: could not establish pc connection Can publish audio Error: could not establish pc connection Can publish video Error: could not establish pc connection Resuming connection after interruption Error: could not establish pc connection Fail What are these different ports, are they required for a connection?If yes, then tell me how can I control them? My current config: port: 7880 log_level: info rtc: tcp_port: 7881 udp_port: 7882 redis: address: localhost:6379 keys: APIbLLHJzVJJEei: ZSLMLLihE5l8sauRKnmNRIFm9nvC73Yf3k96QOWzbgE turn: enabled: true tls_port: 8365 domain: livekit-server-dev.enteract.cloud cert_file: /etc/pki/tls/certs/star.enteract.cloud.fullchain.pem key_file: /etc/pki/tls/private/star.enteract.cloud.key
t
Hi there! I’d love to help you understand how ICE candidate ports work in LiveKit for WebRTC media transport. Here’s a quick overview: • Host candidates: These are your local network addresses that help establish direct connections. • Server reflexive candidates: These are public addresses found via STUN, which help with NAT traversal. • Relayed candidates: These come from TURN servers and are used when direct connections aren’t possible. In your current setup, you’re using: • UDP Mux: All UDP traffic goes through port 7882. • TCP Fallback: Port 7881 is used if UDP isn’t available. To help you manage these ports better, here are a few tips: 1. You might consider using a smaller UDP port range (like 7882-7892) to improve performance and keep the number of open ports manageable:
Copy code
rtc:
  udp_port: 7882-7892
1. Make sure your firewall settings allow traffic on the ports you’ve configured (7881 for TCP and 7882 for UDP). 2. If you’re deploying in the cloud, enabling external IP discovery can be really helpful:
Copy code
rtc:
  use_external_ip: true
If you have any questions or want me to walk you through these steps, please don’t hesitate to ask. I’m here to help you get everything running smoothly! Sources: config-sample.yaml | pkg/transport/udpmultimux.go | Firewall Tips | Protocol & WebRTC Stack | livekit/livekit_composite | DeepWiki | Ports and firewall | LiveKit Docs
a
udp 3.141.128.111:46152 srflx udp 3.141.128.111:49910 srflx udp 3.141.128.111:34916 srflx udp 3.141.128.111:60871 srflx udp 3.141.128.111:59512 srflx udp 3.141.128.111:46912 srflx Warning: error with ICE candidate: 701 STUN host lookup received error. stun:stun.l.google.com:19302 Warning: error with ICE candidate: 701 STUN host lookup received error. stun:stun1.l.google.com:19302 Warning: error with ICE candidate: 701 STUN host lookup received error. stun:global.stun.twilio.com:3478 Warning: error with ICE candidate: 701 Failed to establish connection turnslivekit server dev.enteract.cloud443?transport=tcp Warning: error with ICE candidate: 701 Failed to establish connection turnslivekit server dev.enteract.cloud443?transport=tcp ARE THESE REQUIRED TO CREASTE A CONNECTION? IF THEY ARE IMPORTANT, THEN TELL ME WHERE i CAN CONFIG THEM IN MY .YAML FILE?
t
STUN and TURN servers aren’t absolutely necessary for LiveKit connections, but they really help improve connectivity, especially if you’re working in a network with some restrictions. I’d love to guide you through how to set them up in your YAML file: STUN Servers: These are great for helping devices behind NAT discover their public IP address. LiveKit clients use Google's public STUN servers by default, but you can absolutely specify your own if you prefer:
Copy code
rtc:
  stun_servers:
    - stun:stun.l.google.com:19302
    - stun:stun1.l.google.com:19302
TURN Servers: These come into play when direct connections can’t be made, relaying traffic for you. LiveKit has an embedded TURN server, which is a solid choice for production environments:
Copy code
turn:
  enabled: true
  domain: turn.myhost.com
  tls_port: 443
  udp_port: 3478
  cert_file: /path/to/cert.pem
  key_file: /path/to/key.pem
TURN servers are especially helpful if you’re dealing with restrictive firewalls, since they allow traffic over TCP/TLS on port 443, which looks like regular HTTPS traffic. If you have any questions or want me to walk you through these configurations or how they work, just let me know—I’m here to help! Sources: pkg/config/config.go | Deploying LiveKit | LiveKit Docs | Documentation/CallGuide.md | Firewall Tips
a
Cna you write me a one liner on my would I need these different ports, like why does livekit use them or what purpose they serve? port: 7880 log_level: info rtc: tcp_port: 7881 udp_port: 7882 redis: address: localhost:6379 keys: APIbLLHJzVJJEei: ZSLMLLihE5l8sauRKnmNRIFm9nvC73Yf3k96QOWzbgE turn: enabled: true tls_port: 8365 domain: ws://localhost:7880 cert_file: /etc/pki/tls/certs/star.enteract.cloud.crt key_file: /etc/pki/tls/private/star.enteract.cloud.key
t
Let me walk you through a quick explanation for each port in your setup: • 7880: This one’s for the LiveKit signaling server, helping to set up those initial WebSocket connections. • 7881: Acts as a TCP fallback port for WebRTC connections when UDP isn’t available. • 7882: Handles UDP traffic for WebRTC media, using UDP mux to manage all the media streams. • 8365: This is the TLS port for the embedded TURN server, making sure media traffic is securely relayed. Each port plays an important part in keeping your LiveKit connection smooth and reliable. If you’d like me to explain anything in more detail, just let me know—I’m here to help!
a
5349, 3478 why would I need these two as well?
t
5349: This is the default port for TURN over TLS, which helps relay media traffic securely when direct connections don’t work, especially in networks with restrictions. 3478: This is the default port for TURN over UDP, and it also acts as a STUN server to assist devices behind NAT in discovering their public IP address and setting up connections. These ports play a key role in making sure your connectivity improves even in tricky network situations. If you’d like, I’m here to help you with configuring them or understanding how they work better.
a
rtc: tcp_port: 7881 port_range_start: 50000 port_range_end: 50003 use_external_ip: true what is the advantage of setting port range instead of a single port? does a single customer connecting to my machine get a port while the other customer can't get the same port or they can use the same port but it will be degrade? And how many customer should connect simultaneously on a single port?
t
Using a port range (e.g., 50000-50003) is a great way for LiveKit to assign separate UDP ports for each participant’s media streams. This helps ensure smoother performance and better scalability when many people are connected at the same time. Usually, each participant uses two ports—one for audio and one for video—so having a range makes sure there are enough ports available for everyone. On the other hand, using a single port (e.g., 7882) with UDP multiplexing can make firewall setup easier since all traffic goes through just one port. That said, under heavy use, this might slow things down a bit because all connections share that same port. There isn’t a hard limit on how many customers can connect through one port, but the overall performance really depends on your system’s resources like CPU cores and the network conditions. To get the best results, LiveKit suggests using a port range that’s at least as large as the number of vCPUs on your machine. If you’d like, I’m here to help you with more detailed advice on setting up your system for high-density use or scaling it up smoothly. Just let me know! Sources: Distributed Setup | LiveKit Docs | Ports and firewall | LiveKit Docs | pkg/transport/createmux.go | config-sample.yaml
a
if a token is expired mid conversation, can I return a custom message saying your session has exceeded limit? What behavior is expected?
t
I completely understand how important it is to keep your LiveKit sessions running smoothly! The good news is that if a token expires during a conversation, the session won’t be interrupted because the server takes care of refreshing tokens automatically for connected clients. Token expiration mainly applies when you’re first connecting, so ongoing sessions stay intact. While LiveKit doesn’t provide custom messages when a token expires, you can definitely add some client-side logic to keep an eye on the token’s expiration time (for example, by decoding the JWT’s
exp
claim) and show a friendly notification before it happens. If you’d like, I’m here to help you set up this client-side monitoring or chat through how to handle token expiration in your app. Just let me know! Sources: Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki | Authentication | LiveKit Docs | Sources/LiveKit/Token/CachingTokenSource.swift | livekit-protocol/src/livekit.rs | Core Platform Architecture & Authentication | livekit/livekit_composite | D...
a
token = ( api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET) .with_identity(identity) .with_metadata(metadata_token) .with_grants(api.VideoGrants(room_join=True, room=room)) .to_jwt() ) token = api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET) token.with_identity(identity) token.with_metadata(metadata_token) token.with_grants(api.VideoGrants(room_join=True, room=room)) token.with_ttl( datetime.timedelta( seconds=100 ) ) this token has a lifetime of 100 seconds, after 100 seconds it expires and doesn't renew even when the conversation is going on?
t
Thanks for your question! In LiveKit, when a token is set to expire after 100 seconds using
with_ttl
, it won’t automatically renew. The token expiration is checked only during the initial connection attempt, so your ongoing sessions will continue smoothly even if the token expires in the middle of a conversation. This happens because LiveKit uses a proactive token refresh mechanism to keep the media flowing without interruption. If you’d like to enforce session limits or give users a heads-up about token expiration, you can add some client-side logic to keep an eye on the token’s expiration time and respond accordingly. I’d be happy to help you with that if you want—just let me know!
a
can you show me some code that will help me implement it?
t
Here’s a helpful example to guide you through monitoring token expiration and notifying your users: Python Example:
Copy code
import jwt
import datetime

def is_token_expired(token):
    decoded = jwt.decode(token, options={"verify_signature": False})
    exp = decoded.get("exp")
    if not exp:
        return True

    expiration_time = datetime.datetime.fromtimestamp(exp)
    current_time = datetime.datetime.utcnow()
    return current_time >= expiration_time - datetime.timedelta(seconds=60)

# Example usage
token = "your_jwt_token_here"
if is_token_expired(token):
    print("Token is expired or will expire soon!")
    # Notify user or refresh token logic here
This example gently decodes the JWT token, checks the
exp
claim, and helps you determine if the token will expire within the next 60 seconds. Feel free to swap out the print statement with your own notification or token refresh logic to best fit your needs. If you’d like, I’m here to help with more examples or support in another programming language—just let me know! Sources: complex-agents/note-taking-assistant/note-taker-frontend/hooks/useConnectio... | Sources/LiveKit/Token/CachingTokenSource.swift | Authentication | LiveKit Docs | Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki
a
show me code in the entrypoint(ctx: JobContext) function on how am I supposed to handle it?
t
Hi there! In the
entrypoint(ctx: JobContext)
function, you actually don’t need to worry about handling token expiration yourself. LiveKit takes care of refreshing tokens automatically for connected clients, so your sessions stay valid without any extra effort from you. Here’s a simple example of how you can use the
entrypoint
function:
Copy code
async def entrypoint(ctx: JobContext):
    await ctx.connect()  # Automatically handles token lifecycle

    # Rest of agent logic
    ...
The
ctx.connect()
call is what makes sure the token lifecycle is managed smoothly by the LiveKit server and SDKs. If you’d like, I’m happy to walk you through more details or share additional examples—just let me know! Sources: Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki | Authentication | LiveKit Docs | agents/src/job.ts | README.md
a
Yes, but how can I notify the customer (agent.say) when it is about to reach 100 seconds
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
a
async def check_time_limit(): try: if workspace_record["advanced"]["max_conversation_duration"]: await asyncio.sleep(workspace_record["advanced"]["max_conversation_duration"] + 3) await session.say("You're approaching the maximum talk time limit for this session.") except asyncio.CancelledError: pass async def time_limit_exit(task): if task: task.cancel() timer_task = asyncio.create_task(check_time_limit()) ctx.add_shutdown_callback(time_limit_exit(timer_task)) is this code correct?
5349 and 3478, why are these ports used?