After users lose internet connection for couple se...
# ask-ai
s
After users lose internet connection for couple seconds and regain, agents stop working. Seems like agent can't reconnect
t
Thanks for reaching out, Alex. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
s
{"message": "livekit:rtc engine470livekit:rtc_engine - received session close: \"signal client closed: \\\"ping timeout\\\"\" UnknownReason Resume", "level": "WARNING", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113513.037176+00:00"} {"message": "livekit:rtc engine766livekit:rtc_engine - resuming connection... attempt: 0", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113513.038072+00:00"} {"message": "livekit:rtc enginertc session1032livekitrtc engine:rtc_session - Publisher pc state failed", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113515.334564+00:00"} {"message": "livekit:rtc engine470livekit:rtc_engine - received session close: \"pc_state failed\" UnknownReason Resume", "level": "WARNING", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113515.334806+00:00"} {"message": "livekit:rtc enginertc session1032livekitrtc engine:rtc_session - Subscriber pc state failed", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113515.632994+00:00"} {"message": "livekit:rtc engine470livekit:rtc_engine - received session close: \"pc_state failed\" UnknownReason Resume", "level": "WARNING", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113515.633273+00:00"} {"message": "livekit:rtc engine768livekit:rtc_engine - resuming connection failed: signal failure: ws failure: Connection closed normally", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113523.628799+00:00"} {"message": "livekit:rtc engine766livekit:rtc_engine - resuming connection... attempt: 1", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113523.628933+00:00"} {"message": "livekit:rtc engine768livekit:rtc_engine - resuming connection failed: signal failure: ws failure: Connection closed normally", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113524.457682+00:00"} {"message": "livekit:rtc engine766livekit:rtc_engine - resuming connection... attempt: 2", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113524.457898+00:00"} {"message": "livekit:rtc engine768livekit:rtc_engine - resuming connection failed: signal failure: ws failure: Connection closed normally", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113525.229147+00:00"} {"message": "livekit:rtc engine766livekit:rtc_engine - resuming connection... attempt: 3", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113525.229186+00:00"} {"message": "livekit:rtc engine768livekit:rtc_engine - resuming connection failed: signal failure: ws failure: Connection closed normally", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113526.017608+00:00"} {"message": "livekit:rtc engine766livekit:rtc_engine - resuming connection... attempt: 4", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113526.017817+00:00"} {"message": "livekit:rtc engine768livekit:rtc_engine - resuming connection failed: signal failure: ws failure: Connection closed normally", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113526.809344+00:00"} {"message": "livekit:rtc engine766livekit:rtc_engine - resuming connection... attempt: 5", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113526.809434+00:00"} {"message": "livekit:rtc engine768livekit:rtc_engine - resuming connection failed: signal failure: ws failure: Connection closed normally", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113527.577609+00:00"} {"message": "livekit:rtc engine766livekit:rtc_engine - resuming connection... attempt: 6", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113527.577703+00:00"} {"message": "livekit:rtc engine768livekit:rtc_engine - resuming connection failed: signal failure: ws failure: Connection closed normally", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113528.374202+00:00"} {"message": "livekit:rtc engine766livekit:rtc_engine - resuming connection... attempt: 7", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113528.374317+00:00"} {"message": "livekit:rtc engine768livekit:rtc_engine - resuming connection failed: signal failure: ws failure: Connection closed normally", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113529.143216+00:00"} {"message": "livekit:rtc engine766livekit:rtc_engine - resuming connection... attempt: 8", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113529.143442+00:00"} {"message": "livekit:rtc engine768livekit:rtc_engine - resuming connection failed: signal failure: ws failure: Connection closed normally", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113529.917976+00:00"} {"message": "livekit:rtc engine766livekit:rtc_engine - resuming connection... attempt: 9", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113529.918040+00:00"} {"message": "livekit:rtc engine768livekit:rtc_engine - resuming connection failed: signal failure: ws failure: Connection closed normally", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113530.688319+00:00"} {"message": "livekit:rtc engine692livekit:rtc_engine - failed to reconnect to the livekit room", "level": "ERROR", "name": "livekit", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113530.688395+00:00"} {"message": "process exiting", "level": "INFO", "name": "livekit.agents", "reason": "room disconnected", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113530.695087+00:00"} {"message": "skipping user input, speech scheduling is paused", "level": "WARNING", "name": "livekit.agents", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113532.702225+00:00"} {"message": "websocket closed unexpectedly", "level": "WARNING", "name": "livekit.plugins.elevenlabs", "pid": 80939, "job_id": "AJ_2xLs9RJCnxgf", "timestamp": "2025-12-05T113532.705553+00:00"} those are logs
t
Thanks — I reviewed the logs you sent and I’m responding about agents failing to reconnect after a short internet drop. What the logs show • The agent detected a ping timeout and attempted to resume the LiveKit session. • Multiple "resuming connection... attempt: N" attempts failed with "signal failure: ws failure: Connection closed normally". • The rtc engine reported both "Publisher pc state failed" and "Subscriber pc state failed" during resume attempts. • After repeated failures the agent process exited with "room disconnected" and speech scheduling paused. Likely causes • The WebSocket signaling connection is being closed during resume attempts so the SDK cannot complete the resume/ICE restart flow. • The peer connection state failures indicate the ICE restart or SDP exchange failed, so tracks couldn't be republished. • There may be insufficient retry/timeouts for the resume flow or the environment (proxy, firewall, or load balancer) is closing WS connections quickly. Immediate troubleshooting steps (please try in order) 1. Confirm agent handles reconnect events ◦ Ensure your agent code listens for
Reconnecting
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.
s
generate python code to test pls
t
Below is a concise Python test script that uses the LiveKit WebSocket signaling and aiortc to simulate connecting as a server-side agent, then programmatically closing the network (simulated by closing the WS) to exercise the SDK's resume/reconnect flow and log events like in your traces. Adjust
API_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:
Copy code
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.
s
I've meant only the connection event listeners pls
t
Below are minimal Python connection event listeners for LiveKit (server-side agent). Paste into your agent code where you have a
room
object.
Copy code
# 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 docs
s
One thing I've noticed is as soon as internet goes off, agent fires this log {"message": "worker is at full capacity, marking as unavailable", "level": "INFO", "name": "livekit.agents", "load": 0.8204, "threshold": "_WorkerEnvOption(dev_default=inf, prod_default=0.7)", "timestamp": "2025-12-06T102044.786277+00:00"} and after that it does not work. any reason ?
t
Thanks — I’m responding about the "worker is at full capacity, marking as unavailable" log you see immediately after the internet drop. Why this happens • That log means the agent’s load metric (shown as 0.8204) exceeded the configured load_threshold (default 0.7), so the agent was marked unavailable and stopped taking work. • Short network outages can spike the agent’s measured load (reconnect attempts, ICE restarts, republishing, thread/CPU activity), keeping it above threshold long enough to remain unavailable. • Once unavailable the agent won’t accept new room work and in your case the failed resume attempts plus WS closes prevented normal recovery. What you can do now (short, prioritized) 1. Check agent resource metrics right after an event ◦ Confirm CPU/memory actually spiked (host metrics) vs. load function being too sensitive. 1. If you run a custom deployment ◦ Raise
load_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 docs
I didn't receive any new details — do you want to (pick one): • Share whether agents run in a custom deployment or LiveKit Cloud? • Provide host CPU/memory metrics around the disconnect? • Confirm if there’s a proxy/load balancer or TURN server in your path? Tell me which and I’ll give the exact config/code changes to fix the "worker at full capacity" behavior.
I didn't receive your code—please paste the agent code (or the part that manages connection/reconnect and load checks). Focus on these files/sections if possible: • code that registers the
room
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.