what to do if my agent is occasionally disconnecti...
# ask-ai
k
what to do if my agent is occasionally disconnecting from the room
t
Thanks for reaching out, Ethan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're seeing occasional agent disconnects — I can help. To narrow this down quickly, please tell me: 1. When do disconnects occur? (during network blips, when the agent finishes work, after long idle periods, or randomly) 2. Any client/server error messages or events you see? (examples:
Reconnecting
,
Reconnected
,
JOIN_FAILURE
,
ROOM_DELETED
, shutdown timeout) 3. Are agents running on dedicated servers or sharing resources with other apps? How many agent servers are active? 4. Do you re-publish tracks or rely on automatic reconnection behavior after the agent reconnects? 5. Do you have SDK logs enabled (e.g., JavaScript
setLogExtension()
)? If so, can you share the recent log lines around a disconnect? What I’ll check or recommend once you reply: • Verify graceful shutdown handling and
shutdown_process_timeout
if disconnects happen during agent shutdown. • Confirm reconnection flow and whether you need UI state for `Reconnecting`/`Reconnected`. • Look for connection timeouts (room join >10s) and suggest running multiple agent servers, proper load balancing, or autoscaling. • Inspect ping/pong and keep-alive stability if disconnects look like signaling timeouts. Send the answers and any log excerpts and I’ll provide targeted next steps. Sources: Job lifecycle | LiveKit docs | Connecting to LiveKit | LiveKit docs | Troubleshooting Guide | livekit/livekit_composite | DeepWiki | SIP troubleshooting guide | LiveKit docs | Agent dispatch | LiveKit docs
k
I occasionally get agent left room due to CONNECTION_TIMEOUT (not every time) agents are running in GCP us-central1. there are 4 servers running across 3 zones I don't do anything special beyond the default for reconnection. my participants join via sip
t
Thanks — this is helpful. Since the disconnects are occasional and show as CONNECTION_TIMEOUT, focus on these targeted steps to stabilize agents in your GCP us-central1 setup. 1) Check join latency and load • Measure how long agents take to establish the room connection when the timeout happens. If joins sometimes exceed ~10s, add capacity or reduce startup work. • Verify CPU, memory, and thread usage on the 4 servers during incidents. High contention causes slow joins. 2) Network & placement • Confirm low packet loss and stable latency between agents and the LiveKit server. Run periodic pings/traceroutes from each zone during peak times. • Consider serving agents from the same region as your LiveKit instance or using regional endpoints if available to reduce latency and avoid cross-zone variability. 3) Load balancing & autoscaling • Ensure your load balancer evenly distributes new joins and health checks are tuned so unhealthy instances are removed quickly. • Add autoscaling so new agent instances spin up before capacity is exhausted. 4) SIP dispatch and agent assignment • Ensure SIP dispatch rules and
agent_name
matching are consistent so agents aren’t delayed by dispatch retries. • If SIP participants cause bursts, smooth arrival rate or pre-warm idle agents. 5) Keep-alive and timeouts • Confirm ping/pong connectivity (5s ping / 15s timeout behavior) and watch for signaling stalls. • If joins regularly hit 10s, move any heavy initialization out of the join path so the connection can complete faster. 6) Reconnection behavior & UX • Continue to rely on automatic reconnection, but handle
Reconnecting
UI state so users know there may be a pause while the agent re-publishes tracks. • If you need faster recovery, implement explicit logic to re-create or re-publish tracks sooner after a reconnect completes. 7) Logging to pinpoint root cause • Enable detailed SDK logs (use
setLogExtension()
for JS) and capture timestamps around the CONNECTION_TIMEOUT events. • Collect server-side logs correlated with the agent’s identity and exact timestamps to see if resource spikes or LB health checks align with the timeouts. If you want, share: • One example timestamp (UTC) of a CONNECTION_TIMEOUT and the agent server it hit • Recent SDK log lines around that event I’ll identify the most likely cause and recommend the exact next change.
k
does livekit websocket interface have regional endpoints? i only know about livekit's regional sip endpoints
"Confirm ping/pong connectivity (5s ping / 15s timeout behavior) and watch for signaling stalls." explain
t
Thanks — I’ll explain ping/pong briefly and then confirm I need one detail to answer the regional-endpoint question. Regarding ping/pong (5s/15s) • The LiveKit server sends a WebSocket ping every 5 seconds. The client must reply with a pong within 15 seconds. • If no pong is received within 15 seconds, the server treats the signaling connection as stalled and disconnects the client (this can appear as CONNECTION_TIMEOUT). • This detects signaling/control-channel failures, not media (RTP/ICE) issues. • What to check: ◦ Ensure the client can process pings promptly (avoid blocking the event loop or long synchronous work). ◦ Look for packet loss, high latency, or transient network outages between your agents and the server. ◦ Correlate timeouts with CPU/Garbage Collection spikes, load balancer behavior, or network errors in server/client logs. Regional WebSocket endpoints — one detail I need Please tell me whether you’re using LiveKit Cloud (managed/livekit.cloud) or a self-hosted LiveKit deployment, and which client/SDK you use (JS, iOS, Android, raw WebSocket, or SIP gateway). With that I’ll confirm whether protocol-based region pinning is available for your setup and the exact steps to enable or configure it. Sources: LiveKit Server Platform | livekit/livekit_composite | DeepWiki | Connecting to LiveKit | LiveKit docs
k
managed
t
Thanks — two concise points based on your managed LiveKit setup. 1) Regional WebSocket behavior • LiveKit Cloud does not use DNS-style regional WebSocket endpoints like SIP. Instead it offers protocol-based region pinning: you can restrict WebSocket/signaling connections to one or more regions (e.g.,
us
,
eu
,
asia
,
aus
,
uk
, etc.). • Region pinning is available on the Scale plan or higher and must be enabled for your project. Once enabled, a connection routed outside the pinned region is rejected and the client retries within the allowed region. Note: enabling pinning disables automatic failover to other regions during outages. 2) Ping/pong (5s ping / 15s timeout) — what it means and what to check • The server sends a WebSocket ping every 5 seconds; the client must respond with a pong within 15 seconds. If no pong arrives in 15s, the server treats the signaling connection as stalled and disconnects (this can surface as CONNECTION_TIMEOUT). • What to verify: ◦ Clients process pings promptly (avoid blocking the event loop or long synchronous work). ◦ Watch for CPU spikes or GC pauses on agent servers that might delay pong responses. ◦ Monitor packet loss and latency between your GCP us-central1 agents and the LiveKit cluster. ◦ Check load balancer behavior and health checks that might affect connection stability. ◦ Correlate CONNECTION_TIMEOUT timestamps with server/client logs and SDK logs (
setLogExtension()
on JS) to spot patterns. If you want, I can: • Confirm the exact regions available for your account and the steps to enable protocol-based region pinning for your project. • Review one CONNECTION_TIMEOUT event if you share a UTC timestamp and the agent server that handled it.
k
CONNECTION_TIMEOUT event: {id: "AE_MzxuQgDsW3hm" project_id: "p_1cdfi1ss0et" room_id: "RM_QJ6FLGsMARRQ" timestamp: "2025-11-25T210508Z" type: "Participant left (CONNECTION_TIMEOUT)" participant_id: "PA_yrQ2NXUHqwM3" participant_identity: "agent-AJ_KpUx6fd5QbDE" node_id: "NM_OCHICAGO1B_VAktr4sKabAZ" timestamp_us: 1764104708268598 disconnect_reason: "CONNECTION_TIMEOUT" }
t
Thanks — I reviewed the CONNECTION_TIMEOUT event you shared (agent identity, room, node NM_OCHICAGO1B, timestamp 2025-11-25T210508Z). Summary and focused next steps below. Why this happened (short) • The server didn’t receive a WebSocket pong within the 15s timeout after sending pings every 5s, so it treated the signaling connection as stalled and disconnected the participant as CONNECTION_TIMEOUT. • Likely causes: transient network issues (packet loss, high latency), the client/agent not processing pings promptly (CPU/GC or event-loop stalls), or intermittent load-balancer/network behavior routing the agent to the Chicago node. Targeted checks to run now • Run the connection test from the same VM that runs the agent to reproduce network checks: npx @livekit/connection-test --url=wss://<your-subdomain>.livekit.cloud --token=<agent-token> Capture results and any failures for WebSocket/TURN checks. • Correlate timestamps: ◦ Pull agent-side SDK logs and server logs around 2025-11-25T210500–210600Z. Look for ping/pong timestamps, onclose/onerror, GC or CPU spikes, and LB health-check events. • Measure network health from that VM at the same time window: ◦ Run pings/traceroutes to the LiveKit ingress, and check packet loss and RTT jitter. ◦ Check VPC flow logs for dropped or reset connections. • Inspect agent resource metrics: ◦ CPU, memory, GC pause durations (if applicable), and event-loop latency during the disconnect. • Load balancer and routing: ◦ Confirm the LB didn’t route traffic through a different region or apply time-consuming health checks at that time. Note the event shows node NM_OCHICAGO1B — verify whether routing changes or overloads affected that PoP. • Keepalive behavior validation: ◦ Ensure the agent process can promptly handle incoming pings (no long synchronous work on the same thread that handles WebSocket events). ◦ If using a language/runtime with GC, check for pauses coincident with the timeout. Mitigations to apply • Add lightweight pings/pong instrumentation in the agent to log ping received and pong sent timestamps. • If you observe join latency spikes, move heavy initialization off the join path and pre-warm agent processes. • Scale or autoscale agent capacity so joins and heartbeats aren’t delayed by resource contention. • If network issues persist, consider enabling protocol-based region pinning (Scale plan) to force connections into a closer PoP, understanding it disables automatic cross-region failover. If you’d like, share: • Agent SDK log snippet around 2025-11-25T210508Z (ping/pong lines, onclose/onerror) • Connection test output from the VM that hosts that agent I’ll analyze those and recommend the most likely root cause and next configuration changes. Sources: LiveKit Server Platform | livekit/livekit_composite | DeepWiki | Region pinning | LiveKit docs | SIP cloud and region pinning | LiveKit docs | Ports and firewall | LiveKit docs | Configuring firewalls | LiveKit docs
k
how to avoid agent disconnections?
t
Good — below are focused, actionable steps to reduce agent disconnects and prevent CONNECTION_TIMEOUTs. 1) Ensure WebSocket keepalive responsiveness • Make sure the agent process can promptly handle pings (server pings every 5s; pong required within 15s). Avoid long synchronous work on the thread/event loop that handles WebSocket messages. • Add lightweight instrumentation: log timestamps for received pings and sent pongs. 2) Stabilize network between agents and LiveKit • Run periodic checks from each agent VM: ping/traceroute to your LiveKit subdomain, and the LiveKit connection test: npx @livekit/connection-test --url=wss://<your-subdomain>.livekit.cloud --token=<agent-token> • Monitor packet loss, RTT jitter, and transient drops; fix routing/NAT/proxy issues, firewall or TCP reset behavior that can interrupt long-lived WebSockets. 3) Reduce resource contention on agent hosts • Monitor CPU, memory, GC pauses, and event-loop latency. Correlate spikes with disconnect timestamps. • Move heavy initialization or processing off the join/keepalive path; pre-warm agents so joins and heartbeats are fast. 4) Load balancing, scaling, and placement • Ensure the load balancer evenly distributes connections and removes unhealthy instances quickly. • Autoscale agent capacity to avoid bursts that push instances into contention. • Deploy agents in the same region as LiveKit edge/PoP when possible to reduce latency variability. 5) Handle reconnection and session resilience • Implement reconnect with backoff and token refresh logic; re-publish tracks after
Reconnected
. • Show
Reconnecting
UI/state so users expect short pauses during full reconnection flows. 6) Use region pinning (managed LiveKit, Scale+) • If network variability across PoPs is a factor, enable protocol-based region pinning to force connections into a chosen region (note: this disables automatic failover). 7) Tune graceful shutdown • Ensure graceful shutdown completes quickly (default 60s). If cleanup is longer, either shorten shutdown tasks or increase
shutdown_process_timeout
on agent servers. 8) Increase observability and correlation • Enable SDK logs (
setLogExtension()
for JS) and server logs; capture ping/pong, onclose/onerror, and system metrics around disconnection times. • Correlate LiveKit event timestamps (node_id and event time) with agent VM metrics, LB logs, and VPC flow logs to find root cause patterns. If you want, I can: • Review one agent-side log snippet (ping/pong and onclose) plus the connection-test output for the VM that hit the timeout and give a prioritized remediation.
k
i doubt its actually disconnected since i have other calls that work around these calls. what could be the issue? <50% cpu usage and <30% memory usage on resources
t
Good question — since CPU and memory look fine, CONNECTION_TIMEOUT often comes from signaling/network or orchestration issues rather than host resource exhaustion. Possible causes and focused checks: Possible causes • Intermittent packet loss, high RTT, or jitter between the agent VM and LiveKit ingress causing missed pongs. • Event-loop/GC pauses or brief thread blocking that delay pong handling even at low overall CPU. • Load balancer or NAT timeouts, TCP resets, or proxy behavior interrupting long-lived WebSocket connections. • Region routing variability (agent routed to a different PoP) causing transient latency spikes. • SIP dispatch or participant-token timing causing delayed joins/retries. • Token expiry or token-refresh race that prevents quick reconnects. Immediate checks to run • Run the connection test from the exact VM: npx @livekit/connection-test --url=wss://<your-subdomain>.livekit.cloud --token=<agent-token> • Capture ping/pong timestamps on the agent (log when ping received and pong sent) around a failure. • Check VPC flow logs and LB logs for TCP resets or dropped connections at the timestamp of the timeout. • Measure packet loss and jitter (continuous ping/iperf) from that VM to the LiveKit host at the same times. • Inspect event-loop latency/GC pause metrics even if CPU is low (use node’s event-loop delay or similar). • Verify tokens are valid at reconnect time and SIP dispatch rules aren’t delaying assignment. Quick mitigations • Add lightweight ping/pong instrumentation and alert when pong latency >5s. • Move any blocking work off the WebSocket handler thread and pre-warm agents. • Tune LB health checks and avoid aggressive idle timeouts or proxies that reset TCP. • Consider protocol-based region pinning if routing variance is suspected (Scale plan). If you share: • One SDK log snippet around a recent CONNECTION_TIMEOUT (ping/pong and onclose/onerror) and • The connection-test output from that VM, I’ll analyze and point to the most likely root cause.
k
are there timeouts on the agent side that could be affecting this?
t
You're right to suspect agent-side timeouts can play a role. Short answer: yes—there are agent-side behaviors and time windows that can cause or appear as CONNECTION_TIMEOUTs. Below I’ll list the most relevant ones and what to check or change. Key agent-side timeouts/behaviors to check • WebSocket keepalive (ping/pong) ◦ Server pings every 5s; a pong must arrive within 15s. If the agent blocks the event loop or is paused (GC, synchronous work), pongs can be delayed and trigger CONNECTION_TIMEOUT. ◦ What to do: instrument and log ping-receive and pong-send timestamps in the agent. • Dispatch / job acceptance window ◦ Agents must accept a dispatched JobRequest promptly (delays or failing to call
req.accept()
can cause the client to time out or the dispatch to fail). ◦ What to do: ensure
on_request
handlers accept quickly and defer heavy work to
setup_fnc
or a background task. • Room-join / connection latency ◦ LiveKit Cloud enforces a short connection window (commonly seen as ~10s) from dispatch to a joined room. Long initialization or cold-starts can exceed this. ◦ What to do: prewarm models, move heavy initialization out of the join path, use sustained-performance instances. • Graceful shutdown / drain behavior ◦ If servers are draining or being redeployed often, available capacity drops and dispatch/joins can be delayed. ◦ What to do: verify drain timing, stagger deployments, and keep enough warmed agents. • Token expiry / reconnect timing ◦ Reconnect attempts must present valid tokens; token expiry or racey refresh logic can prevent quick reconnects. ◦ What to do: ensure tokens are valid during reconnect windows or refresh preemptively. • Agent load reporting and load_threshold ◦ If the agent reports a high load, it may be skipped for dispatch, producing delays elsewhere. ◦ What to do: verify
load_fnc
output and adjust
load_threshold
or capacity. Diagnostics to run now (high priority) 1. Add ping/pong logs in the agent and capture a recent timeout window (log ping received time and pong sent time). 2. Extract the time from dispatch →
req.accept()
→ room join for a sample timeout event. 3. Run the connection test from the same VM: npx @livekit/connection-test --url=wss://<your-subdomain>.livekit.cloud --token=<agent-token> 1. Capture agent VM metrics (event-loop delay, GC pause times, CPU steal) and LB/VPC flow logs for the event timestamp. Quick mitigations • Prewarm and move heavy tasks off the join/keepalive path. • Ensure agent code never runs long blocking work on the thread that handles WebSocket events. • Instrument pings/pongs and alert if pong latency exceeds a few seconds. • Scale or autoscale to avoid dispatch queuing and cold starts. • If routing variance is suspected, consider protocol-based region pinning (Scale plan) to constrain which PoP handles the WebSocket. If you want, share: • A short agent log snippet showing ping/pong and onclose around one of your recent CONNECTION_TIMEOUTs, and • The connection-test output from that VM. I’ll analyze them and point to the most likely agent-side timeout or behavior to fix. Sources: Agent server options | LiveKit docs | Troubleshooting Latency and Timeout Errors with Turn Detection on AWS | LiveKit Server Platform | livekit/livekit_composite | DeepWiki | Connecting to LiveKit | LiveKit docs | Quotas and limits | LiveKit docs
k
i'm not sure what to say other than that the agent disconnected from the livekit server. how can i make sure it stays connected?
t
I hear you — you just want the agent to stay connected. Here’s a short, prioritized checklist you can follow now to keep agents reliably connected. 1) Make sure pings get answered • Log when your agent receives ping and when it sends pong. If pong is delayed >5s, fix it. • Avoid blocking the WebSocket handler: move heavy work off the event-loop/thread that handles signaling. 2) Eliminate cold-starts / slow joins • Prewarm models and initialization so the agent joins quickly. • Move heavy setup out of the join path (use background tasks or `prewarm`/`setup_fnc`). 3) Keep network stable • Run the connection test from the agent VM: npx @livekit/connection-test --url=wss://<your-subdomain>.livekit.cloud --token=<agent-token> • Monitor packet loss, RTT jitter, and TCP resets (VPC flow logs, LB logs, traceroute). • Ensure firewalls/proxies don’t reset idle WebSockets. 4) Confirm dispatch responsiveness • Ensure
on_request
handlers call
req.accept()
promptly; avoid blocking there. • If dispatch latency spikes, add more agent capacity or adjust load thresholds. 5) Scale and placement • Autoscale agents to avoid contention; deploy agents in the same region/PoP as LiveKit when possible. • Consider protocol-based region pinning (Scale plan) if routing variance is suspected. 6) Reconnect & token handling • Implement reconnect with backoff and refresh tokens proactively so reconnects succeed. • On `Reconnecting`/`Reconnected`, re-publish tracks as needed. 7) Observability (must-have) • Enable SDK logs (
setLogExtension()
for JS) and server logs; capture ping/pong, onclose, onerror with timestamps. • Correlate LiveKit event timestamp/node_id with agent VM metrics and LB/VPC logs. If you want a quick next step, share: • One agent log snippet around a recent disconnect (ping/pong/onclose) and • The connection-test output from that VM I’ll analyze those and give the single highest-impact change to keep that agent connected.