I have deployed livekit server on an ec2 instance....
# ask-ai
g
I have deployed livekit server on an ec2 instance. Also, I am running the livekit agent in ecs containers. As of now, I am running 5 containers always so that if some user joins the call, the agent can join that call. But I keep getting errors as follows:
Copy code
ConnectionError: could not establish pc connection

ConnectionError: could not establish signal connection: room connection has timed out (signal)
Its quite random, not sure if its causing because I have 5 agents running and no of users joining are more than 5? Spec: 1. ECS - 1vcpu and 2 GB memory 2. EC2 (livekit server) - 4 vcpu and 8 GB memory Thoughts/help on this?
t
Thanks for reaching out, Harsh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’m responding to the connection errors you shared and the question about whether running 5 agent containers while more than 5 users join could cause them. Short answer: 5 agent containers is not inherently the cause of those connection errors. Agents control agent sessions (AI bots) and do not limit standard user-to-user connections. The errors you’re seeing point to networking, TURN/ICE, or server-performance issues. Here’s a focused checklist to diagnose and fix this quickly. 1) Verify TURN / UDP and firewall • Ensure UDP ports 50000–60000 are open and reachable from clients. • Make sure a TURN server is configured and reachable (fallback when UDP is blocked). Without TURN, WebRTC will often fail in restrictive networks. 2) Check signal (WebSocket) connectivity • Confirm TCP 443 (or your configured signal port) is open and that WebSocket upgrade works through any LB or proxy. • If you use a load balancer, ensure sticky sessions or that WebSocket upgrades are preserved. 3) Inspect server resource behavior • Watch EC2 CPU, memory, and network during failures. If your EC2 is a burstable type (t3/t4), CPU credit exhaustion can cause timeouts — consider switching to a fixed-performance instance (m5/c5 family). • Check agent container CPU/memory on ECS; 1 vCPU / 2GB may be saturated if agents do heavy processing. 4) Correlate logs and timing • Check LiveKit server logs for ICE/STUN/TURN errors and signal timeouts at the same timestamps users hit errors. • Check agent logs for timeouts or queues if your app expects an agent to join every room. 5) Test connectivity from client networks • Run LiveKit Connection Test / ConnectionCheck from the failing client environments to see whether WebRTC, WebSocket, or TURN checks fail. • If WebRTC fails but TURN succeeds, it’s UDP/NAT related; if TURN also fails, it’s a network/TURN reachability problem. 6) Agent scaling considerations • If your design spawns one agent per room and you exceed 5 concurrent rooms requiring agents, new rooms will wait for an available agent — that can cause application-level delays but should not prevent user signaling or media connectivity. • If you need one agent per concurrent room, scale agents or use autoscaling based on load. Suggested immediate steps 1. Run the connection test from a client that hit the error and share results (WebRTC vs. WebSocket vs. TURN failures). 2. Check LiveKit server logs and agent logs around one error timestamp and share any ICE/TURN or timeout messages. 3. If on a t3/t4 EC2, try a fixed-performance instance and observe if timeouts drop. If you want, share: • One example error timestamp and the corresponding LiveKit server log lines (redact tokens), • Whether clients failing are behind restrictive NATs (mobile/carrier networks, corporate), and • Whether your EC2 instance is burstable (t3/t4) or fixed type. I can help interpret the test/log output and recommend precise next steps. Sources: Agent server | LiveKit docs | Firewall Tips | Configuring firewalls | LiveKit docs | Diagnosing Connection Errors with Connection Test Utility | Operational Best Practices | livekit/livekit_composite | DeepWiki
g
These are the logs from livekit server when the connection error happens:
Copy code
2025-11-24T05:56:30.630Z        INFO    livekit service/roommanager.go:408      starting RTC session    {"room": "5y8we4sT4P4YItkpBrXTi", "roomID": "RM_UA7U2scATKXL", "participant": "RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV", "pID": "PA_kZU7vAAAqsSz", "remote": false, "room": "5y8we4sT4P4YItkpBrXTi", "nodeID": "ND_RXFve7p7vS2R", "numParticipants": 0, "participantInit": {"Identity": "RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV", "Reconnect": false, "ReconnectReason": "RR_UNKNOWN", "AutoSubscribe": true, "Client": {"sdk": "JS", "version": "2.15.13", "protocol": 16, "os": "Linux", "deviceModel": "Other", "browser": "Edge", "browserVersion": "142.0.0"}, "Grants": {"Identity": "RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV", "Kind": "", "Video": {"RoomCreate": false, "RoomList": false, "RoomRecord": false, "RoomAdmin": false, "RoomJoin": true, "Room": "5y8we4sT4P4YItkpBrXTi", "CanPublish": true, "CanSubscribe": true, "CanPublishData": true, "CanPublishSources": [], "CanUpdateOwnMetadata": "not-set", "IngressAdmin": false, "Hidden": false, "Recorder": false, "Agent": false, "CanSubscribeMetrics": "not-set", "DestinationRoom": ""}, "SIP": {}, "Agent": {}, "Inference": {}, "Observability": {}, "RoomConfig": {"agents": [{"metadata": "{\"gender\":\"M\",\"language\":\"en-IN\",\"job_prompt\":\"DO NOT PROCEED WITH THE INTERVIEW QUESTIONS UNTIL THE CANDIDATE HAS INTRODUCED THEMSELVES. CONCLUDE THE INTERVIEW IN EN-IN LANGUAGE, UNLESS THE CANDIDATE SPECIFICALLY ASKS FOR ANOTHER LANGUAGE. Conduct a technical interview as an AI Interviewer, focusing on evaluating a Software Engineer candidate's practical skills required for the role.\\n\\n- Aim for a professional and concise interaction.\\n- Avoid using the candidate's first name.\\n- The interview consists of some hygiene questions and question pairs, ensure the candidate is unaware of the hygiene questions, primary and secondary structure. The distinction is for internal use only. Do not reveal or hint at this structure to the candidate. Once the candidate has introduced themselves, ask the hygiene questions first, then the question pairs.\\n\\n# Hygiene Questions\\n### Before starting the interview, ask the following questions one at a time, don't start with the question pairs until these questions are answered\\n- Are you okay to work remotely?\\n\\n# Question Pairs\\n\\n\\n\\t\\t1. Primary: \\\"Can you describe a recent software project you developed using JavaScript or Python?\\\"\\n\\t\\tSecondary (if needed): \\\"What challenges did you face during this project, and how did you overcome them?\\\"\\n\\t\\t\\n\\n\\t\\t2. Primary: \\\"How do you ensure the quality of your code during development?\\\"\\n\\t\\tSecondary (if needed): \\\"Can you give an example of how you've implemented coding standards in a past project?\\\"\\n\\t\\t\\n\\n\\t\\t3. Primary: \\\"What strategies do you use to stay updated on emerging technologies relevant to software development?\\\"\\n\\t\\tSecondary (if needed): \\\"Have you applied any new technologies in your work recently, and what was the impact?\\\"\\n\\t\\t\\n\\n# Flow Logic\\n1. Start the hygiene questions.\\n2. Then ask the primary question 1.\\n3. Evaluate the response:\\n   - If satisfactory, skip the secondary and go to primary n + 1.\\n   - If not satisfactory, ask the paired secondary question.\\n4. After the secondary response, move on to primary n + 1 regardless of satisfaction.\\n5. Repeat until all question pairs are completed.\\n6. Keep the acknowledgment of past response brief; do not praise or appreciate.\\n7. Thank the candidate and close the interview without excessive admiration.\\n\\n# Special Instructions\\n- Ask one question at a time.\\n- Avoid unrelated questions; remind candidates to focus on the interview.\\n- Issue a warning if irrelevant questions persist; conclude if needed.\\n- Address answer discrepancies for clarity.\\n- Request specific examples if responses are too vague.\\n- Avoid repetitive questions and deep dives into confidential topics.\\n- Ensure all necessary questions are asked.\\n\\n# Output Format\\nProvide brief, concise responses. Avoid excessive admiration or praise.\\n\\n# Notes\\n- To conclude the interview, say \\\"I will conclude the call now.\\\" This phrase should only be used to end the call. Saying it at any other time will prematurely end the call, so use it with caution. The call will not end unless this exact phrase is used by you.\\n- Slightly modify questions each time to maintain variety and avoid sounding repetitive.\",\"job_greeting\":\"Welcome to the initial stage of the interview process with Harsh. Could you please start by briefly introducing yourself and sharing your professional journey so far?\",\"interview_slug\":\"n87k9bw,mja\"}"}]}, "RoomPreset": ""}, "Region": "", "AdaptiveStream": false, "ID": "", "SubscriberAllowPause": "not-set", "DisableICELite": false, "CreateRoom": {"name": "5y8we4sT4P4YItkpBrXTi", "agents": [{"metadata": "{\"gender\":\"M\",\"language\":\"en-IN\",\"job_prompt\":\"DO NOT PROCEED WITH THE INTERVIEW QUESTIONS UNTIL THE CANDIDATE HAS INTRODUCED THEMSELVES. ",\"job_greeting\":\"Welcome to the initial stage of the interview process with Harsh. Could you please start by briefly introducing yourself and sharing your professional journey so far?\",\"interview_slug\":\"n87k9bw,mja\"}"}]}, "AddTrackRequests": [], "PublisherOffer": {}, "SyncState": {}, "UseSinglePeerConnection": false}}
2025-11-24T05:56:30.936Z        INFO    livekit rtc/room.go:1326        removing participant without connection {"room": "5y8we4sT4P4YItkpBrXTi", "roomID": "RM_UA7U2scATKXL", "participant": "RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV", "pID": "PA_kZU7vAAAqsSz", "remote": false, "publisherCandidates": ["[local][trickle] udp4 host 65.0.72.28:58700 (resolved: 65.0.72.28:58700)", "[local][trickle] tcp4 host 65.0.72.28:7881 (resolved: 65.0.72.28:7881)", "[local][trickle] udp4 host 172.17.0.1:54074 (resolved: 172.17.0.1:54074)", "[local][trickle] tcp4 host 172.17.0.1:7881 (resolved: 172.17.0.1:7881)", "[local][trickle] udp4 host 172.18.0.1:52905 (resolved: 172.18.0.1:52905)", "[local][trickle] tcp4 host 172.18.0.1:7881 (resolved: 172.18.0.1:7881)", "[remote][trickle] udp4 host 192.168.29.200:45192", "[remote][trickle] udp6 host 2405:201:3022:38f0:243e:9a3:493c:1...:48319", "[remote][trickle] udp4 host 192.168.29.200:51196", "[remote][trickle] udp6 host 2405:201:3022:38f0:243e:9a3:493c:1...:60186", "[remote][trickle] udp4 host 192.168.29.200:41412", "[remote][trickle] udp6 host 2405:201:3022:38f0:243e:9a3:493c:1...:45089"], "subscriberCandidates": ["[local][trickle] tcp4 host 65.0.72.28:7881 (resolved: 65.0.72.28:7881)", "[local][trickle] udp4 host 65.0.72.28:51530 (resolved: 65.0.72.28:51530)", "[local][trickle] udp4 host 172.17.0.1:52690 (resolved: 172.17.0.1:52690)", "[local][trickle] tcp4 host 172.17.0.1:7881 (resolved: 172.17.0.1:7881)", "[local][trickle] udp4 host 172.18.0.1:54810 (resolved: 172.18.0.1:54810)", "[local][trickle] tcp4 host 172.18.0.1:7881 (resolved: 172.18.0.1:7881)"], "connectionType": "unknown", "reason": "CLIENT_REQUEST_LEAVE", "clientInfo": {"sdk": "JS", "version": "2.15.13", "protocol": 16, "os": "Linux", "deviceModel": "Other", "browser": "Edge", "browserVersion": "142.0.0"}}
2025-11-24T05:56:30.936Z        INFO    livekit rtc/participant.go:1502 participant closing     {"room": "5y8we4sT4P4YItkpBrXTi", "roomID": "RM_UA7U2scATKXL", "participant": "RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV", "pID": "PA_kZU7vAAAqsSz", "remote": false, "sendLeave": true, "reason": "CLIENT_REQUEST_LEAVE", "isExpectedToResume": false}
2025-11-24T05:56:31.436Z        INFO    livekit service/roommanager.go:408      starting RTC session    {"room": "5y8we4sT4P4YItkpBrXTi", "roomID": "RM_UA7U2scATKXL", "participant": "agent-AJ_3gfeEsVV4sCw", "pID": "PA_2yUikoqrFNM5", "remote": false, "room": "5y8we4sT4P4YItkpBrXTi", "nodeID": "ND_RXFve7p7vS2R", "numParticipants": 0, "participantInit": {"Identity": "agent-AJ_3gfeEsVV4sCw", "Reconnect": false, "ReconnectReason": "RR_UNKNOWN", "AutoSubscribe": true, "Client": {"sdk": "PYTHON", "version": "1.0.12", "protocol": 16}, "Grants": {"Identity": "agent-AJ_3gfeEsVV4sCw", "Kind": "agent", "Video": {"RoomCreate": false, "RoomList": false, "RoomRecord": false, "RoomAdmin": false, "RoomJoin": true, "Room": "5y8we4sT4P4YItkpBrXTi", "CanPublish": true, "CanSubscribe": true, "CanPublishData": true, "CanPublishSources": [], "CanUpdateOwnMetadata": true, "IngressAdmin": false, "Hidden": false, "Recorder": false, "Agent": true, "CanSubscribeMetrics": false, "DestinationRoom": ""}, "SIP": {}, "Agent": {}, "Inference": {}, "Observability": {}, "RoomConfig": {}, "RoomPreset": ""}, "Region": "", "AdaptiveStream": false, "ID": "", "SubscriberAllowPause": "not-set", "DisableICELite": false, "CreateRoom": {"name": "5y8we4sT4P4YItkpBrXTi"}, "AddTrackRequests": [], "PublisherOffer": {}, "SyncState": {}, "UseSinglePeerConnection": false}}
2025-11-24T05:56:31.738Z        INFO    livekit rtc/room.go:507 participant active      {"room": "5y8we4sT4P4YItkpBrXTi", "roomID": "RM_UA7U2scATKXL", "participant": "agent-AJ_3gfeEsVV4sCw", "pID": "PA_2yUikoqrFNM5", "remote": false, "subscriberCandidates": ["[local][selected:1][trickle] udp4 host 65.0.72.28:50978 (resolved: 65.0.72.28:50978)", "[local][trickle] tcp4 host 65.0.72.28:7881 (resolved: 65.0.72.28:7881)", "[local][trickle] udp4 host 172.17.0.1:51382 (resolved: 172.17.0.1:51382)", "[local][trickle] tcp4 host 172.17.0.1:7881 (resolved: 172.17.0.1:7881)", "[local][trickle] udp4 host 172.18.0.1:56855 (resolved: 172.18.0.1:56855)", "[local][trickle] tcp4 host 172.18.0.1:7881 (resolved: 172.18.0.1:7881)", "[remote][trickle] udp4 host 169.254.17...:60112", "[remote][selected:1][trickle] udp4 host 172.31.15.205:51457", "[remote][trickle] udp4 srflx 13.126.247....:51457  related 172.31.15.205:51457"], "connectionType": "udp", "clientInfo": {"sdk": "PYTHON", "version": "1.0.12", "protocol": 16}}
2025-11-24T05:56:50.742Z        INFO    livekit.room    rtc/room.go:860 closing room    {"room": "5y8we4sT4P4YItkpBrXTi", "roomID": "RM_UA7U2scATKXL"}
2025-11-24T05:56:50.742Z        INFO    livekit rtc/participant.go:1502 participant closing     {"room": "5y8we4sT4P4YItkpBrXTi", "roomID": "RM_UA7U2scATKXL", "participant": "agent-AJ_3gfeEsVV4sCw", "pID": "PA_2yUikoqrFNM5", "remote": false, "sendLeave": true, "reason": "ROOM_CLOSED", "isExpectedToResume": false}
2025-11-24T05:56:50.744Z        INFO    livekit service/roommanager.go:184      deleting room state     {"room": "5y8we4sT4P4YItkpBrXTi"}
2025-11-24T05:56:50.745Z        INFO    livekit.room    service/roommanager.go:655      room closed     {"room": "5y8we4sT4P4YItkpBrXTi", "roomID": "RM_UA7U2scATKXL"}
2025-11-24T05:56:50.745Z        INFO    livekit.room    rtc/room.go:844 closing idle room       {"room": "5y8we4sT4P4YItkpBrXTi", "roomID": "RM_UA7U2scATKXL", "reason": "departure timeout"}
t
Thanks — I reviewed the server logs you shared. Quick summary and next steps. What the logs show • A user (Edge/Linux) starts RTC session, then immediately issues CLIENT_REQUEST_LEAVE and is removed. • An agent then joins successfully over UDP. • The room closes after ~20s due to departure timeout (no remaining participants). • This indicates the LiveKit server and agent dispatch are working; the failure happens on the client side before a stable PeerConnection is established. Conclusion • Agent count is not the root cause — the agent connects fine. • The errors point to network/ICE/TURN or client-side WebRTC issues (UDP blocked, TURN unreachable, or client aborting). Actionable next steps 1. Run the Connection Test from the failing client network and share results (WebSocket, WebRTC, TURN). ◦ Use the ConnectionCheck utilities: checkWebsocket(), checkWebRTC(), checkTURN(). 1. Verify TURN and ports ◦ Ensure TURN is enabled and reachable (TLS on TCP 443 for restrictive networks). ◦ Open UDP 50000–60000 for media and allow TCP 443 for signaling/TURN. 1. Reproduce by forcing relay ◦ On the failing client, try
iceTransportPolicy: 'relay'
. If that succeeds, UDP is blocked and TURN must be fixed. 1. Collect client-side debug logs ◦ Enable debug logging in the JS SDK and capture ICE state transitions around the join attempt: ▪︎ set log level to debug and capture the sequence: gathering -> checking -> connected/failed. ◦ Share a short excerpt (redact tokens) if you want help interpreting. 1. Verify instance behavior ◦ Confirm EC2 instance type is not burstable (t3/t4) or hitting CPU credit exhaustion. If it is, try a fixed-performance type (m5/c5) to rule out throttling. If you’d like, share: • One failing session timestamp + the debug client logs (ICE state events) and the ConnectionCheck output. I’ll interpret them and recommend the precise fix. Sources: Troubleshooting Latency and Timeout Errors with Turn Detection on AWS | Troubleshooting Guide | livekit/livekit_composite | DeepWiki | Diagnosing Connection Errors with Connection Test Utility | Deploying LiveKit | LiveKit docs | Firewall Tips
g
Untitled
client side logs:
t
Thanks — to diagnose the peer connection failure I need the client-side debug logs and ConnectionCheck results. Please paste: • The JS SDK debug logs around the join attempt (set log level to debug). Include ICE state transitions and any errors. • Output from ConnectionCheck: results of checkWebsocket(), checkWebRTC(), and checkTURN(). • The join timestamp that matches your server log (e.g., 2025-11-24T055630.630Z). • Whether the failing client is on a corporate/mobile network or behind a VPN. With those I’ll interpret the ICE flow and recommend the exact fix.
g
connected to Livekit Server edition: 0, version: 1.9.3, protocol: 16, region: , nodeId: ND_RXFve7p7vS2R, debugInfo: , agentProtocol: 1 {room: '5y8we4sT4P4YItkpBrXTi', roomSid: 'RM_UA7U2scATKXL', identity: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV'} Room.ts:2578 room event signalConnected {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', event: 'signalConnected', …} PCTransportManager.ts:209 negotiation required, start negotiating {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'} publishUtils.ts:126 using video encoding {maxBitrate: 1700000, maxFramerate: 30, priority: undefined} LocalVideoTrack.ts:287 setting degradationPreference to balanced {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', trackID: undefined, …} LocalVideoTrack.ts:287 setting degradationPreference to balanced {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', trackID: undefined, …} DeviceManager.ts:31 awaiting getUserMedia promise DeviceManager.ts:31 awaiting getUserMedia promise PCTransportManager.ts:172 received server offer {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', RTCSdpType: 'offer', …} RTCEngine.ts:523 got ICE candidate from peer {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', candidate: {…}, …} RTCEngine.ts:523 got ICE candidate from peer {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', candidate: {…}, …} RTCEngine.ts:523 got ICE candidate from peer {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', candidate: {…}, …} RTCEngine.ts:523 got ICE candidate from peer {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', candidate: {…}, …} RTCEngine.ts:523 got ICE candidate from peer {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', candidate: {…}, …} RTCEngine.ts:523 got ICE candidate from peer {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', candidate: {…}, …} turbopack-hot-reloader-common.ts:43 [Fast Refresh] rebuilding PCTransport.ts:289 starting to negotiate {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'} RTCEngine.ts:541 received trackPublishedResponse {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', cid: 'b47ff7c3-f383-473c-8955-4b2ee749ac25', …} RTCEngine.ts:541 received trackPublishedResponse {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', cid: 'b8cc30ae-84c5-4e34-bb2a-b48e6ac59290', …} PCTransport.ts:294 original offer {sdp: 'v=0\r\no=- 5164436411333276465 2 IN IP4 127.0.0.1\r\ns…2\r\na=sctp port5000\r\na=max-message-size:262144\r\n', room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'} PCTransport.ts:506 setting munged local description {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'} PCTransport.ts:506 setting munged local description {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'} SignalClient.ts:530 sending offer {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', offerSdp: 'v=0\r\no=- 5164436411333276465 2 IN IP4 127.0.0.1\r\ns…le\r\na=sctp-port5000\r\na=max message size262144\r\n'} SignalClient.ts:539 sending answer {room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz', answerSdp: 'v=0\r\no=- 4462346997563918577 2 IN IP4 127.0.0.1\r\ns…kle\r\na=sctp-port5000\r\na=max message size65535\r\n'} report-hmr-latency.ts:26
t
Thanks — the client logs are helpful. They show signaling, offer/answer exchange, and ICE candidates being received, but no ICE connection-state events. That indicates the client began negotiation but likely aborted before ICE reached a connected state. Please do the following so I can pinpoint the failure: 1. Capture and paste the client-side ICE state transitions around the join (enable debug logging and include lines for): ◦
iceConnectionStateChange
◦
iceGatheringStateChange
◦
icecandidate
events (local candidates) ◦ Any
onconnectionstatechange
or RTCPeerConnection error messages 1. Run ConnectionCheck from the failing client network and paste results for: ◦ checkWebsocket() ◦ checkWebRTC() ◦ checkTURN() 1. Confirm client network type for the failing session (corporate VPN, mobile carrier, home Wi‑Fi, etc.) and whether a TURN server is configured on your LiveKit server. 2. As a quick test, try forcing relay on the client: ◦ connect with
rtcConfig: { iceTransportPolicy: 'relay' }
◦ If that succeeds, UDP is blocked and TURN needs fixing. Share the above logs/results and one matching timestamp (e.g., 2025-11-24T055630.630Z). I’ll analyze the ICE flow and give exact steps to fix it.
g
1. Abort connection attempt due to user initiated disconnect _{room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'}_ 1. abort transport connection _{room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'}_ 1. abort transport connection _{room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'}_ 1. engine disconnected while negotiation was ongoing _{room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'}_ 1. engine disconnected while negotiation was ongoing _{room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'}_ 1. engine disconnected while negotiation was ongoing _{room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'}_ 1. pc state change: from NEW to CLOSED _{room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'}_ 1. primary PC state changed 5 _{room: '5y8we4sT4P4YItkpBrXTi', roomID: 'RM_UA7U2scATKXL', participant: 'RUfOCp3ZCsT02WHaTk3dTEGppxevHEKV', pID: 'PA_kZU7vAAAqsSz'}_ 1. update publication info _{trackID: 'TR_AM3JDPQKQ8S4KT', enabled: true, muted: false, trackInfo: {…}, info: TrackInfo}_
t
Thanks — this confirms the client is aborting the negotiation (engine disconnected while negotiation was ongoing → PC goes NEW → CLOSED). That points to a client-side disconnect or network/ICE/TURN issue, not agent capacity. Next steps to pinpoint and fix: 1. Confirm TURN reachability • From the failing client network run the ConnectionCheck: checkWebsocket(), checkWebRTC(), checkTURN(). Paste the results. • If checkTURN fails or relay succeeds but direct fails, ensure TURN is enabled, DNS and TLS match, and TCP 443 is reachable. 1. Capture the exact ICE lifecycle on the client • Enable debug and paste lines for: ◦ iceGatheringStateChange (new→gathering→complete) ◦ iceConnectionStateChange and onconnectionstatechange (checking→connected/failed) ◦ local
icecandidate
events • Look for “failed” or repeated “disconnected” states before the abort. 1. Test forcing relay • Connect with
rtcConfig: { iceTransportPolicy: 'relay' }
. If this succeeds, UDP is blocked and TURN must be fixed. 1. Check client-side logic/timeouts • Ensure the app isn’t calling a disconnect/leave on slow negotiations (increase any client-side negotiation/signal timeouts or add retries with backoff). • Verify UI or navigation logic isn’t canceling the join (user-initiated disconnect logs suggest the client code may abort on perceived slowness). 1. Verify network and server ports • Open UDP 50000–60000 for media and allow TCP 443 for signaling/TURN. • If clients are on restrictive networks (corporate/VPN/mobile), prefer TURN over TLS (443). 1. Server-side checks • Confirm LiveKit TURN config (domain, TLS cert) and security groups. • Check server metrics for transient CPU/network spikes at the timestamps you saw aborts. If you share: • One failing join timestamp, the ConnectionCheck output, and the client ICE state logs (gathering/connection state transitions), I’ll analyze them and provide the exact fix or config changes to apply.
g
1. Connect with
rtcConfig: { iceTransportPolicy: 'relay' }
. If this succeeds, UDP is blocked and TURN must be fixed. does not work and gives connection error. This is the following client code: // biome-ignore lint/correctness/useExhaustiveDependencies: fu! React.useEffect(() => { const connect = async () => { if ( sessionStarted && room.state === 'disconnected' && connectionDetails ) { try { await Promise.all([ room.localParticipant.setMicrophoneEnabled(true, undefined, { preConnectBuffer: true, }), room.localParticipant.setCameraEnabled( true, { facingMode: 'user', // use front camera on mobile devices }, { preConnectBuffer: true, }, ), room.connect( connectionDetails.serverUrl, connectionDetails.participantToken, { maxRetries: 5, } ), ]); // android audio fix: ensure remote audio tracks are enabled and audible room.remoteParticipants.forEach((participant) => { participant.audioTrackPublications.forEach((publication) => { if (publication.track) { (publication.track as RemoteAudioTrack).setVolume(1.0); } }); }); // listen for new remote tracks and ensure audio is enabled room.on(RoomEvent.TrackSubscribed, (_track_: RemoteTrack) => { if (track.kind === 'audio') { const audioTrack = track as RemoteAudioTrack; audioTrack.setVolume(1.0); // android-specific: force play on audio elements setTimeout(() => { audioTrack.attachedElements.forEach((element) => { if (element instanceof HTMLAudioElement) { element.muted = false; element.volume = 1.0; element.play(); } }); }, 100); } }); (async () => { if (egressStarted.current) return; egressStarted.current = true; try { const res = await fetch('/api/egress/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ roomName: connectionDetails?.roomName, interviewSlug: id, }), }); const data = await res.json(); if (!res.ok) throw new Error(data?.error ?? res.statusText); } catch (e) { const err = e instanceof Error ? e : new Error(String(e)); void sendSlackAlert( [ '🚨 LiveKit egress error - Frontend',
• room: ${connectionDetails?.roomName || id}
,
• user: ${user.id} (${user.name})
,
• interview slug: ${id}
,
• jobId: ${job.id}
,
• message: ${err.name}: ${err.message}
,
• stack trace: ${JSON.stringify(err, null, 2)}
, ].join('\n'), { channel: SLACK_CHANNELS['interview-meltdowns'], }, ); toast.error( 'Unsported Device Detected, please use desktop browser', ); } })(); } catch (error) { const err = error as Error; toast('There was an error connecting to the agent', { description:
${err.name}: ${err.message}
, }); void sendSlackAlert( [ '🚨 LiveKit connect error - Frontend',
• room: ${connectionDetails?.roomName || id}
,
• user: ${user.id} (${user.name})
,
• jobId: ${job.id}
,
• interview slug: ${id}
,
• message: ${err.name}: ${err.message}
, ].join('\n'), { channel: SLACK_CHANNELS['interview-meltdowns'], }, ); } } }; void connect(); return () => { room.disconnect(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [room, sessionStarted, connectionDetails, id]);
t
Thanks — this is helpful. You're seeing the client abort negotiation and relay-only (
iceTransportPolicy: 'relay'
) also fails, so TURN is unreachable or misconfigured. Agent count isn't the cause. Please provide the following so I can pinpoint the problem and give exact fixes: • Your LiveKit TURN config (values for
turn.enabled
, `turn.domain`/host, `turn.tls_port`/ports, and whether you use a TLS cert for the TURN domain). • Security group / firewall rules for the LiveKit server: inbound/outbound for UDP 50000–60000, UDP/TCP 3478 (if used), and TCP 443. • Result output of ConnectionCheck run from the failing client: checkWebsocket(), checkWebRTC(), checkTURN(). • Network type of the failing client (corporate VPN, mobile carrier, home Wi‑Fi) and whether the client uses a proxy. • One example timestamp of a failed join (e.g., 2025-11-24T055630.630Z) to correlate server logs. While you gather that, try: • Temporarily point the client to a public TURN (if available) to confirm TURN reachability. • Increase client-side connect retries/timeouts (you already have maxRetries: 5; add small delays between retries). • Check for any code path that may call disconnect() on slow negotiation (ensure UI/navigation isn’t aborting the effect). Share the TURN config, firewall rules, and ConnectionCheck output and I’ll provide the exact config changes and tests to resolve this.
g
i don't have turn because i am running the livekit server on 2 ec2 instances under the aws load balancer.
t
Thanks — since you’re running without TURN behind an AWS load balancer, that explains the intermittent failures. WebRTC needs a relayed path when UDP/direct connections fail; without TURN clients on restrictive networks will abort negotiation (what your logs show). What to do next (priority order) 1. Enable TURN (recommended) • Enable LiveKit’s embedded TURN with TLS (relay over TCP/443) so traffic can traverse restrictive networks. • Example config changes (update to your LiveKit config):
Copy code
turn:
  enabled: true
  domain: turn.yourdomain.com
  tls_port: 443
  cert_file: /path/to/fullchain.pem
  key_file: /path/to/privkey.pem
  # optionally: port_range_start: 50000, port_range_end: 60000
