swift-yacht-23770
12/05/2025, 4:48 PMtall-airline-16756
12/05/2025, 4:48 PMswift-yacht-23770
12/05/2025, 4:48 PMtall-airline-16756
12/05/2025, 4:48 PMReconnecting and Reconnected events and does not forcibly tear down the PeerConnection when Reconnecting fires.
1. Increase timeouts/retries for resume
◦ Allow a longer window before giving up on resume (increase retry attempts or backoff limits) so brief network blips can recover.
1. Check WebSocket stability/path
◦ Verify proxies/load balancers or firewalls between agent and LiveKit aren’t terminating idle/short-lived WS connections. If they are, enable keepalives or increase idle timeouts.
1. Verify ICE restart succeeds
◦ Confirm the agent can perform an ICE restart. If you see repeated "pc_state failed" across both publisher/subscriber, check TURN server availability and ICE candidate exchange logging.
1. Capture client-side logs and network traces
◦ Collect browser/agent-side WebRTC logs and the WS frames during a disconnection/reconnect attempt to see why signaling is closing "normally".
1. Ensure agent restarts or recovers cleanly
◦ If the agent exits after failed resume, ensure you have logic to rejoin or restart the worker process so it can reconnect to the room.
Targeted questions to narrow this down
• Are these agents running server-side (Node/Rust/Python) or in browsers?
• Do you use a TURN server, and are TURN logs showing allocation failures during the events?
• Is there a proxy/load balancer (e.g., nginx, Cloud LB) in front of LiveKit or the agents that might close idle WS connections?
• Do these failures affect all agents or only some hosts/regions?
If you share the agent type (server/browser), how signaling is proxied (if at all), and whether TURN is configured, I’ll suggest exact config changes and the specific logs/network traces to capture next.swift-yacht-23770
12/05/2025, 4:49 PMtall-airline-16756
12/05/2025, 4:50 PMAPI_KEY, API_SECRET, URL, and room/participant names to match your environment.
Requirements:
• Python 3.9+
• aiohttp
• aiortc
• pyjwt
Install: pip install aiohttp aiortc pyjwt
Script:
import asyncio
import json
import jwt
import time
import logging
from aiohttp import ClientSession, WSMsgType, TCPConnector
from aiortc import RTCPeerConnection, RTCSessionDescription, MediaStreamTrack
# Configure
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
LIVEKIT_URL = "https://your-livekit-server.com" # no trailing slash
ROOM = "test-room"
SID = "agent-sid" # participant identity
LOG = logging.getLogger("agent_test")
logging.basicConfig(level=logging.INFO)
def mk_token(api_key, api_secret, room, identity, ttl=60):
now = int(time.time())
payload = {
"jti": f"{identity}-{now}",
"iss": api_key,
"sub": room,
"nbf": now,
"exp": now + ttl,
"name": identity,
}
token = jwt.encode(payload, api_secret, algorithm="HS256")
return token
class DummyTrack(MediaStreamTrack):
kind = "audio"
async def recv(self):
await asyncio.sleep(0.02)
return None
async def run_test(simulate_drop_after=5, resume_delay=3):
token = mk_token(API_KEY, API_SECRET, ROOM, SID, ttl=300)
ws_url = f"{LIVEKIT_URL.replace('https','wss').replace('http','ws')}/rtc?access_token={token}&protocol=8"
LOG.info("Connecting to %s", ws_url)
conn = TCPConnector(force_close=True)
async with ClientSession(connector=conn) as session:
async with session.ws_connect(ws_url, heartbeat=30) as ws:
pc = RTCPeerConnection()
# simple local track so republish path runs
pc.addTrack(DummyTrack())
async def handle_ws_messages():
async for msg in ws:
if msg.type == WSMsgType.TEXT:
data = json.loads(msg.data)
LOG.info("WS RX: %s", data.get("type", data))
elif msg.type == WSMsgType.ERROR:
LOG.error("WS error: %s", msg)
break
msg_task = asyncio.create_task(handle_ws_messages())
# create local offer (minimal) to exercise publisher flow
offer = await pc.createOffer()
await pc.setLocalDescription(offer)
LOG.info("Created local offer")
# send a simplified Join/Offer message to trigger server flows
join_payload = {
"type": "join",
"room": ROOM,
"sid": SID,
"client": {"protocol": 8},
"offer": {"sdp": pc.localDescription.sdp, "type": pc.localDescription.type}
}
await ws.send_str(json.dumps(join_payload))
LOG.info("Sent join/offer to server")
# let things run, then simulate network drop by closing WS
await asyncio.sleep(simulate_drop_after)
LOG.warning("Simulating network drop: closing websocket")
await ws.close(code=1000, message=b"simulate drop")
# wait resume_delay then reconnect (simulate network restored)
await asyncio.sleep(resume_delay)
LOG.info("Reopening websocket to attempt resume")
# open a fresh websocket (new session) — in real resume the client may attempt resume with same token and resume flag
async with session.ws_connect(ws_url, heartbeat=30) as ws2:
async for i in range(3):
await asyncio.sleep(1)
LOG.info("Testing post-drop signaling ping %d", i)
await ws2.close()
# cleanup
msg_task.cancel()
await pc.close()
LOG.info("Test complete")
if __name__ == "__main__":
asyncio.run(run_test())
Notes and how to use
• This script intentionally uses a simplified signaling exchange to exercise join/offer flows and to create the same kind of WS close/resume behavior you saw in logs.
• To replicate your environment more closely:
◦ Use the same client library codepath you run in production (if available) and simulate network interruption by temporarily disabling the host interface or closing the WS.
◦ Increase logging inside your agent's LiveKit client to capture Reconnecting, Resuming, and pc_state events.
• If you want, tell me whether your agents are running with a proxy/NGINX or behind a load balancer and I can adapt the script to repeatedly try resume using the LiveKit resume protocol details.swift-yacht-23770
12/05/2025, 4:52 PMtall-airline-16756
12/05/2025, 4:52 PMroom object.
# connection event listeners for LiveKit Python client
@room.on("reconnecting")
def on_reconnecting():
print("Reconnecting to the room...")
@room.on("reconnected")
def on_reconnected():
print("Reconnected to the room")
@room.on("disconnected")
def on_disconnected():
print("Disconnected from the room")
@room.on("resuming")
def on_resuming():
print("Resuming session")
@room.on("resume_failed")
def on_resume_failed():
print("Resume failed; will attempt full reconnect or exit")
If you want, tell me which SDK/library version you use and I’ll adapt names/signatures to match it.
Sources: Handling events | LiveKit docs | Handling DTMF | LiveKit docsswift-yacht-23770
12/06/2025, 10:24 AMtall-airline-16756
12/06/2025, 10:24 AMload_threshold or adjust load_fnc to use a less-sensitive metric or longer averaging window.
◦ Ensure agent process restarts or requeues jobs if resume fails.
1. If behind a proxy/ALB
◦ Ensure WebSocket keepalives/idle timeouts are long enough so signaling isn’t closed during resume attempts.
1. Tune reconnect behavior
◦ Allow longer resume retry/backoff so brief blips can recover before marking unavailable.
1. Confirm TURN and ICE behavior
◦ Verify TURN allocations are available during reconnection and check pc_state failures in logs.
Quick clarifying questions to recommend exact changes
• Are you running LiveKit Agents in a custom deployment or LiveKit Cloud?
• Do you have host CPU/memory metrics around the event (spike present?) or only the agent load value?
• Is there a proxy/load balancer between agents and LiveKit?
Tell me those details and I’ll give the exact config snippets or code changes to adjust `load_threshold`/`load_fnc` or the reconnection timings.
Sources: Agent server options | LiveKit docs | Deploying to custom environments | LiveKit docs | Agent insights in LiveKit Cloud | LiveKit docstall-airline-16756
12/06/2025, 10:43 AMtall-airline-16756
12/06/2025, 10:43 AMroom event listeners (reconnecting, reconnected, resuming, disconnected)
• any custom load_fnc or load_threshold settings
• reconnection/backoff logic or where you close/restart the PeerConnection
If you prefer, paste only the relevant functions (up to ~200 lines) and I’ll review for issues.