• Use the same TLS cert/domain that your clients connect to, or a valid cert for the TURN domain. 1. Adjust AWS load balancer & security groups • Ensure ALB/NLB forwards TCP 443 to your LiveKit instances and preserves WebSocket upgrades. • If using ALB (HTTP/HTTPS), terminate TLS there and configure target group to forward TCP 443 to instances; for TURN/TCP you may prefer an NLB passing through TCP 443. • Security groups: allow inbound TCP 443 and UDP 50000–60000 to the LiveKit instances. 1. Open and map UDP media ports • Ensure LiveKit’s media port range (default UDP 50000–60000) is allowed in the instance SG and any NAT/route. TURN/TLS on 443 covers restrictive clients, but media UDP should be open when possible. 1. Short tests to validate • From a failing client network run ConnectionCheck: checkWebsocket(), checkWebRTC(), checkTURN(). If checkTURN succeeds, connections should work. • Temporarily point clients to a known working public TURN to confirm behavior if you can’t enable embedded TURN immediately. 1. Short-term mitigations • Increase client-side connect retries/delays (you already have maxRetries: 5 — add small backoff). • Ensure your app doesn’t call disconnect() on slow negotiations (your logs showed user-initiated aborts; confirm UI/navigation isn’t cancelling joins). Notes on agents • Agent count is not causing the ICE failures — logs show agents join fine. Scale agents for redundancy only (≥2) if you rely on agent availability. If you’d like I can provide: • Exact example LiveKit config tuned for AWS (ALB vs NLB differences), • Steps to test TURN after you enable it, • Help interpreting ConnectionCheck output once you run it. Which would you like next? Sources: Connecting to LiveKit | LiveKit docs | Deploying LiveKit | LiveKit docs | Ports and firewall | LiveKit docs | Diagnosing Connection Errors with Connection Test Utility
g
how to find this: • Check for any code path that may call disconnect() on slow negotiation (ensure UI/navigation isn’t aborting the effect).
t
Good question — here’s a focused checklist to find and eliminate any code path that might call
disconnect()
during slow negotiation. 1) Grep/search for disconnect • Search the repo for
.disconnect(
,
room.disconnect(
,
disconnectRoom
, or any wrapper that calls disconnect. Inspect each hit for surrounding conditions or timers. 2) Audit React lifecycle and effects • Check useEffect cleanups: ensure effects that call
room.disconnect()
run only when truly unmounting, not on prop/state changes during join. • Example problematic pattern: effect dependency includes a changing value that triggers cleanup while negotiation is ongoing. • Look for conditional early returns in effects that call disconnect when connectionDetails is missing or stale. 3) Check navigation/routing events • Search for route changes or history.push listeners that call disconnect on navigation. • If using React Router, ensure you’re not calling disconnect in a top-level route change handler triggered while join is pending. 4) Inspect UI handlers and timeouts • Look for “Cancel”, “Back”, or modal close handlers that call disconnect. • Search for setTimeout, setInterval, or abort logic that aborts connects after X ms — increase or remove timeouts for testing. 5) Instrument the connect/disconnect path • Add logging around all disconnect calls showing timestamps, stack traces, and app state (room state, negotiation start time, user action). • Example log: console.debug('disconnect called', { reason, timestamp: Date.now(), room.state, negotiationStart }) 6) Log RTCPeerConnection lifecycle on client • Hook RTCPeerConnection events and log: ◦ icegatheringstatechange, iceconnectionstatechange, connectionstatechange, signalingstatechange • Correlate those with disconnect logs to see if disconnect occurs while state is still checking/gathering. 7) Guard disconnect calls • Temporarily wrap disconnect with a guard during debugging:
Copy code
const safeDisconnect = (reason) => {
  console.debug('safeDisconnect called', { reason, roomState: room.state });
  if (room.state === 'connected' || room.state === 'disconnected') {
    room.disconnect();
  } else {
    console.debug('skipping disconnect during negotiation');
  }
};
• Use this to detect and avoid disconnects mid-negotiation. 8) Reproduce with extended timeouts • Increase client-side retries/timeouts (add small delays between retries) and remove any auto-abort on slow joins to observe whether negotiation eventually completes. 9) Capture stack traces on disconnect • In dev builds, throw a synthetic Error inside each disconnect wrapper to get stack traces (catch and log) so you can identify the caller. 10) Correlate with server timestamps • Use a matching timestamp from client disconnect logs and server logs to correlate whether the client initiated the leave and why. If you want, paste the results of your repo search for disconnect calls or a short snippet of the effect that manages connect/disconnect and I’ll point out risky patterns and how to fix them.
g
but if i don't have turn, how is it working for most of the times and fails only some times?
t
Short answer: WebRTC succeeds most of the time because ICE can find a direct path (usually UDP) in many networks; it fails occasionally when a client is on a restrictive NAT/firewall or when UDP/TCP paths are blocked — and without TURN there is no fallback. Why it’s intermittent (concise): • ICE tries multiple paths in order: UDP → TCP → TURN. Most home/mobile networks allow UDP, so ICE succeeds quickly. • Some networks (corporate VPNs, certain mobile carriers, proxies, packet filters) block or drop UDP or non‑443 TCP, causing ICE UDP/TCP attempts to fail. • If TURN is unavailable, those clients have no relay path and the negotiation aborts. Different clients and networks produce different outcomes, so failures appear sporadic. What that means for your system: • No TURN = many clients connect fine, but any client behind a restrictive path will fail. Those failures appear "random" because they depend on client network conditions, not server load or agent count. Immediate recommendations: • Enable TURN (TURN/TLS on port 443 recommended) so clients behind restrictive networks can connect reliably. • Run ConnectionCheck from failing networks to confirm TURN is needed (checkWebRTC vs checkTURN). • Temporarily increase client-side timeouts/retries and avoid auto-cancelling connect while negotiation is ongoing to reduce false aborts. If you want, I can: • Provide an example LiveKit TURN config for AWS (ALB vs NLB) and exact SG/load-balancer rules, or • Help interpret ConnectionCheck output from one failing client. Which would you prefer? Sources: Connecting to LiveKit | LiveKit docs | Firewall Tips | Ports and firewall | LiveKit docs | Configuring firewalls | LiveKit docs | Diagnosing Connection Errors with Connection Test Utility
g
but on the same client, when i refresh the page, it works
t
That behavior is expected and here’s why — short and actionable. Why a refresh can make the join succeed • ICE is a best-effort process (UDP → TCP → TURN). On the first attempt the client may hit a blocked/unstable path (UDP or TCP). A refresh restarts ICE and sometimes finds a working path or the network state changes briefly, so the next attempt succeeds. • A retry may also end up using a different local candidate (different ephemeral port or IPv family) or the server/client NAT mapping may have changed, allowing the handshake to complete. • If TURN were available, the first failure would fall back to TURN reliably; without TURN some networks simply fail until a retry happens to use a path that works. What to check now (fast priorities) 1. Enable TURN/TLS (port 443) — this fixes all intermittent failures for restrictive networks. 2. Add logs to correlate events on failure vs success: ◦ Client: iceGatheringStateChange, iceConnectionStateChange, icecandidate, connectionstatechange, and timestamps. ◦ Server: matching join timestamp lines you already have. 1. Verify client logic doesn’t abort: ◦ Ensure no code (effect cleanup, navigation, timeout) calls room.disconnect() during negotiation. Temporarily guard disconnects and add a console log/stack trace when disconnect is called. 1. Add small retry/backoff on connect attempts instead of immediately aborting (you have maxRetries; add incremental delays). If you want I can: • Provide the exact LiveKit TURN config for AWS (ALB vs NLB) and security group rules, or • Review a short snippet of your disconnect handlers/effect cleanup and point out risky patterns. Which would you prefer? Sources: Firewall Tips | Configuring firewalls | LiveKit docs | Deploying LiveKit | LiveKit docs | Connecting to LiveKit | LiveKit docs | Diagnosing Connection Errors with Connection Test Utility